Debian Codegraph @

llvm-project/llvm/projects/llvm-spirv/lib/SPIRV/SPIRVWriter.cpp

raw
1 //===- SPIRVWriter.cpp - Converts LLVM to SPIR-V ----------------*- C++ -*-===//
2 //
3 // The LLVM/SPIR-V Translator
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 // Copyright (c) 2014 Advanced Micro Devices, Inc. All rights reserved.
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining a
11 // copy of this software and associated documentation files (the "Software"),
12 // to deal with the Software without restriction, including without limitation
13 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
14 // and/or sell copies of the Software, and to permit persons to whom the
15 // Software is furnished to do so, subject to the following conditions:
16 //
17 // Redistributions of source code must retain the above copyright notice,
18 // this list of conditions and the following disclaimers.
19 // Redistributions in binary form must reproduce the above copyright notice,
20 // this list of conditions and the following disclaimers in the documentation
21 // and/or other materials provided with the distribution.
22 // Neither the names of Advanced Micro Devices, Inc., nor the names of its
23 // contributors may be used to endorse or promote products derived from this
24 // Software without specific prior written permission.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28 // CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
31 // THE SOFTWARE.
32 //
33 //===----------------------------------------------------------------------===//
34 /// \file
35 ///
36 /// This file implements conversion of LLVM intermediate language to SPIR-V
37 /// binary.
38 ///
39 //===----------------------------------------------------------------------===//
40
41 #include "SPIRVWriter.h"
42 #include "LLVMToSPIRVDbgTran.h"
43 #include "OCLToSPIRV.h"
44 #include "PreprocessMetadata.h"
45 #include "SPIRVAsm.h"
46 #include "SPIRVBasicBlock.h"
47 #include "SPIRVEntry.h"
48 #include "SPIRVEnum.h"
49 #include "SPIRVExtInst.h"
50 #include "SPIRVFunction.h"
51 #include "SPIRVInstruction.h"
52 #include "SPIRVInternal.h"
53 #include "SPIRVLLVMUtil.h"
54 #include "SPIRVLowerBitCastToNonStandardType.h"
55 #include "SPIRVLowerBool.h"
56 #include "SPIRVLowerConstExpr.h"
57 #include "SPIRVLowerMemmove.h"
58 #include "SPIRVLowerOCLBlocks.h"
59 #include "SPIRVLowerSaddWithOverflow.h"
60 #include "SPIRVMDWalker.h"
61 #include "SPIRVMemAliasingINTEL.h"
62 #include "SPIRVModule.h"
63 #include "SPIRVRegularizeLLVM.h"
64 #include "SPIRVType.h"
65 #include "SPIRVUtil.h"
66 #include "SPIRVValue.h"
67 #include "VectorComputeUtil.h"
68
69 #include "llvm/ADT/DenseMap.h"
70 #include "llvm/ADT/StringSwitch.h"
71 #include "llvm/ADT/Triple.h"
72 #include "llvm/Analysis/LoopAnalysisManager.h"
73 #include "llvm/Analysis/LoopInfo.h"
74 #include "llvm/Analysis/ValueTracking.h"
75 #include "llvm/IR/Constants.h"
76 #include "llvm/IR/DerivedTypes.h"
77 #include "llvm/IR/Dominators.h"
78 #include "llvm/IR/Function.h"
79 #include "llvm/IR/InlineAsm.h"
80 #include "llvm/IR/InstrTypes.h"
81 #include "llvm/IR/Instructions.h"
82 #include "llvm/IR/IntrinsicInst.h"
83 #include "llvm/IR/Module.h"
84 #include "llvm/IR/Operator.h"
85 #include "llvm/IR/TypedPointerType.h"
86 #include "llvm/Pass.h"
87 #include "llvm/Passes/PassBuilder.h"
88 #include "llvm/Support/Casting.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Transforms/Utils/LoopSimplify.h"
92 #include "llvm/Transforms/Utils/Mem2Reg.h"
93
94 #include <cstdlib>
95 #include <functional>
96 #include <iostream>
97 #include <memory>
98 #include <queue>
99 #include <regex>
100 #include <set>
101 #include <vector>
102
103 #define DEBUG_TYPE "spirv"
104
105 using namespace llvm;
106 using namespace SPIRV;
107 using namespace OCLUtil;
108
109 namespace {
110
111 static SPIRVWord convertFloatToSPIRVWord(float F) {
112 union {
113 float F;
114 SPIRVWord Spir;
115 } FPMaxError;
116 FPMaxError.F = F;
117 return FPMaxError.Spir;
118 }
119
120 } // namespace
121
122 namespace SPIRV {
123
124 static void foreachKernelArgMD(
125 MDNode *MD, SPIRVFunction *BF,
126 std::function<void(const std::string &Str, SPIRVFunctionParameter *BA)>
127 Func) {
128 for (unsigned I = 0, E = MD->getNumOperands(); I != E; ++I) {
129 SPIRVFunctionParameter *BA = BF->getArgument(I);
130 Func(getMDOperandAsString(MD, I).str(), BA);
131 }
132 }
133
134 static void foreachKernelArgMD(
135 MDNode *MD, SPIRVFunction *BF,
136 std::function<void(Metadata *MDOp, SPIRVFunctionParameter *BA)> Func) {
137 for (unsigned I = 0, E = MD->getNumOperands(); I != E; ++I) {
138 SPIRVFunctionParameter *BA = BF->getArgument(I);
139 Func(MD->getOperand(I), BA);
140 }
141 }
142
143 static SPIRVMemoryModelKind getMemoryModel(Module &M) {
144 auto *MemoryModelMD = M.getNamedMetadata(kSPIRVMD::MemoryModel);
145 if (MemoryModelMD && (MemoryModelMD->getNumOperands() > 0)) {
146 auto *Ref0 = MemoryModelMD->getOperand(0);
147 if (Ref0 && Ref0->getNumOperands() > 1) {
148 auto &&ModelOp = Ref0->getOperand(1);
149 auto *ModelCI = mdconst::dyn_extract<ConstantInt>(ModelOp);
150 if (ModelCI && (ModelCI->getValue().getActiveBits() <= 64)) {
151 auto Model = static_cast<SPIRVMemoryModelKind>(ModelCI->getZExtValue());
152 return Model;
153 }
154 }
155 }
156 return SPIRVMemoryModelKind::MemoryModelMax;
157 }
158
159 static void translateSEVDecoration(Attribute Sev, SPIRVValue *Val) {
160 assert(Sev.isStringAttribute() &&
161 Sev.getKindAsString() == kVCMetadata::VCSingleElementVector);
162
163 auto *Ty = Val->getType();
164 assert((Ty->isTypeBool() || Ty->isTypeFloat() || Ty->isTypeInt() ||
165 Ty->isTypePointer()) &&
166 "This decoration is valid only for Scalar or Pointer types");
167
168 if (Ty->isTypePointer()) {
169 SPIRVWord IndirectLevelsOnElement = 0;
170 Sev.getValueAsString().getAsInteger(0, IndirectLevelsOnElement);
171 Val->addDecorate(DecorationSingleElementVectorINTEL,
172 IndirectLevelsOnElement);
173 } else
174 Val->addDecorate(DecorationSingleElementVectorINTEL);
175 }
176
177 LLVMToSPIRVBase::LLVMToSPIRVBase(SPIRVModule *SMod)
178 : BuiltinCallHelper(ManglingRules::None), M(nullptr), Ctx(nullptr),
179 BM(SMod), SrcLang(0), SrcLangVer(0) {
180 DbgTran = std::make_unique<LLVMToSPIRVDbgTran>(nullptr, SMod, this);
181 }
182
183 LLVMToSPIRVBase::~LLVMToSPIRVBase() {
184 for (auto *I : UnboundInst)
185 I->deleteValue();
186 }
187
188 bool LLVMToSPIRVBase::runLLVMToSPIRV(Module &Mod) {
189 M = &Mod;
190 initialize(Mod);
191 CG = std::make_unique<CallGraph>(Mod);
192 Ctx = &M->getContext();
193 DbgTran->setModule(M);
194 assert(BM && "SPIR-V module not initialized");
195 translate();
196 return true;
197 }
198
199 SPIRVValue *LLVMToSPIRVBase::getTranslatedValue(const Value *V) const {
200 auto Loc = ValueMap.find(V);
201 if (Loc != ValueMap.end())
202 return Loc->second;
203 return nullptr;
204 }
205
206 bool LLVMToSPIRVBase::isKernel(Function *F) {
207 if (F->getCallingConv() == CallingConv::SPIR_KERNEL)
208 return true;
209 return false;
210 }
211
212 bool LLVMToSPIRVBase::isBuiltinTransToInst(Function *F) {
213 StringRef DemangledName;
214 if (!oclIsBuiltin(F->getName(), DemangledName) &&
215 !isDecoratedSPIRVFunc(F, DemangledName))
216 return false;
217 SPIRVDBG(spvdbgs() << "CallInst: demangled name: " << DemangledName.str()
218 << '\n');
219 return getSPIRVFuncOC(DemangledName) != OpNop;
220 }
221
222 bool LLVMToSPIRVBase::isBuiltinTransToExtInst(
223 Function *F, SPIRVExtInstSetKind *ExtSet, SPIRVWord *ExtOp,
224 SmallVectorImpl<std::string> *Dec) {
225 StringRef DemangledName;
226 if (!oclIsBuiltin(F->getName(), DemangledName))
227 return false;
228 LLVM_DEBUG(dbgs() << "[oclIsBuiltinTransToExtInst] CallInst: demangled name: "
229 << DemangledName << '\n');
230 StringRef S = DemangledName;
231 if (!S.startswith(kSPIRVName::Prefix))
232 return false;
233 S = S.drop_front(strlen(kSPIRVName::Prefix));
234 auto Loc = S.find(kSPIRVPostfix::Divider);
235 auto ExtSetName = S.substr(0, Loc);
236 SPIRVExtInstSetKind Set = SPIRVEIS_Count;
237 if (!SPIRVExtSetShortNameMap::rfind(ExtSetName.str(), &Set))
238 return false;
239 assert((Set == SPIRVEIS_OpenCL || Set == BM->getDebugInfoEIS()) &&
240 "Unsupported extended instruction set");
241
242 auto ExtOpName = S.substr(Loc + 1);
243 auto Splited = ExtOpName.split(kSPIRVPostfix::ExtDivider);
244 OCLExtOpKind EOC;
245 if (!OCLExtOpMap::rfind(Splited.first.str(), &EOC))
246 return false;
247
248 if (ExtSet)
249 *ExtSet = Set;
250 if (ExtOp)
251 *ExtOp = EOC;
252 if (Dec) {
253 SmallVector<StringRef, 2> P;
254 Splited.second.split(P, kSPIRVPostfix::Divider);
255 for (auto &I : P)
256 Dec->push_back(I.str());
257 }
258 return true;
259 }
260
261 bool isUniformGroupOperation(Function *F) {
262 auto Name = F->getName();
263 if (Name.contains("GroupIMulKHR") || Name.contains("GroupFMulKHR") ||
264 Name.contains("GroupBitwiseAndKHR") ||
265 Name.contains("GroupBitwiseOrKHR") ||
266 Name.contains("GroupBitwiseXorKHR") ||
267 Name.contains("GroupLogicalAndKHR") ||
268 Name.contains("GroupLogicalOrKHR") || Name.contains("GroupLogicalXorKHR"))
269 return true;
270 return false;
271 }
272
273 static bool recursiveType(const StructType *ST, const Type *Ty) {
274 SmallPtrSet<const StructType *, 4> Seen;
275
276 std::function<bool(const Type *Ty)> Run = [&](const Type *Ty) {
277 if (auto *StructTy = dyn_cast<StructType>(Ty)) {
278 if (StructTy == ST)
279 return true;
280
281 if (Seen.count(StructTy))
282 return false;
283
284 Seen.insert(StructTy);
285
286 return find_if(StructTy->element_begin(), StructTy->element_end(), Run) !=
287 StructTy->element_end();
288 }
289
290 // Opaque pointers are translated to i8*, so they're not going to create
291 // recursive types.
292 if (Ty->isPointerTy() && !Ty->isOpaquePointerTy()) {
293 Type *ElTy = Ty->getNonOpaquePointerElementType();
294 if (auto *FTy = dyn_cast<FunctionType>(ElTy)) {
295 // If we have a function pointer, then argument types and return type of
296 // the referenced function also need to be checked
297 return Run(FTy->getReturnType()) ||
298 any_of(FTy->param_begin(), FTy->param_end(), Run);
299 }
300
301 return Run(ElTy);
302 }
303
304 if (auto *ArrayTy = dyn_cast<ArrayType>(Ty))
305 return Run(ArrayTy->getArrayElementType());
306
307 return false;
308 };
309
310 return Run(Ty);
311 }
312
313 SPIRVType *LLVMToSPIRVBase::transType(Type *T) {
314 LLVMToSPIRVTypeMap::iterator Loc = TypeMap.find(T);
315 if (Loc != TypeMap.end())
316 return Loc->second;
317
318 SPIRVDBG(dbgs() << "[transType] " << *T << '\n');
319 if (T->isVoidTy())
320 return mapType(T, BM->addVoidType());
321
322 if (T->isIntegerTy(1))
323 return mapType(T, BM->addBoolType());
324
325 if (T->isIntegerTy()) {
326 unsigned BitWidth = T->getIntegerBitWidth();
327 // SPIR-V 2.16.1. Universal Validation Rules: Scalar integer types can be
328 // parameterized only as 32 bit, plus any additional sizes enabled by
329 // capabilities.
330 if (BM->isAllowedToUseExtension(
331 ExtensionID::SPV_INTEL_arbitrary_precision_integers) ||
332 BM->getErrorLog().checkError(
333 (BitWidth == 4 &&
334 BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_int4)) ||
335 BitWidth == 8 || BitWidth == 16 || BitWidth == 32 ||
336 BitWidth == 64,
337 SPIRVEC_InvalidBitWidth, std::to_string(BitWidth))) {
338 return mapType(T, BM->addIntegerType(T->getIntegerBitWidth()));
339 }
340 }
341
342 if (T->isBFloatTy()) {
343 BM->getErrorLog().checkError(
344 BM->isAllowedToUseExtension(ExtensionID::SPV_KHR_bfloat16),
345 SPIRVEC_RequiresExtension,
346 "SPV_KHR_bfloat16\n"
347 "NOTE: LLVM module contains bfloat type, translation of which "
348 "requires this extension");
349 return mapType(T, BM->addFloatType(16, FPEncodingBFloat16KHR));
350 }
351
352 if (T->isFloatingPointTy())
353 return mapType(T, BM->addFloatType(T->getPrimitiveSizeInBits()));
354
355 // A pointer to image or pipe type in LLVM is translated to a SPIRV
356 // (non-pointer) image or pipe type.
357 if (T->isPointerTy()) {
358 auto *ET = T->isOpaquePointerTy() ? Type::getInt8Ty(T->getContext())
359 : T->getNonOpaquePointerElementType();
360 auto AddrSpc = T->getPointerAddressSpace();
361 return transPointerType(ET, AddrSpc);
362 }
363
364 if (auto *TPT = dyn_cast<TypedPointerType>(T)) {
365 return transPointerType(TPT->getElementType(), TPT->getAddressSpace());
366 }
367
368 if (auto *VecTy = dyn_cast<FixedVectorType>(T)) {
369 if (VecTy->getElementType()->isPointerTy() ||
370 isa<TypedPointerType>(VecTy->getElementType())) {
371 // SPV_INTEL_masked_gather_scatter extension changes 2.16.1. Universal
372 // Validation Rules:
373 // Vector types must be parameterized only with numerical types,
374 // [Physical Pointer Type] types or the [OpTypeBool] type.
375 // Without it vector of pointers is not allowed in SPIR-V.
376 if (!BM->isAllowedToUseExtension(
377 ExtensionID::SPV_INTEL_masked_gather_scatter)) {
378 BM->getErrorLog().checkError(
379 false, SPIRVEC_RequiresExtension,
380 "SPV_INTEL_masked_gather_scatter\n"
381 "NOTE: LLVM module contains vector of pointers, translation "
382 "of which requires this extension");
383 return nullptr;
384 }
385 BM->addExtension(ExtensionID::SPV_INTEL_masked_gather_scatter);
386 BM->addCapability(internal::CapabilityMaskedGatherScatterINTEL);
387 }
388 return mapType(T, BM->addVectorType(transType(VecTy->getElementType()),
389 VecTy->getNumElements()));
390 }
391
392 if (T->isArrayTy()) {
393 // SPIR-V 1.3 s3.32.6: Length is the number of elements in the array.
394 // It must be at least 1.
395 const auto ArraySize =
396 T->getArrayNumElements() ? T->getArrayNumElements() : 1;
397 Type *ElTy = T->getArrayElementType();
398 SPIRVType *TransType = BM->addArrayType(
399 transType(ElTy),
400 static_cast<SPIRVConstant *>(transValue(
401 ConstantInt::get(getSizetType(), ArraySize, false), nullptr)));
402 mapType(T, TransType);
403 if (ElTy->isOpaquePointerTy()) {
404 mapType(
405 ArrayType::get(TypedPointerType::get(Type::getInt8Ty(*Ctx),
406 ElTy->getPointerAddressSpace()),
407 ArraySize),
408 TransType);
409 }
410 return TransType;
411 }
412
413 if (T->isStructTy() && !T->isSized()) {
414 auto ST = dyn_cast<StructType>(T);
415 (void)ST; // Silence warning
416 assert(!ST->getName().startswith(kSPR2TypeName::PipeRO));
417 assert(!ST->getName().startswith(kSPR2TypeName::PipeWO));
418 assert(!ST->getName().startswith(kSPR2TypeName::ImagePrefix));
419 return mapType(T, BM->addOpaqueType(T->getStructName().str()));
420 }
421
422 if (auto ST = dyn_cast<StructType>(T)) {
423 assert(ST->isSized());
424
425 StringRef Name;
426 if (ST->hasName())
427 Name = ST->getName();
428
429 if (Name == getSPIRVTypeName(kSPIRVTypeName::ConstantSampler))
430 return transSPIRVOpaqueType(getSPIRVTypeName(kSPIRVTypeName::Sampler),
431 SPIRAS_Constant);
432 if (Name == getSPIRVTypeName(kSPIRVTypeName::ConstantPipeStorage))
433 return transSPIRVOpaqueType(getSPIRVTypeName(kSPIRVTypeName::PipeStorage),
434 SPIRAS_Constant);
435
436 constexpr size_t MaxNumElements = MaxWordCount - SPIRVTypeStruct::FixedWC;
437 const size_t NumElements = ST->getNumElements();
438 size_t SPIRVStructNumElements = NumElements;
439 // In case number of elements is greater than maximum WordCount and
440 // SPV_INTEL_long_constant_composite is not enabled, the error will be
441 // emitted by validate functionality of SPIRVTypeStruct class.
442 if (NumElements > MaxNumElements &&
443 BM->isAllowedToUseExtension(
444 ExtensionID::SPV_INTEL_long_constant_composite)) {
445 SPIRVStructNumElements = MaxNumElements;
446 }
447
448 auto *Struct = BM->openStructType(SPIRVStructNumElements, Name.str());
449 mapType(T, Struct);
450
451 if (NumElements > MaxNumElements &&
452 BM->isAllowedToUseExtension(
453 ExtensionID::SPV_INTEL_long_constant_composite)) {
454 uint64_t NumOfContinuedInstructions = NumElements / MaxNumElements - 1;
455 for (uint64_t J = 0; J < NumOfContinuedInstructions; J++) {
456 auto *Continued = BM->addTypeStructContinuedINTEL(MaxNumElements);
457 Struct->addContinuedInstruction(
458 static_cast<SPIRVTypeStruct::ContinuedInstType>(Continued));
459 }
460 uint64_t Remains = NumElements % MaxNumElements;
461 if (Remains) {
462 auto *Continued = BM->addTypeStructContinuedINTEL(Remains);
463 Struct->addContinuedInstruction(
464 static_cast<SPIRVTypeStruct::ContinuedInstType>(Continued));
465 }
466 }
467
468 SmallVector<unsigned, 4> ForwardRefs;
469
470 for (unsigned I = 0, E = T->getStructNumElements(); I != E; ++I) {
471 auto *ElemTy = ST->getElementType(I);
472 if ((isa<StructType>(ElemTy) || isa<ArrayType>(ElemTy) ||
473 isa<VectorType>(ElemTy) || isa<PointerType>(ElemTy)) &&
474 recursiveType(ST, ElemTy))
475 ForwardRefs.push_back(I);
476 else
477 Struct->setMemberType(I, transType(ST->getElementType(I)));
478 }
479
480 BM->closeStructType(Struct, ST->isPacked());
481
482 for (auto I : ForwardRefs)
483 Struct->setMemberType(I, transType(ST->getElementType(I)));
484
485 return Struct;
486 }
487
488 if (FunctionType *FT = dyn_cast<FunctionType>(T)) {
489 SPIRVType *RT = transType(FT->getReturnType());
490 std::vector<SPIRVType *> PT;
491 for (FunctionType::param_iterator I = FT->param_begin(),
492 E = FT->param_end();
493 I != E; ++I)
494 PT.push_back(transType(*I));
495 return mapType(T, getSPIRVFunctionType(RT, PT));
496 }
497
498 if (auto *TargetTy = dyn_cast<TargetExtType>(T)) {
499 StringRef Name = TargetTy->getName();
500 if (Name.consume_front(kSPIRVTypeName::PrefixAndDelim)) {
501 auto Opcode = SPIRVOpaqueTypeOpCodeMap::map(Name.str());
502 auto CastAccess = [](unsigned Val) {
503 return static_cast<SPIRVAccessQualifierKind>(Val);
504 };
505 switch (static_cast<size_t>(Opcode)) {
506 case OpTypePipe: {
507 auto *PipeT = BM->addPipeType();
508 PipeT->setPipeAcessQualifier(CastAccess(TargetTy->getIntParameter(0)));
509 return mapType(T, PipeT);
510 }
511 case OpTypeImage: {
512 auto *SampledTy = transType(TargetTy->getTypeParameter(0));
513 ArrayRef<unsigned> Ops = TargetTy->int_params();
514 SPIRVTypeImageDescriptor Desc(static_cast<SPIRVImageDimKind>(Ops[0]),
515 Ops[1], Ops[2], Ops[3], Ops[4], Ops[5]);
516 return mapType(T,
517 BM->addImageType(SampledTy, Desc, CastAccess(Ops[6])));
518 }
519 case OpTypeSampledImage: {
520 auto *ImageTy = static_cast<SPIRVTypeImage *>(transType(adjustImageType(
521 T, kSPIRVTypeName::SampledImg, kSPIRVTypeName::Image)));
522 return mapType(T, BM->addSampledImageType(ImageTy));
523 }
524 case OpTypeVmeImageINTEL: {
525 auto *ImageTy = static_cast<SPIRVTypeImage *>(transType(adjustImageType(
526 T, kSPIRVTypeName::VmeImageINTEL, kSPIRVTypeName::Image)));
527 return mapType(T, BM->addVmeImageINTELType(ImageTy));
528 }
529 case OpTypeQueue:
530 return mapType(T, BM->addQueueType());
531 case OpTypeDeviceEvent:
532 return mapType(T, BM->addDeviceEventType());
533 case OpTypeBufferSurfaceINTEL: {
534 ArrayRef<unsigned> Ops = TargetTy->int_params();
535 return mapType(T, BM->addBufferSurfaceINTELType(CastAccess(Ops[0])));
536 }
537 case internal::OpTypeJointMatrixINTEL: {
538 // The expected representation is:
539 // target("spirv.JointMatrixINTEL", %element_type, %rows%, %cols%,
540 // %layout%, %scope%, %use%,
541 // (optional) %element_type_interpretation%)
542 auto *ElemTy = transType(TargetTy->getTypeParameter(0));
543 ArrayRef<unsigned> Ops = TargetTy->int_params();
544 std::vector<SPIRVValue *> Args;
545 for (const auto &Op : Ops)
546 Args.emplace_back(transConstant(getUInt32(M, Op)));
547 return mapType(T, BM->addJointMatrixINTELType(ElemTy, Args));
548 }
549 case OpTypeCooperativeMatrixKHR: {
550 // The expected representation is:
551 // target("spirv.CooperativeMatrixKHR", %element_type, %scope%, %rows%,
552 // %cols%, %use%)
553 auto *ElemTy = transType(TargetTy->getTypeParameter(0));
554 ArrayRef<unsigned> Ops = TargetTy->int_params();
555 std::vector<SPIRVValue *> Args;
556 for (const auto &Op : Ops)
557 Args.emplace_back(transConstant(getUInt32(M, Op)));
558 return mapType(T, BM->addCooperativeMatrixKHRType(ElemTy, Args));
559 }
560 default:
561 if (isSubgroupAvcINTELTypeOpCode(Opcode))
562 return mapType(T, BM->addSubgroupAvcINTELType(Opcode));
563 return mapType(T, BM->addOpaqueGenericType(Opcode));
564 }
565 }
566 }
567
568 if (T->isTokenTy()) {
569 BM->getErrorLog().checkError(
570 false, SPIRVEC_InvalidModule,
571 "LLVM module contains token type, which doesn't have a counterpart in "
572 "SPIR-V");
573 return nullptr;
574 }
575
576 llvm_unreachable("Not implemented!");
577 return 0;
578 }
579
580 SPIRVType *LLVMToSPIRVBase::transPointerType(Type *ET, unsigned AddrSpc) {
581 Type *T = PointerType::get(ET, AddrSpc);
582 if (ET->isFunctionTy() &&
583 !BM->checkExtension(ExtensionID::SPV_INTEL_function_pointers,
584 SPIRVEC_FunctionPointers, toString(T)))
585 return nullptr;
586
587 std::string TypeKey = (Twine((uintptr_t)ET) + Twine(AddrSpc)).str();
588 auto Loc = PointeeTypeMap.find(TypeKey);
589 if (Loc != PointeeTypeMap.end())
590 return Loc->second;
591
592 // A pointer to image or pipe type in LLVM is translated to a SPIRV
593 // (non-pointer) image or pipe type.
594 auto *ST = dyn_cast<StructType>(ET);
595 // Lower global_device and global_host address spaces that were added in
596 // SYCL as part of SYCL_INTEL_usm_address_spaces extension to just global
597 // address space if device doesn't support SPV_INTEL_usm_storage_classes
598 // extension
599 if (!BM->isAllowedToUseExtension(
600 ExtensionID::SPV_INTEL_usm_storage_classes) &&
601 ((AddrSpc == SPIRAS_GlobalDevice) || (AddrSpc == SPIRAS_GlobalHost))) {
602 return transPointerType(ET, SPIRAS_Global);
603 }
604 // Lower function pointer address space to private if
605 // spirv-emit-function-ptr-addr-space is not passed
606 if (AddrSpc == SPIRAS_CodeSectionINTEL &&
607 !BM->shouldEmitFunctionPtrAddrSpace())
608 return transPointerType(ET, SPIRAS_Private);
609 if (ST && !ST->isSized()) {
610 Op OpCode;
611 StringRef STName = ST->getName();
612 // Workaround for non-conformant SPIR binary
613 if (STName == "struct._event_t") {
614 STName = kSPR2TypeName::Event;
615 ST->setName(STName);
616 }
617
618 std::pair<StringRef, unsigned> Key = {STName, AddrSpc};
619 if (auto *MappedTy = OpaqueStructMap.lookup(Key))
620 return MappedTy;
621
622 auto SaveType = [&](SPIRVType *MappedTy) {
623 OpaqueStructMap[Key] = MappedTy;
624 PointeeTypeMap[TypeKey] = MappedTy;
625 return MappedTy;
626 };
627
628 if (STName.startswith(kSPR2TypeName::PipeRO) ||
629 STName.startswith(kSPR2TypeName::PipeWO)) {
630 auto *PipeT = BM->addPipeType();
631 PipeT->setPipeAcessQualifier(STName.startswith(kSPR2TypeName::PipeRO)
632 ? AccessQualifierReadOnly
633 : AccessQualifierWriteOnly);
634 return SaveType(PipeT);
635 }
636 if (STName.startswith(kSPR2TypeName::ImagePrefix)) {
637 assert(AddrSpc == SPIRAS_Global);
638 Type *ImageTy =
639 adjustImageType(TypedPointerType::get(ST, AddrSpc),
640 kSPIRVTypeName::Image, kSPIRVTypeName::Image);
641 return SaveType(transType(ImageTy));
642 }
643 if (STName == kSPR2TypeName::Sampler)
644 return SaveType(transType(getSPIRVType(OpTypeSampler)));
645 if (STName.startswith(kSPIRVTypeName::PrefixAndDelim))
646 return transSPIRVOpaqueType(STName, AddrSpc);
647
648 if (STName.startswith(kOCLSubgroupsAVCIntel::TypePrefix))
649 return SaveType(BM->addSubgroupAvcINTELType(
650 OCLSubgroupINTELTypeOpCodeMap::map(ST->getName().str())));
651
652 if (OCLOpaqueTypeOpCodeMap::find(STName.str(), &OpCode)) {
653 Type *RealType = getSPIRVType(OpCode);
654 return SaveType(transType(RealType));
655 }
656 if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_vector_compute)) {
657 if (STName.startswith(kVCType::VCBufferSurface)) {
658 // VCBufferSurface always have Access Qualifier
659 auto Access = getAccessQualifier(STName);
660 return SaveType(BM->addBufferSurfaceINTELType(Access));
661 }
662 }
663
664 if (ST->isOpaque()) {
665 return SaveType(BM->addPointerType(
666 SPIRSPIRVAddrSpaceMap::map(static_cast<SPIRAddressSpace>(AddrSpc)),
667 transType(ET)));
668 }
669 } else {
670 // JointMatrixINTEL type is not necessarily an opaque type, it can be
671 // represented as a structure with pointer to a multidimensional array
672 // member.
673 if (ST && ST->hasName()) {
674 StringRef STName = ST->getName();
675 if (STName.startswith(kSPIRVTypeName::PrefixAndDelim)) {
676 SmallVector<std::string, 8> Postfixes;
677 auto TN = decodeSPIRVTypeName(STName, Postfixes);
678 if (TN == kSPIRVTypeName::JointMatrixINTEL) {
679 SPIRVType *TranslatedTy = transSPIRVJointMatrixINTELType(Postfixes);
680 PointeeTypeMap[TypeKey] = TranslatedTy;
681 return TranslatedTy;
682 }
683 }
684 }
685 SPIRVType *ElementType = transType(ET);
686 // ET, as a recursive type, may contain exactly the same pointer T, so it
687 // may happen that after translation of ET we already have translated T,
688 // added the translated pointer to the SPIR-V module and mapped T to this
689 // pointer. Now we have to check PointeeTypeMap again.
690 auto Loc = PointeeTypeMap.find(TypeKey);
691 if (Loc != PointeeTypeMap.end()) {
692 return Loc->second;
693 }
694 SPIRVType *TranslatedTy = transPointerType(ElementType, AddrSpc);
695 PointeeTypeMap[TypeKey] = TranslatedTy;
696 return TranslatedTy;
697 }
698
699 llvm_unreachable("Not implemented!");
700 return nullptr;
701 }
702
703 SPIRVType *LLVMToSPIRVBase::transPointerType(SPIRVType *ET, unsigned AddrSpc) {
704 std::string TypeKey = (Twine((uintptr_t)ET) + Twine(AddrSpc)).str();
705 auto Loc = PointeeTypeMap.find(TypeKey);
706 if (Loc != PointeeTypeMap.end())
707 return Loc->second;
708
709 if (AddrSpc == SPIRAS_CodeSectionINTEL &&
710 !BM->shouldEmitFunctionPtrAddrSpace())
711 return transPointerType(ET, SPIRAS_Private);
712
713 SPIRVType *TranslatedTy = BM->addPointerType(
714 SPIRSPIRVAddrSpaceMap::map(static_cast<SPIRAddressSpace>(AddrSpc)), ET);
715 PointeeTypeMap[TypeKey] = TranslatedTy;
716 return TranslatedTy;
717 }
718
719 // Representation in LLVM IR before the translator is a pointer to an opaque
720 // structure:
721 // %spirv.JointMatrixINTEL._%element_type%_%rows%_%cols%_%scope%_%use%
722 // Here we check the structure name yet again. Another option would be to
723 // check SPIR-V friendly function calls (by their name) and obtain return
724 // or their parameter types, assuming, that the appropriate types are Matrix
725 // structure type. But in the near future, we will reuse Composite
726 // instructions to do, for example, matrix initialization directly on AMX
727 // register by OpCompositeConstruct. And we can't claim, that the Result type
728 // of OpCompositeConstruct instruction is always the joint matrix type, it's
729 // simply not true.
730 SPIRVType *LLVMToSPIRVBase::transSPIRVJointMatrixINTELType(
731 SmallVector<std::string, 8> Postfixes) {
732 Type *ElemTy = nullptr;
733 StringRef Ty{Postfixes[0]};
734 auto NumBits = llvm::StringSwitch<unsigned>(Ty)
735 .Case("char", 8)
736 .Case("short", 16)
737 .Case("int", 32)
738 .Case("long", 64)
739 .Default(0);
740 if (NumBits)
741 ElemTy = IntegerType::get(M->getContext(), NumBits);
742 else if (Ty == "half")
743 ElemTy = Type::getHalfTy(M->getContext());
744 else if (Ty == "float")
745 ElemTy = Type::getFloatTy(M->getContext());
746 else if (Ty == "double")
747 ElemTy = Type::getDoubleTy(M->getContext());
748 else if (Ty == "bfloat16")
749 ElemTy = Type::getInt16Ty(M->getContext());
750 else
751 llvm_unreachable("Unexpected type for matrix!");
752
753 auto ParseInteger = [this](StringRef Postfix) -> ConstantInt * {
754 unsigned long long N = 0;
755 if (consumeUnsignedInteger(Postfix, 10, N)) {
756 BM->getErrorLog().checkError(
757 false, SPIRVEC_InvalidLlvmModule,
758 "TypeJointMatrixINTEL expects integer parameters");
759 return 0;
760 }
761 return getUInt32(M, N);
762 };
763 std::vector<SPIRVValue *> Args;
764 for (size_t I = 1; I != Postfixes.size(); ++I)
765 Args.emplace_back(transConstant(ParseInteger(Postfixes[I])));
766 return BM->addJointMatrixINTELType(transType(ElemTy), Args);
767 }
768
769 SPIRVType *LLVMToSPIRVBase::transSPIRVOpaqueType(StringRef STName,
770 unsigned AddrSpace) {
771 std::pair<StringRef, unsigned> Key = {STName, AddrSpace};
772 if (auto *MappedTy = OpaqueStructMap.lookup(Key))
773 return MappedTy;
774
775 auto SaveType = [&](SPIRVType *MappedTy) {
776 OpaqueStructMap[Key] = MappedTy;
777 return MappedTy;
778 };
779 StructType *ST = StructType::getTypeByName(M->getContext(), STName);
780
781 assert(STName.startswith(kSPIRVTypeName::PrefixAndDelim) &&
782 "Invalid SPIR-V opaque type name");
783 SmallVector<std::string, 8> Postfixes;
784 auto TN = decodeSPIRVTypeName(STName, Postfixes);
785 if (TN == kSPIRVTypeName::Pipe) {
786 assert(AddrSpace == SPIRAS_Global);
787 assert(Postfixes.size() == 1 && "Invalid pipe type ops");
788 auto PipeT = BM->addPipeType();
789 PipeT->setPipeAcessQualifier(
790 static_cast<spv::AccessQualifier>(atoi(Postfixes[0].c_str())));
791 return SaveType(PipeT);
792 } else if (TN == kSPIRVTypeName::Image) {
793 assert(AddrSpace == SPIRAS_Global);
794 // The sampled type needs to be translated through LLVM type to guarantee
795 // uniqueness.
796 auto SampledT = transType(
797 getLLVMTypeForSPIRVImageSampledTypePostfix(Postfixes[0], *Ctx));
798 SmallVector<int, 7> Ops;
799 for (unsigned I = 1; I < 8; ++I)
800 Ops.push_back(atoi(Postfixes[I].c_str()));
801 SPIRVTypeImageDescriptor Desc(static_cast<SPIRVImageDimKind>(Ops[0]),
802 Ops[1], Ops[2], Ops[3], Ops[4], Ops[5]);
803 return SaveType(BM->addImageType(
804 SampledT, Desc, static_cast<spv::AccessQualifier>(Ops[6])));
805 } else if (TN == kSPIRVTypeName::SampledImg) {
806 return SaveType(BM->addSampledImageType(static_cast<SPIRVTypeImage *>(
807 transType(adjustImageType(TypedPointerType::get(ST, SPIRAS_Global),
808 kSPIRVTypeName::SampledImg,
809 kSPIRVTypeName::Image)))));
810 } else if (TN == kSPIRVTypeName::VmeImageINTEL) {
811 // This type is the same as SampledImageType, but consumed by Subgroup AVC
812 // Intel extension instructions.
813 return SaveType(BM->addVmeImageINTELType(static_cast<SPIRVTypeImage *>(
814 transType(adjustImageType(TypedPointerType::get(ST, SPIRAS_Global),
815 kSPIRVTypeName::VmeImageINTEL,
816 kSPIRVTypeName::Image)))));
817 } else if (TN == kSPIRVTypeName::Sampler)
818 return SaveType(BM->addSamplerType());
819 else if (TN == kSPIRVTypeName::DeviceEvent)
820 return SaveType(BM->addDeviceEventType());
821 else if (TN == kSPIRVTypeName::Queue)
822 return SaveType(BM->addQueueType());
823 else if (TN == kSPIRVTypeName::PipeStorage)
824 return SaveType(BM->addPipeStorageType());
825 else if (TN == kSPIRVTypeName::JointMatrixINTEL)
826 return SaveType(transSPIRVJointMatrixINTELType(Postfixes));
827 else if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_vector_compute) &&
828 TN == kSPIRVTypeName::BufferSurfaceINTEL) {
829 auto Access = getAccessQualifier(STName);
830 return SaveType(BM->addBufferSurfaceINTELType(Access));
831 } else
832 return SaveType(
833 BM->addOpaqueGenericType(SPIRVOpaqueTypeOpCodeMap::map(TN)));
834 }
835
836 SPIRVType *LLVMToSPIRVBase::transScavengedType(Value *V) {
837 if (auto *F = dyn_cast<Function>(V)) {
838 FunctionType *FnTy = F->getType()->isOpaquePointerTy()
839 ? Scavenger->getFunctionType(F)
840 : F->getFunctionType();
841 SPIRVType *RT = transType(FnTy->getReturnType());
842 std::vector<SPIRVType *> PT;
843 for (Argument &Arg : F->args()) {
844 assert(OCLTypeToSPIRVPtr);
845 Type *Ty = OCLTypeToSPIRVPtr->getAdaptedArgumentType(F, Arg.getArgNo());
846 if (!Ty) {
847 Ty = FnTy->getParamType(Arg.getArgNo());
848 }
849 PT.push_back(transType(Ty));
850 }
851
852 return getSPIRVFunctionType(RT, PT);
853 }
854
855 return transType(Scavenger->getScavengedType(V));
856 }
857
858 SPIRVType *
859 LLVMToSPIRVBase::getSPIRVFunctionType(SPIRVType *RT,
860 const std::vector<SPIRVType *> &Args) {
861 // Come up with a unique string identifier for the arguments. This is a hacky
862 // way of doing so, but it works.
863 std::string TypeKey;
864 llvm::raw_string_ostream TKS(TypeKey);
865 TKS << (uintptr_t)RT << ",";
866 for (SPIRVType *ArgTy : Args) {
867 TKS << (uintptr_t)ArgTy << ",";
868 }
869
870 // Create a SPIRVType for the function type. Since SPIRVModule doesn't do
871 // any type uniquing for SPIRVType, we have to do it ourself.
872 TKS.flush();
873 auto It = PointeeTypeMap.find(TypeKey);
874 if (It == PointeeTypeMap.end())
875 It = PointeeTypeMap.insert({TypeKey, BM->addFunctionType(RT, Args)}).first;
876 return It->second;
877 }
878
879 SPIRVFunction *LLVMToSPIRVBase::transFunctionDecl(Function *F) {
880 if (auto BF = getTranslatedValue(F))
881 return static_cast<SPIRVFunction *>(BF);
882
883 if (F->isIntrinsic() && (!BM->isSPIRVAllowUnknownIntrinsicsEnabled() ||
884 isKnownIntrinsic(F->getIntrinsicID()))) {
885 // We should not translate LLVM intrinsics as a function
886 assert(none_of(F->users(),
887 [this](User *U) { return getTranslatedValue(U); }) &&
888 "LLVM intrinsics shouldn't be called in SPIRV");
889 return nullptr;
890 }
891
892 // Don't translate FP conversion translator builtins as function declarations.
893 auto MangledName = F->getName();
894 std::string DemangledName;
895 if (isInternalSPIRVBuiltin(MangledName, DemangledName)) {
896 if (SPIRV::FPConvertToEncodingMap::find(llvm::StringRef(DemangledName))) {
897 // Create an early exit here if none of the extensions are enabled.
898 // Proper checks for the required extensions will be done during TypeFloat
899 // generation.
900 if (!BM->isAllowedToUseExtension(ExtensionID::SPV_EXT_float8) &&
901 !BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_int4) &&
902 !BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_float4)) {
903 std::string ErrorStr =
904 "One of the following extensions: SPV_EXT_float8, SPV_INTEL_float4"
905 "SPV_INTEL_int4 should be enabled to process "
906 "conversion builtins";
907 getErrorLog().checkError(false, SPIRVEC_RequiresExtension, F, ErrorStr);
908 }
909 return nullptr;
910 }
911 }
912
913 SPIRVTypeFunction *BFT =
914 static_cast<SPIRVTypeFunction *>(transScavengedType(F));
915 SPIRVFunction *BF =
916 static_cast<SPIRVFunction *>(mapValue(F, BM->addFunction(BFT)));
917 BF->setFunctionControlMask(transFunctionControlMask(F));
918 if (F->hasName()) {
919 if (isKernel(F)) {
920 /* strip the prefix as the runtime will be looking for this name */
921 std::string Prefix = kSPIRVName::EntrypointPrefix;
922 std::string Name = F->getName().str();
923 BM->setName(BF, Name.substr(Prefix.size()));
924 } else {
925 if (isUniformGroupOperation(F))
926 BM->getErrorLog().checkError(
927 BM->isAllowedToUseExtension(
928 ExtensionID::SPV_KHR_uniform_group_instructions),
929 SPIRVEC_RequiresExtension, "SPV_KHR_uniform_group_instructions\n");
930 BM->setName(BF, F->getName().str());
931 }
932 }
933 if (!isKernel(F) && F->getLinkage() != GlobalValue::InternalLinkage)
934 BF->setLinkageType(transLinkageType(F));
935
936 // Translate OpenCL/SYCL buffer_location metadata if it's attached to the
937 // translated function declaration
938 MDNode *BufferLocation = nullptr;
939 if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_fpga_buffer_location))
940 BufferLocation = F->getMetadata("kernel_arg_buffer_location");
941
942 // Translate runtime_aligned metadata if it's attached to the translated
943 // function declaration
944 MDNode *RuntimeAligned = nullptr;
945 if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_runtime_aligned))
946 RuntimeAligned = F->getMetadata("kernel_arg_runtime_aligned");
947
948 auto Attrs = F->getAttributes();
949
950 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
951 ++I) {
952 auto ArgNo = I->getArgNo();
953 SPIRVFunctionParameter *BA = BF->getArgument(ArgNo);
954 if (I->hasName())
955 BM->setName(BA, I->getName().str());
956 if (I->hasByValAttr())
957 BA->addAttr(FunctionParameterAttributeByVal);
958 if (I->hasNoAliasAttr())
959 BA->addAttr(FunctionParameterAttributeNoAlias);
960 if (I->hasNoCaptureAttr())
961 BA->addAttr(FunctionParameterAttributeNoCapture);
962 if (I->hasStructRetAttr())
963 BA->addAttr(FunctionParameterAttributeSret);
964 if (Attrs.hasParamAttr(ArgNo, Attribute::ReadOnly))
965 BA->addAttr(FunctionParameterAttributeNoWrite);
966 if (Attrs.hasParamAttr(ArgNo, Attribute::ReadNone))
967 BA->addAttr(FunctionParameterAttributeNoReadWrite);
968 if (Attrs.hasParamAttr(ArgNo, Attribute::ZExt))
969 BA->addAttr(FunctionParameterAttributeZext);
970 if (Attrs.hasParamAttr(ArgNo, Attribute::SExt))
971 BA->addAttr(FunctionParameterAttributeSext);
972 if (Attrs.hasParamAttr(ArgNo, Attribute::Alignment)) {
973 SPIRVWord AlignmentBytes = Attrs.getParamAttr(ArgNo, Attribute::Alignment)
974 .getAlignment()
975 .valueOrOne()
976 .value();
977 BA->setAlignment(AlignmentBytes);
978 }
979 if (BM->isAllowedToUseVersion(VersionNumber::SPIRV_1_1) &&
980 Attrs.hasParamAttr(ArgNo, Attribute::Dereferenceable))
981 BA->addDecorate(DecorationMaxByteOffset,
982 Attrs.getParamAttr(ArgNo, Attribute::Dereferenceable)
983 .getDereferenceableBytes());
984 if (BufferLocation && I->getType()->isPointerTy()) {
985 // Order of integer numbers in MD node follows the order of function
986 // parameters on which we shall attach the appropriate decoration. Add
987 // decoration only if MD value is not negative.
988 int LocID = -1;
989 if (!isa<MDString>(BufferLocation->getOperand(ArgNo)) &&
990 !isa<MDNode>(BufferLocation->getOperand(ArgNo)))
991 LocID = getMDOperandAsInt(BufferLocation, ArgNo);
992 if (LocID >= 0)
993 BA->addDecorate(DecorationBufferLocationINTEL, LocID);
994 }
995 if (RuntimeAligned && I->getType()->isPointerTy()) {
996 // Order of integer numbers in MD node follows the order of function
997 // parameters on which we shall attach the appropriate decoration. Add
998 // decoration only if MD value is 1.
999 int IsRuntimeAligned = 0;
1000 if (!isa<MDString>(RuntimeAligned->getOperand(ArgNo)) &&
1001 !isa<MDNode>(RuntimeAligned->getOperand(ArgNo)))
1002 IsRuntimeAligned = getMDOperandAsInt(RuntimeAligned, ArgNo);
1003 if (IsRuntimeAligned == 1) {
1004 // TODO: to replace non-conformant to the spec decoration generation
1005 // with:
1006 // BM->addExtension(ExtensionID::SPV_INTEL_runtime_aligned);
1007 // BM->addCapability(CapabilityRuntimeAlignedAttributeINTEL);
1008 // BA->addAttr(FunctionParameterAttributeRuntimeAlignedINTEL);
1009 BA->addDecorate(internal::DecorationRuntimeAlignedINTEL,
1010 IsRuntimeAligned);
1011 }
1012 }
1013 }
1014 if (Attrs.hasRetAttr(Attribute::ZExt))
1015 BF->addDecorate(DecorationFuncParamAttr, FunctionParameterAttributeZext);
1016 if (Attrs.hasRetAttr(Attribute::SExt))
1017 BF->addDecorate(DecorationFuncParamAttr, FunctionParameterAttributeSext);
1018 if (Attrs.hasFnAttr("referenced-indirectly")) {
1019 assert(!isKernel(F) &&
1020 "kernel function was marked as referenced-indirectly");
1021 BF->addDecorate(DecorationReferencedIndirectlyINTEL);
1022 }
1023
1024 if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_vector_compute))
1025 transVectorComputeMetadata(F);
1026
1027 transFPGAFunctionMetadata(BF, F);
1028
1029 if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_maximum_registers))
1030 transFunctionMetadataAsExecutionMode(BF, F);
1031 else
1032 transFunctionMetadataAsUserSemanticDecoration(BF, F);
1033
1034 transAuxDataInst(BF, F);
1035
1036 SPIRVDBG(dbgs() << "[transFunction] " << *F << " => ";
1037 spvdbgs() << *BF << '\n';)
1038 return BF;
1039 }
1040
1041 void LLVMToSPIRVBase::transVectorComputeMetadata(Function *F) {
1042 using namespace VectorComputeUtil;
1043 if (!BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_vector_compute))
1044 return;
1045 auto BF = static_cast<SPIRVFunction *>(getTranslatedValue(F));
1046 assert(BF && "The SPIRVFunction pointer shouldn't be nullptr");
1047 auto Attrs = F->getAttributes();
1048
1049 if (Attrs.hasFnAttr(kVCMetadata::VCStackCall))
1050 BF->addDecorate(DecorationStackCallINTEL);
1051 if (Attrs.hasFnAttr(kVCMetadata::VCFunction))
1052 BF->addDecorate(DecorationVectorComputeFunctionINTEL);
1053
1054 if (Attrs.hasFnAttr(kVCMetadata::VCSIMTCall)) {
1055 SPIRVWord SIMTMode = 0;
1056 Attrs.getFnAttr(kVCMetadata::VCSIMTCall)
1057 .getValueAsString()
1058 .getAsInteger(0, SIMTMode);
1059 BF->addDecorate(DecorationSIMTCallINTEL, SIMTMode);
1060 }
1061
1062 if (Attrs.hasRetAttr(kVCMetadata::VCSingleElementVector))
1063 translateSEVDecoration(
1064 Attrs.getAttributeAtIndex(AttributeList::ReturnIndex,
1065 kVCMetadata::VCSingleElementVector),
1066 BF);
1067
1068 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
1069 ++I) {
1070 auto ArgNo = I->getArgNo();
1071 SPIRVFunctionParameter *BA = BF->getArgument(ArgNo);
1072 if (Attrs.hasParamAttr(ArgNo, kVCMetadata::VCArgumentIOKind)) {
1073 SPIRVWord Kind = {};
1074 Attrs.getParamAttr(ArgNo, kVCMetadata::VCArgumentIOKind)
1075 .getValueAsString()
1076 .getAsInteger(0, Kind);
1077 BA->addDecorate(DecorationFuncParamIOKindINTEL, Kind);
1078 }
1079 if (Attrs.hasParamAttr(ArgNo, kVCMetadata::VCSingleElementVector))
1080 translateSEVDecoration(
1081 Attrs.getParamAttr(ArgNo, kVCMetadata::VCSingleElementVector), BA);
1082 if (Attrs.hasParamAttr(ArgNo, kVCMetadata::VCMediaBlockIO)) {
1083 assert(BA->getType()->isTypeImage() &&
1084 "VCMediaBlockIO attribute valid only on image parameters");
1085 BA->addDecorate(DecorationMediaBlockIOINTEL);
1086 }
1087 }
1088 if (!isKernel(F) &&
1089 BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_float_controls2) &&
1090 Attrs.hasFnAttr(kVCMetadata::VCFloatControl)) {
1091
1092 SPIRVWord Mode = 0;
1093 Attrs.getFnAttr(kVCMetadata::VCFloatControl)
1094 .getValueAsString()
1095 .getAsInteger(0, Mode);
1096 VCFloatTypeSizeMap::foreach (
1097 [&](VCFloatType FloatType, unsigned TargetWidth) {
1098 BF->addDecorate(new SPIRVDecorateFunctionDenormModeINTEL(
1099 BF, TargetWidth, getFPDenormMode(Mode, FloatType)));
1100
1101 BF->addDecorate(new SPIRVDecorateFunctionRoundingModeINTEL(
1102 BF, TargetWidth, getFPRoundingMode(Mode)));
1103
1104 BF->addDecorate(new SPIRVDecorateFunctionFloatingPointModeINTEL(
1105 BF, TargetWidth, getFPOperationMode(Mode)));
1106 });
1107 }
1108 }
1109
1110 static void transMetadataDecorations(Metadata *MD, SPIRVValue *Target);
1111
1112 void LLVMToSPIRVBase::transFPGAFunctionMetadata(SPIRVFunction *BF,
1113 Function *F) {
1114 if (MDNode *StallEnable = F->getMetadata(kSPIR2MD::StallEnable)) {
1115 if (BM->isAllowedToUseExtension(
1116 ExtensionID::SPV_INTEL_fpga_cluster_attributes)) {
1117 if (getMDOperandAsInt(StallEnable, 0))
1118 BF->addDecorate(new SPIRVDecorateStallEnableINTEL(BF));
1119 }
1120 }
1121 if (MDNode *LoopFuse = F->getMetadata(kSPIR2MD::LoopFuse)) {
1122 if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_loop_fuse)) {
1123 size_t Depth = getMDOperandAsInt(LoopFuse, 0);
1124 size_t Independent = getMDOperandAsInt(LoopFuse, 1);
1125 BF->addDecorate(
1126 new SPIRVDecorateFuseLoopsInFunctionINTEL(BF, Depth, Independent));
1127 }
1128 }
1129 if (MDNode *PreferDSP = F->getMetadata(kSPIR2MD::PreferDSP)) {
1130 if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_fpga_dsp_control)) {
1131 size_t Mode = getMDOperandAsInt(PreferDSP, 0);
1132 MDNode *PropDSPPref = F->getMetadata(kSPIR2MD::PropDSPPref);
1133 size_t Propagate = PropDSPPref ? getMDOperandAsInt(PropDSPPref, 0) : 0;
1134 BF->addDecorate(new SPIRVDecorateMathOpDSPModeINTEL(BF, Mode, Propagate));
1135 }
1136 }
1137 if (MDNode *InitiationInterval =
1138 F->getMetadata(kSPIR2MD::InitiationInterval)) {
1139 if (BM->isAllowedToUseExtension(
1140 ExtensionID::SPV_INTEL_fpga_invocation_pipelining_attributes)) {
1141 if (size_t Cycles = getMDOperandAsInt(InitiationInterval, 0))
1142 BF->addDecorate(new SPIRVDecorateInitiationIntervalINTEL(BF, Cycles));
1143 }
1144 }
1145 if (MDNode *MaxConcurrency = F->getMetadata(kSPIR2MD::MaxConcurrency)) {
1146 if (BM->isAllowedToUseExtension(
1147 ExtensionID::SPV_INTEL_fpga_invocation_pipelining_attributes)) {
1148 size_t Invocations = getMDOperandAsInt(MaxConcurrency, 0);
1149 BF->addDecorate(new SPIRVDecorateMaxConcurrencyINTEL(BF, Invocations));
1150 }
1151 }
1152 if (MDNode *DisableLoopPipelining =
1153 F->getMetadata(kSPIR2MD::DisableLoopPipelining)) {
1154 if (BM->isAllowedToUseExtension(
1155 ExtensionID::SPV_INTEL_fpga_invocation_pipelining_attributes)) {
1156 size_t Disable = getMDOperandAsInt(DisableLoopPipelining, 0);
1157 BF->addDecorate(new SPIRVDecoratePipelineEnableINTEL(BF, !Disable));
1158 }
1159 }
1160
1161 // In addition, process the decorations on the function
1162 if (auto *FDecoMD = F->getMetadata(SPIRV_MD_DECORATIONS))
1163 transMetadataDecorations(FDecoMD, BF);
1164 }
1165
1166 void LLVMToSPIRVBase::transFunctionMetadataAsExecutionMode(SPIRVFunction *BF,
1167 Function *F) {
1168 SmallVector<MDNode *, 1> RegisterAllocModeMDs;
1169 F->getMetadata("RegisterAllocMode", RegisterAllocModeMDs);
1170
1171 for (unsigned I = 0; I < RegisterAllocModeMDs.size(); I++) {
1172 auto *RegisterAllocMode = RegisterAllocModeMDs[I]->getOperand(0).get();
1173 if (isa<MDString>(RegisterAllocMode)) {
1174 StringRef Str = getMDOperandAsString(RegisterAllocModeMDs[I], 0);
1175 NamedMaximumNumberOfRegisters NamedValue =
1176 SPIRVNamedMaximumNumberOfRegistersNameMap::rmap(Str.str());
1177 BF->addExecutionMode(BM->add(new SPIRVExecutionMode(
1178 OpExecutionMode, BF, ExecutionModeNamedMaximumRegistersINTEL,
1179 NamedValue)));
1180 } else if (isa<MDNode>(RegisterAllocMode)) {
1181 auto *RegisterAllocNodeMDOp =
1182 getMDOperandAsMDNode(RegisterAllocModeMDs[I], 0);
1183 int Num = getMDOperandAsInt(RegisterAllocNodeMDOp, 0);
1184 auto *Const =
1185 BM->addConstant(transType(Type::getInt32Ty(F->getContext())), Num);
1186 BF->addExecutionMode(BM->add(new SPIRVExecutionModeId(
1187 BF, ExecutionModeMaximumRegistersIdINTEL, Const->getId())));
1188 } else {
1189 int64_t RegisterAllocVal =
1190 mdconst::dyn_extract<ConstantInt>(RegisterAllocMode)->getZExtValue();
1191 BF->addExecutionMode(BM->add(new SPIRVExecutionMode(
1192 OpExecutionMode, BF, ExecutionModeMaximumRegistersINTEL,
1193 RegisterAllocVal)));
1194 }
1195 }
1196 }
1197
1198 void LLVMToSPIRVBase::transFunctionMetadataAsUserSemanticDecoration(
1199 SPIRVFunction *BF, Function *F) {
1200 if (auto *RegisterAllocModeMD = F->getMetadata("RegisterAllocMode")) {
1201 // TODO: Once the design for per-kernel register size allocation is
1202 // finalized, we will need to move away from UserSemantic and introduce an
1203 // extension
1204 int RegisterAllocNodeMDOp = getMDOperandAsInt(RegisterAllocModeMD, 0);
1205 // The current RegisterAllocMode metadata format is as follows
1206 // AUTO - 0
1207 // SMALL - 1
1208 // LARGE - 2
1209 // DEFAULT - 3
1210 // Currently we only support SMALL and LARGE
1211 if (RegisterAllocNodeMDOp == 1 || RegisterAllocNodeMDOp == 2) {
1212 // 4 threads per eu means large grf mode, and 8 threads per eu
1213 // means small grf mode
1214 std::string NumThreads = RegisterAllocNodeMDOp == 2 ? "4" : "8";
1215 BF->addDecorate(new SPIRVDecorateUserSemanticAttr(
1216 BF, "num-thread-per-eu " + NumThreads));
1217 }
1218 }
1219 }
1220
1221 void LLVMToSPIRVBase::transAuxDataInst(SPIRVFunction *BF, Function *F) {
1222 auto *BM = BF->getModule();
1223 if (!BM->preserveAuxData())
1224 return;
1225 if (!BM->isAllowedToUseVersion(VersionNumber::SPIRV_1_6))
1226 BM->addExtension(SPIRV::ExtensionID::SPV_KHR_non_semantic_info);
1227 else
1228 BM->setMinSPIRVVersion(VersionNumber::SPIRV_1_6);
1229 const auto &FnAttrs = F->getAttributes().getFnAttrs();
1230 for (const auto &Attr : FnAttrs) {
1231 std::vector<SPIRVWord> Ops;
1232 Ops.push_back(BF->getId());
1233 if (Attr.isStringAttribute()) {
1234 // Format for String attributes is:
1235 // NonSemanticAuxDataFunctionAttribute Fcn AttrName AttrValue
1236 // or, if no value:
1237 // NonSemanticAuxDataFunctionAttribute Fcn AttrName
1238 //
1239 // AttrName and AttrValue are always Strings
1240 const StringRef AttrKind = Attr.getKindAsString();
1241 const StringRef AttrValue = Attr.getValueAsString();
1242 auto *KindSpvString = BM->getString(AttrKind.str());
1243 Ops.push_back(KindSpvString->getId());
1244 if (!AttrValue.empty()) {
1245 auto *ValueSpvString = BM->getString(AttrValue.str());
1246 Ops.push_back(ValueSpvString->getId());
1247 }
1248 } else {
1249 // Format for other types is:
1250 // NonSemanticAuxDataFunctionAttribute Fcn AttrStr
1251 // AttrStr is always a String.
1252 const std::string AttrStr = Attr.getAsString();
1253 auto *AttrSpvString = BM->getString(AttrStr);
1254 Ops.push_back(AttrSpvString->getId());
1255 }
1256 BM->addAuxData(NonSemanticAuxData::FunctionAttribute,
1257 transType(Type::getVoidTy(F->getContext())), Ops);
1258 }
1259 SmallVector<std::pair<unsigned, MDNode *>> AllMD;
1260 SmallVector<StringRef> MDNames;
1261 F->getContext().getMDKindNames(MDNames);
1262 F->getAllMetadata(AllMD);
1263 for (auto MD : AllMD) {
1264 const std::string MDName = MDNames[MD.first].str();
1265
1266 // spirv.Decorations, spirv.ParameterDecorations and debug information are
1267 // handled elsewhere for both forward and reverse translation and are
1268 // complicated to support here, so just skip them.
1269 if (MDName == SPIRV_MD_DECORATIONS ||
1270 MDName == SPIRV_MD_PARAMETER_DECORATIONS ||
1271 MD.first == LLVMContext::MD_dbg)
1272 continue;
1273
1274 // Format for metadata is:
1275 // NonSemanticAuxDataFunctionMetadata Fcn MDName MDVals...
1276 // MDName is always a String, MDVals have different types as explained
1277 // below. Also note this instruction has a variable number of operands
1278 std::vector<SPIRVWord> Ops;
1279 Ops.push_back(BF->getId());
1280 Ops.push_back(BM->getString(MDName)->getId());
1281 for (unsigned int OpIdx = 0; OpIdx < MD.second->getNumOperands(); OpIdx++) {
1282 const auto &CurOp = MD.second->getOperand(OpIdx);
1283 if (auto *MDStr = dyn_cast<MDString>(CurOp)) {
1284 // For MDString, MDVal is String
1285 auto *SPIRVStr = BM->getString(MDStr->getString().str());
1286 Ops.push_back(SPIRVStr->getId());
1287 } else if (auto *ValueAsMeta = dyn_cast<ValueAsMetadata>(CurOp)) {
1288 // For Value metadata, MDVal is a SPIRVValue
1289 auto *SPIRVVal = transValue(ValueAsMeta->getValue(), nullptr);
1290 Ops.push_back(SPIRVVal->getId());
1291 } else {
1292 assert(false && "Unsupported metadata type");
1293 }
1294 }
1295 BM->addAuxData(NonSemanticAuxData::FunctionMetadata,
1296 transType(Type::getVoidTy(F->getContext())), Ops);
1297 }
1298 }
1299
1300 SPIRVValue *LLVMToSPIRVBase::transConstantUse(Constant *C,
1301 SPIRVType *ExpectedType) {
1302 // Constant expressions expect their pointer types to be i8* in opaque pointer
1303 // mode, but the value may have a different "natural" type. If that is the
1304 // case, we need to adjust the type of the constant.
1305 SPIRVValue *Trans = transValue(C, nullptr, true, FuncTransMode::Pointer);
1306 if (Trans->getType() == ExpectedType || Trans->getType()->isTypePipeStorage())
1307 return Trans;
1308
1309 assert(C->getType()->isPointerTy() &&
1310 "Only pointer type mismatches should be possible");
1311 // In the common case of strings ([N x i8] GVs), see if we can emit a GEP
1312 // instruction.
1313 if (auto *GV = dyn_cast<GlobalVariable>(C)) {
1314 if (GV->getValueType()->isArrayTy() &&
1315 GV->getValueType()->getArrayElementType()->isIntegerTy(8)) {
1316 SPIRVValue *Offset = transValue(getUInt32(M, 0), nullptr);
1317 return BM->addPtrAccessChainInst(ExpectedType, Trans, {Offset, Offset},
1318 nullptr, true);
1319 }
1320 }
1321
1322 // Otherwise, just use a bitcast.
1323 return BM->addUnaryInst(OpBitcast, ExpectedType, Trans, nullptr);
1324 }
1325
1326 SPIRVValue *LLVMToSPIRVBase::transConstant(Value *V) {
1327 SPIRVType *ExpectedType = transScavengedType(V);
1328 if (isa<ConstantPointerNull>(V))
1329 return BM->addNullConstant(bcast<SPIRVTypePointer>(ExpectedType));
1330
1331 if (isa<ConstantTargetNone>(V))
1332 return BM->addNullConstant(ExpectedType);
1333
1334 if (auto CAZero = dyn_cast<ConstantAggregateZero>(V)) {
1335 Type *AggType = CAZero->getType();
1336 if (const StructType *ST = dyn_cast<StructType>(AggType))
1337 if (ST->hasName() &&
1338 ST->getName() == getSPIRVTypeName(kSPIRVTypeName::ConstantSampler))
1339 return BM->addSamplerConstant(transType(AggType), 0, 0, 0);
1340
1341 return BM->addNullConstant(transType(AggType));
1342 }
1343
1344 if (auto ConstI = dyn_cast<ConstantInt>(V)) {
1345 unsigned BitWidth = ConstI->getType()->getBitWidth();
1346 if (BitWidth > 64) {
1347 BM->getErrorLog().checkError(
1348 BM->isAllowedToUseExtension(
1349 ExtensionID::SPV_INTEL_arbitrary_precision_integers),
1350 SPIRVEC_InvalidBitWidth, std::to_string(BitWidth));
1351 return BM->addConstant(ExpectedType, ConstI->getValue());
1352 }
1353 return BM->addConstant(ExpectedType, ConstI->getZExtValue());
1354 }
1355
1356 if (auto ConstFP = dyn_cast<ConstantFP>(V)) {
1357 auto *BT = static_cast<SPIRVType *>(ExpectedType);
1358 return BM->addConstant(
1359 BT, ConstFP->getValueAPF().bitcastToAPInt().getZExtValue());
1360 }
1361
1362 if (auto ConstDA = dyn_cast<ConstantDataArray>(V)) {
1363 SPIRVType *InnerTy = ExpectedType->getArrayElementType();
1364 std::vector<SPIRVValue *> BV;
1365 for (unsigned I = 0, E = ConstDA->getNumElements(); I != E; ++I)
1366 BV.push_back(transConstantUse(ConstDA->getElementAsConstant(I), InnerTy));
1367 return BM->addCompositeConstant(ExpectedType, BV);
1368 }
1369
1370 if (auto ConstA = dyn_cast<ConstantArray>(V)) {
1371 SPIRVType *InnerTy = ExpectedType->getArrayElementType();
1372 std::vector<SPIRVValue *> BV;
1373 for (auto I = ConstA->op_begin(), E = ConstA->op_end(); I != E; ++I)
1374 BV.push_back(transConstantUse(cast<Constant>(*I), InnerTy));
1375 return BM->addCompositeConstant(ExpectedType, BV);
1376 }
1377
1378 if (auto ConstDV = dyn_cast<ConstantDataVector>(V)) {
1379 SPIRVType *InnerTy = ExpectedType->getScalarType();
1380 std::vector<SPIRVValue *> BV;
1381 for (unsigned I = 0, E = ConstDV->getNumElements(); I != E; ++I)
1382 BV.push_back(transConstantUse(ConstDV->getElementAsConstant(I), InnerTy));
1383 return BM->addCompositeConstant(ExpectedType, BV);
1384 }
1385
1386 if (auto ConstV = dyn_cast<ConstantVector>(V)) {
1387 SPIRVType *InnerTy = ExpectedType->getScalarType();
1388 std::vector<SPIRVValue *> BV;
1389 for (auto I = ConstV->op_begin(), E = ConstV->op_end(); I != E; ++I)
1390 BV.push_back(transConstantUse(cast<Constant>(*I), InnerTy));
1391 return BM->addCompositeConstant(ExpectedType, BV);
1392 }
1393
1394 if (const auto *ConstV = dyn_cast<ConstantStruct>(V)) {
1395 StringRef StructName;
1396 if (ConstV->getType()->hasName())
1397 StructName = ConstV->getType()->getName();
1398 if (StructName == getSPIRVTypeName(kSPIRVTypeName::ConstantSampler)) {
1399 assert(ConstV->getNumOperands() == 3);
1400 SPIRVWord AddrMode =
1401 ConstV->getOperand(0)->getUniqueInteger().getZExtValue(),
1402 Normalized =
1403 ConstV->getOperand(1)->getUniqueInteger().getZExtValue(),
1404 FilterMode =
1405 ConstV->getOperand(2)->getUniqueInteger().getZExtValue();
1406 assert(AddrMode < 5 && "Invalid addressing mode");
1407 assert(Normalized < 2 && "Invalid value of normalized coords");
1408 assert(FilterMode < 2 && "Invalid filter mode");
1409 SPIRVType *SamplerTy = transType(ConstV->getType());
1410 return BM->addSamplerConstant(SamplerTy, AddrMode, Normalized,
1411 FilterMode);
1412 }
1413 if (StructName == getSPIRVTypeName(kSPIRVTypeName::ConstantPipeStorage)) {
1414 assert(ConstV->getNumOperands() == 3);
1415 SPIRVWord PacketSize =
1416 ConstV->getOperand(0)->getUniqueInteger().getZExtValue(),
1417 PacketAlign =
1418 ConstV->getOperand(1)->getUniqueInteger().getZExtValue(),
1419 Capacity =
1420 ConstV->getOperand(2)->getUniqueInteger().getZExtValue();
1421 assert(PacketAlign >= 1 && "Invalid packet alignment");
1422 assert(PacketSize >= PacketAlign && PacketSize % PacketAlign == 0 &&
1423 "Invalid packet size and/or alignment.");
1424 SPIRVType *PipeStorageTy = transType(ConstV->getType());
1425 return BM->addPipeStorageConstant(PipeStorageTy, PacketSize, PacketAlign,
1426 Capacity);
1427 }
1428 std::vector<SPIRVValue *> BV;
1429 for (auto I = ConstV->op_begin(), E = ConstV->op_end(); I != E; ++I) {
1430 SPIRVType *InnerTy = ExpectedType->getStructMemberType(BV.size());
1431 BV.push_back(transConstantUse(cast<Constant>(*I), InnerTy));
1432 }
1433 return BM->addCompositeConstant(ExpectedType, BV);
1434 }
1435
1436 if (auto *ConstUE = dyn_cast<ConstantExpr>(V)) {
1437 if (auto *GEP = dyn_cast<GEPOperator>(ConstUE)) {
1438 std::vector<SPIRVValue *> Indices;
1439 for (unsigned I = 0, E = GEP->getNumIndices(); I != E; ++I)
1440 Indices.push_back(transValue(GEP->getOperand(I + 1), nullptr));
1441 auto *TransPointerOperand = transValue(GEP->getPointerOperand(), nullptr);
1442 // Determine the expected pointer type from the GEP source element type.
1443 Type *GepSourceElemTy = GEP->getSourceElementType();
1444 SPIRVType *ExpectedPtrTy =
1445 transPointerType(GepSourceElemTy, GEP->getPointerAddressSpace());
1446
1447 // Ensure the base pointer's type matches the GEP's effective source
1448 // element type.
1449 if (TransPointerOperand->getType() != ExpectedPtrTy) {
1450 TransPointerOperand = BM->addUnaryInst(OpBitcast, ExpectedPtrTy,
1451 TransPointerOperand, nullptr);
1452 }
1453
1454 SPIRVType *TranslatedTy = transScavengedType(GEP);
1455 return BM->addPtrAccessChainInst(TranslatedTy, TransPointerOperand,
1456 Indices, nullptr, GEP->isInBounds());
1457 }
1458 auto *Inst = ConstUE->getAsInstruction();
1459 SPIRVDBG(dbgs() << "ConstantExpr: " << *ConstUE << '\n';
1460 dbgs() << "Instruction: " << *Inst << '\n';)
1461 auto BI = transValue(Inst, nullptr, false);
1462 Inst->dropAllReferences();
1463 UnboundInst.push_back(Inst);
1464 return BI;
1465 }
1466
1467 // Translate aliases to their aliasee because they can't be represented
1468 // directly in SPIR-V.
1469 if (auto *const ConstAlias = dyn_cast<GlobalAlias>(V)) {
1470 return transValue(ConstAlias->getAliasee(), nullptr, false,
1471 FuncTransMode::Pointer);
1472 }
1473
1474 if (isa<UndefValue>(V)) {
1475 return BM->addUndef(ExpectedType);
1476 }
1477
1478 return nullptr;
1479 }
1480
1481 SPIRVValue *LLVMToSPIRVBase::transValue(Value *V, SPIRVBasicBlock *BB,
1482 bool CreateForward,
1483 FuncTransMode FuncTrans) {
1484 LLVMToSPIRVValueMap::iterator Loc = ValueMap.find(V);
1485 if (Loc != ValueMap.end() && (!Loc->second->isForward() || CreateForward) &&
1486 // do not return forward-decl of a function if we
1487 // actually want to create a function pointer
1488 !(FuncTrans == FuncTransMode::Pointer && isa<Function>(V)))
1489 return Loc->second;
1490
1491 SPIRVDBG(dbgs() << "[transValue] " << *V << '\n');
1492 assert((!isa<Instruction>(V) || isa<GetElementPtrInst>(V) ||
1493 isa<CastInst>(V) || isa<ExtractElementInst>(V) ||
1494 isa<BinaryOperator>(V) || BB) &&
1495 "Invalid SPIRV BB");
1496
1497 auto *BV = transValueWithoutDecoration(V, BB, CreateForward, FuncTrans);
1498 if (!BV)
1499 return nullptr;
1500 // Only translate decorations for non-forward instructions. Forward
1501 // instructions will have their decorations translated when the actual
1502 // instruction is seen and rewritten to a real SPIR-V instruction.
1503 if (!BV->isForward() && !transDecoration(V, BV))
1504 return nullptr;
1505 StringRef Name = V->getName();
1506 if (!Name.empty()) // Don't erase the name, which BM might already have
1507 BM->setName(BV, Name.str());
1508 return BV;
1509 }
1510
1511 SPIRVInstruction *LLVMToSPIRVBase::transBinaryInst(BinaryOperator *B,
1512 SPIRVBasicBlock *BB) {
1513 unsigned LLVMOC = B->getOpcode();
1514 auto Op0 = transValue(B->getOperand(0), BB);
1515 SPIRVInstruction *BI = BM->addBinaryInst(
1516 transBoolOpCode(Op0, OpCodeMap::map(LLVMOC)), transType(B->getType()),
1517 Op0, transValue(B->getOperand(1), BB), BB);
1518
1519 // BinaryOperator can have no parent if it is handled as an expression inside
1520 // another instruction.
1521 if (B->getParent() && isUnfusedMulAdd(B)) {
1522 Function *F = B->getFunction();
1523 SPIRVDBG(dbgs() << "[fp-contract] disabled for " << F->getName()
1524 << ": possible fma candidate " << *B << '\n');
1525 joinFPContract(F, FPContract::DISABLED);
1526 }
1527
1528 return BI;
1529 }
1530
1531 SPIRVInstruction *LLVMToSPIRVBase::transCmpInst(CmpInst *Cmp,
1532 SPIRVBasicBlock *BB) {
1533 auto *Op0 = Cmp->getOperand(0);
1534 SPIRVValue *TOp0 = transValue(Op0, BB);
1535 SPIRVValue *TOp1 = transValue(Cmp->getOperand(1), BB);
1536 if (Op0->getType()->isPointerTy()) {
1537 auto P = Cmp->getPredicate();
1538 if (BM->isAllowedToUseVersion(VersionNumber::SPIRV_1_4) &&
1539 (P == ICmpInst::ICMP_EQ || P == ICmpInst::ICMP_NE) &&
1540 Cmp->getOperand(1)->getType()->isPointerTy()) {
1541 Op OC = P == ICmpInst::ICMP_EQ ? OpPtrEqual : OpPtrNotEqual;
1542 return BM->addBinaryInst(OC, transType(Cmp->getType()), TOp0, TOp1, BB);
1543 }
1544 unsigned AS = cast<PointerType>(Op0->getType())->getAddressSpace();
1545 SPIRVType *Ty = transType(getSizetType(AS));
1546 TOp0 = BM->addUnaryInst(OpConvertPtrToU, Ty, TOp0, BB);
1547 TOp1 = BM->addUnaryInst(OpConvertPtrToU, Ty, TOp1, BB);
1548 }
1549 SPIRVInstruction *BI =
1550 BM->addCmpInst(transBoolOpCode(TOp0, CmpMap::map(Cmp->getPredicate())),
1551 transType(Cmp->getType()), TOp0, TOp1, BB);
1552 return BI;
1553 }
1554
1555 SPIRVValue *LLVMToSPIRVBase::transUnaryInst(UnaryInstruction *U,
1556 SPIRVBasicBlock *BB) {
1557 if (isa<BitCastInst>(U) && U->getType()->isPointerTy()) {
1558 if (isa<ConstantPointerNull>(U->getOperand(0))) {
1559 SPIRVType *ExpectedTy = transScavengedType(U);
1560 return BM->addNullConstant(bcast<SPIRVTypePointer>(ExpectedTy));
1561 }
1562 if (isa<UndefValue>(U->getOperand(0))) {
1563 SPIRVType *ExpectedTy = transScavengedType(U);
1564 return BM->addUndef(ExpectedTy);
1565 }
1566 }
1567
1568 Op BOC = OpNop;
1569 if (auto Cast = dyn_cast<AddrSpaceCastInst>(U)) {
1570 const auto SrcAddrSpace = Cast->getSrcTy()->getPointerAddressSpace();
1571 const auto DestAddrSpace = Cast->getDestTy()->getPointerAddressSpace();
1572 if (DestAddrSpace == SPIRAS_Generic) {
1573 getErrorLog().checkError(
1574 SrcAddrSpace != SPIRAS_Constant, SPIRVEC_InvalidModule, U,
1575 "Casts from constant address space to generic are illegal\n");
1576 BOC = OpPtrCastToGeneric;
1577 // In SPIR-V only casts to/from generic are allowed. But with
1578 // SPV_INTEL_usm_storage_classes we can also have casts from global_device
1579 // and global_host to global addr space and vice versa.
1580 } else if (SrcAddrSpace == SPIRAS_GlobalDevice ||
1581 SrcAddrSpace == SPIRAS_GlobalHost) {
1582 getErrorLog().checkError(DestAddrSpace == SPIRAS_Global ||
1583 DestAddrSpace == SPIRAS_Generic,
1584 SPIRVEC_InvalidModule, U,
1585 "Casts from global_device/global_host only "
1586 "allowed to global/generic\n");
1587 if (!BM->isAllowedToUseExtension(
1588 ExtensionID::SPV_INTEL_usm_storage_classes)) {
1589 if (DestAddrSpace == SPIRAS_Global)
1590 return nullptr;
1591 BOC = OpPtrCastToGeneric;
1592 } else {
1593 BOC = OpPtrCastToCrossWorkgroupINTEL;
1594 }
1595 } else if (DestAddrSpace == SPIRAS_GlobalDevice ||
1596 DestAddrSpace == SPIRAS_GlobalHost) {
1597 getErrorLog().checkError(SrcAddrSpace == SPIRAS_Global ||
1598 SrcAddrSpace == SPIRAS_Generic,
1599 SPIRVEC_InvalidModule, U,
1600 "Casts to global_device/global_host only "
1601 "allowed from global/generic\n");
1602 if (!BM->isAllowedToUseExtension(
1603 ExtensionID::SPV_INTEL_usm_storage_classes)) {
1604 if (SrcAddrSpace == SPIRAS_Global)
1605 return nullptr;
1606 BOC = OpGenericCastToPtr;
1607 } else {
1608 BOC = OpCrossWorkgroupCastToPtrINTEL;
1609 }
1610 } else {
1611 getErrorLog().checkError(
1612 SrcAddrSpace == SPIRAS_Generic, SPIRVEC_InvalidModule, U,
1613 "Casts from private/local/global address space are allowed only to "
1614 "generic\n");
1615 getErrorLog().checkError(
1616 DestAddrSpace != SPIRAS_Constant, SPIRVEC_InvalidModule, U,
1617 "Casts from generic address space to constant are illegal\n");
1618 BOC = OpGenericCastToPtr;
1619 }
1620 } else {
1621 auto OpCode = U->getOpcode();
1622 BOC = OpCodeMap::map(OpCode);
1623 }
1624
1625 auto Op = transValue(U->getOperand(0), BB, true, FuncTransMode::Pointer);
1626 SPIRVType *TransTy = transScavengedType(U);
1627 return BM->addUnaryInst(transBoolOpCode(Op, BOC), TransTy, Op, BB);
1628 }
1629
1630 /// This helper class encapsulates information extraction from
1631 /// "llvm.loop.parallel_access_indices" metadata hints. Initialize
1632 /// with a pointer to an MDNode with the following structure:
1633 /// !<Node> = !{!"llvm.loop.parallel_access_indices", !<Node>, !<Node>, ...}
1634 /// OR:
1635 /// !<Node> = !{!"llvm.loop.parallel_access_indices", !<Nodes...>, i32 <value>}
1636 ///
1637 /// All of the MDNode-type operands mark the index groups for particular
1638 /// array variables. An optional i32 value indicates the safelen (safe
1639 /// number of iterations) for the optimization application to these
1640 /// array variables. If the safelen value is absent, an infinite
1641 /// number of iterations is implied.
1642 class LLVMParallelAccessIndices {
1643 public:
1644 LLVMParallelAccessIndices(
1645 MDNode *Node, LLVMToSPIRVBase::LLVMToSPIRVMetadataMap &IndexGroupArrayMap)
1646 : Node(Node), IndexGroupArrayMap(IndexGroupArrayMap) {
1647
1648 assert(isValid() &&
1649 "LLVMParallelAccessIndices initialized from an invalid MDNode");
1650
1651 unsigned NumOperands = Node->getNumOperands();
1652 auto *SafeLenExpression = mdconst::dyn_extract_or_null<ConstantInt>(
1653 Node->getOperand(NumOperands - 1));
1654 // If no safelen value is specified and the last operand
1655 // casts to an MDNode* rather than an int, 0 will be stored
1656 SafeLen = SafeLenExpression ? SafeLenExpression->getZExtValue() : 0;
1657
1658 // Count MDNode operands that refer to index groups:
1659 // - operand [0] is a string literal and should be ignored;
1660 // - depending on whether a particular safelen is specified as the
1661 // last operand, we may or may not want to extract the latter
1662 // as an index group
1663 unsigned NumIdxGroups = SafeLen ? NumOperands - 2 : NumOperands - 1;
1664 for (unsigned I = 1; I <= NumIdxGroups; ++I) {
1665 MDNode *IdxGroupNode = getMDOperandAsMDNode(Node, I);
1666 assert(IdxGroupNode &&
1667 "Invalid operand in the MDNode for LLVMParallelAccessIndices");
1668 auto IdxGroupArrayPairIt = IndexGroupArrayMap.find(IdxGroupNode);
1669 // TODO: Some LLVM IR optimizations (e.g. loop inlining as part of
1670 // the function inlining) can result in invalid parallel_access_indices
1671 // metadata. Only valid cases will pass the subsequent check and
1672 // survive the translation. This check should be replaced with an
1673 // assertion once all known cases are handled.
1674 if (IdxGroupArrayPairIt != IndexGroupArrayMap.end())
1675 for (SPIRVId ArrayAccessId : IdxGroupArrayPairIt->second)
1676 ArrayVariablesVec.push_back(ArrayAccessId);
1677 }
1678 }
1679
1680 bool isValid() {
1681 bool IsNamedCorrectly = getMDOperandAsString(Node, 0) == ExpectedName;
1682 return Node && IsNamedCorrectly;
1683 }
1684
1685 unsigned getSafeLen() { return SafeLen; }
1686 const std::vector<SPIRVId> &getArrayVariables() { return ArrayVariablesVec; }
1687
1688 private:
1689 MDNode *Node;
1690 LLVMToSPIRVBase::LLVMToSPIRVMetadataMap &IndexGroupArrayMap;
1691 const std::string ExpectedName = "llvm.loop.parallel_access_indices";
1692 std::vector<SPIRVId> ArrayVariablesVec;
1693 unsigned SafeLen;
1694 };
1695
1696 /// Go through the operands !llvm.loop metadata attached to the branch
1697 /// instruction, fill the Loop Control mask and possible parameters for its
1698 /// fields.
1699 spv::LoopControlMask
1700 LLVMToSPIRVBase::getLoopControl(const BranchInst *Branch,
1701 std::vector<SPIRVWord> &Parameters) {
1702 if (!Branch)
1703 return spv::LoopControlMaskNone;
1704 MDNode *LoopMD = Branch->getMetadata("llvm.loop");
1705 if (!LoopMD)
1706 return spv::LoopControlMaskNone;
1707
1708 size_t LoopControl = spv::LoopControlMaskNone;
1709 std::vector<std::pair<SPIRVWord, SPIRVWord>> ParametersToSort;
1710 // If only a subset of loop count parameters is defined in metadata
1711 // then undefined ones should have a default value -1 in SPIR-V.
1712 // Preset all loop count parameters with the default value.
1713 struct LoopCountInfo {
1714 int64_t Min = -1, Max = -1, Avg = -1;
1715 } LoopCount;
1716
1717 // Unlike with most of the cases, some loop metadata specifications
1718 // can occur multiple times - for these, all correspondent tokens
1719 // need to be collected first, and only then added to SPIR-V loop
1720 // parameters in a separate routine
1721 std::vector<std::pair<SPIRVWord, SPIRVWord>> DependencyArrayParameters;
1722
1723 for (const MDOperand &MDOp : LoopMD->operands()) {
1724 if (MDNode *Node = dyn_cast<MDNode>(MDOp)) {
1725 StringRef S = getMDOperandAsString(Node, 0);
1726 // Set the loop control bits. Parameters are set in the order described
1727 // in 3.23 SPIR-V Spec. rev. 1.4:
1728 // Bits that are set can indicate whether an additional operand follows,
1729 // as described by the table. If there are multiple following operands
1730 // indicated, they are ordered: Those indicated by smaller-numbered bits
1731 // appear first.
1732 if (S == "llvm.loop.unroll.disable")
1733 LoopControl |= spv::LoopControlDontUnrollMask;
1734 else if (S == "llvm.loop.unroll.enable")
1735 LoopControl |= spv::LoopControlUnrollMask;
1736 // Attempt to do full unroll of the loop and disable unrolling if the trip
1737 // count is not known at compile time by setting PartialCount to 1
1738 else if (S == "llvm.loop.unroll.full") {
1739 LoopControl |= spv::LoopControlUnrollMask;
1740 if (BM->isAllowedToUseVersion(VersionNumber::SPIRV_1_4)) {
1741 BM->setMinSPIRVVersion(VersionNumber::SPIRV_1_4);
1742 ParametersToSort.emplace_back(spv::LoopControlPartialCountMask, 1);
1743 LoopControl |= spv::LoopControlPartialCountMask;
1744 }
1745 }
1746 // PartialCount must not be used with the DontUnroll bit
1747 else if (S == "llvm.loop.unroll.count" &&
1748 !(LoopControl & LoopControlDontUnrollMask)) {
1749 if (BM->isAllowedToUseVersion(VersionNumber::SPIRV_1_4)) {
1750 BM->setMinSPIRVVersion(VersionNumber::SPIRV_1_4);
1751 size_t I = getMDOperandAsInt(Node, 1);
1752 ParametersToSort.emplace_back(spv::LoopControlPartialCountMask, I);
1753 LoopControl |= spv::LoopControlPartialCountMask;
1754 }
1755 } else if (S == "llvm.loop.ivdep.enable")
1756 LoopControl |= spv::LoopControlDependencyInfiniteMask;
1757 else if (S == "llvm.loop.ivdep.safelen") {
1758 size_t I = getMDOperandAsInt(Node, 1);
1759 ParametersToSort.emplace_back(spv::LoopControlDependencyLengthMask, I);
1760 LoopControl |= spv::LoopControlDependencyLengthMask;
1761 } else if (BM->isAllowedToUseExtension(
1762 ExtensionID::SPV_INTEL_fpga_loop_controls)) {
1763 // Add Intel specific Loop Control masks
1764 if (S == "llvm.loop.ii.count") {
1765 BM->addExtension(ExtensionID::SPV_INTEL_fpga_loop_controls);
1766 BM->addCapability(CapabilityFPGALoopControlsINTEL);
1767 size_t I = getMDOperandAsInt(Node, 1);
1768 ParametersToSort.emplace_back(
1769 spv::LoopControlInitiationIntervalINTELMask, I);
1770 LoopControl |= spv::LoopControlInitiationIntervalINTELMask;
1771 } else if (S == "llvm.loop.max_concurrency.count") {
1772 BM->addExtension(ExtensionID::SPV_INTEL_fpga_loop_controls);
1773 BM->addCapability(CapabilityFPGALoopControlsINTEL);
1774 size_t I = getMDOperandAsInt(Node, 1);
1775 ParametersToSort.emplace_back(spv::LoopControlMaxConcurrencyINTELMask,
1776 I);
1777 LoopControl |= spv::LoopControlMaxConcurrencyINTELMask;
1778 } else if (S == "llvm.loop.parallel_access_indices") {
1779 // Intel FPGA IVDep loop attribute
1780 LLVMParallelAccessIndices IVDep(Node, IndexGroupArrayMap);
1781 // Store IVDep-specific parameters into an intermediate
1782 // container to address the case when there're multiple
1783 // IVDep metadata nodes and this condition gets entered multiple
1784 // times. The update of the main parameters vector & the loop control
1785 // mask will be done later, in the main scope of the function
1786 unsigned SafeLen = IVDep.getSafeLen();
1787 for (auto &ArrayId : IVDep.getArrayVariables())
1788 DependencyArrayParameters.emplace_back(ArrayId, SafeLen);
1789 } else if (S == "llvm.loop.intel.pipelining.enable") {
1790 BM->addExtension(ExtensionID::SPV_INTEL_fpga_loop_controls);
1791 BM->addCapability(CapabilityFPGALoopControlsINTEL);
1792 size_t I = getMDOperandAsInt(Node, 1);
1793 ParametersToSort.emplace_back(spv::LoopControlPipelineEnableINTELMask,
1794 I);
1795 LoopControl |= spv::LoopControlPipelineEnableINTELMask;
1796 } else if (S == "llvm.loop.coalesce.enable") {
1797 BM->addExtension(ExtensionID::SPV_INTEL_fpga_loop_controls);
1798 BM->addCapability(CapabilityFPGALoopControlsINTEL);
1799 ParametersToSort.emplace_back(spv::LoopControlLoopCoalesceINTELMask,
1800 0);
1801 LoopControl |= spv::LoopControlLoopCoalesceINTELMask;
1802 } else if (S == "llvm.loop.coalesce.count") {
1803 BM->addExtension(ExtensionID::SPV_INTEL_fpga_loop_controls);
1804 BM->addCapability(CapabilityFPGALoopControlsINTEL);
1805 size_t I = getMDOperandAsInt(Node, 1);
1806 ParametersToSort.emplace_back(spv::LoopControlLoopCoalesceINTELMask,
1807 I);
1808 LoopControl |= spv::LoopControlLoopCoalesceINTELMask;
1809 } else if (S == "llvm.loop.max_interleaving.count") {
1810 BM->addExtension(ExtensionID::SPV_INTEL_fpga_loop_controls);
1811 BM->addCapability(CapabilityFPGALoopControlsINTEL);
1812 size_t I = getMDOperandAsInt(Node, 1);
1813 ParametersToSort.emplace_back(
1814 spv::LoopControlMaxInterleavingINTELMask, I);
1815 LoopControl |= spv::LoopControlMaxInterleavingINTELMask;
1816 } else if (S == "llvm.loop.intel.speculated.iterations.count") {
1817 BM->addExtension(ExtensionID::SPV_INTEL_fpga_loop_controls);
1818 BM->addCapability(CapabilityFPGALoopControlsINTEL);
1819 size_t I = getMDOperandAsInt(Node, 1);
1820 ParametersToSort.emplace_back(
1821 spv::LoopControlSpeculatedIterationsINTELMask, I);
1822 LoopControl |= spv::LoopControlSpeculatedIterationsINTELMask;
1823 } else if (S == "llvm.loop.fusion.disable") {
1824 BM->addExtension(ExtensionID::SPV_INTEL_fpga_loop_controls);
1825 BM->addCapability(CapabilityFPGALoopControlsINTEL);
1826 LoopControl |= spv::LoopControlNoFusionINTELMask;
1827 } else if (S == "llvm.loop.intel.loopcount_min") {
1828 BM->addExtension(ExtensionID::SPV_INTEL_fpga_loop_controls);
1829 BM->addCapability(CapabilityFPGALoopControlsINTEL);
1830 LoopCount.Min = getMDOperandAsInt(Node, 1);
1831 LoopControl |= spv::LoopControlLoopCountINTELMask;
1832 } else if (S == "llvm.loop.intel.loopcount_max") {
1833 BM->addExtension(ExtensionID::SPV_INTEL_fpga_loop_controls);
1834 BM->addCapability(CapabilityFPGALoopControlsINTEL);
1835 LoopCount.Max = getMDOperandAsInt(Node, 1);
1836 LoopControl |= spv::LoopControlLoopCountINTELMask;
1837 } else if (S == "llvm.loop.intel.loopcount_avg") {
1838 BM->addExtension(ExtensionID::SPV_INTEL_fpga_loop_controls);
1839 BM->addCapability(CapabilityFPGALoopControlsINTEL);
1840 LoopCount.Avg = getMDOperandAsInt(Node, 1);
1841 LoopControl |= spv::LoopControlLoopCountINTELMask;
1842 } else if (S == "llvm.loop.intel.max_reinvocation_delay.count") {
1843 BM->addExtension(ExtensionID::SPV_INTEL_fpga_loop_controls);
1844 BM->addCapability(CapabilityFPGALoopControlsINTEL);
1845 size_t I = getMDOperandAsInt(Node, 1);
1846 ParametersToSort.emplace_back(
1847 spv::LoopControlMaxReinvocationDelayINTELMask, I);
1848 LoopControl |= spv::LoopControlMaxReinvocationDelayINTELMask;
1849 }
1850 }
1851 }
1852 }
1853 if (LoopControl & spv::LoopControlLoopCountINTELMask) {
1854 // LoopCountINTELMask have int64 literal parameters and we need to store
1855 // int64 into 2 SPIRVWords
1856 ParametersToSort.emplace_back(spv::LoopControlLoopCountINTELMask,
1857 static_cast<SPIRVWord>(LoopCount.Min));
1858 ParametersToSort.emplace_back(spv::LoopControlLoopCountINTELMask,
1859 static_cast<SPIRVWord>(LoopCount.Min >> 32));
1860 ParametersToSort.emplace_back(spv::LoopControlLoopCountINTELMask,
1861 static_cast<SPIRVWord>(LoopCount.Max));
1862 ParametersToSort.emplace_back(spv::LoopControlLoopCountINTELMask,
1863 static_cast<SPIRVWord>(LoopCount.Max >> 32));
1864 ParametersToSort.emplace_back(spv::LoopControlLoopCountINTELMask,
1865 static_cast<SPIRVWord>(LoopCount.Avg));
1866 ParametersToSort.emplace_back(spv::LoopControlLoopCountINTELMask,
1867 static_cast<SPIRVWord>(LoopCount.Avg >> 32));
1868 }
1869 // If any loop control parameters were held back until fully collected,
1870 // now is the time to move the information to the main parameters collection
1871 if (!DependencyArrayParameters.empty()) {
1872 // The first parameter states the number of <array, safelen> pairs to be
1873 // listed
1874 ParametersToSort.emplace_back(spv::LoopControlDependencyArrayINTELMask,
1875 DependencyArrayParameters.size());
1876 for (auto &ArraySflnPair : DependencyArrayParameters) {
1877 ParametersToSort.emplace_back(spv::LoopControlDependencyArrayINTELMask,
1878 ArraySflnPair.first);
1879 ParametersToSort.emplace_back(spv::LoopControlDependencyArrayINTELMask,
1880 ArraySflnPair.second);
1881 }
1882 BM->addExtension(ExtensionID::SPV_INTEL_fpga_loop_controls);
1883 BM->addCapability(CapabilityFPGALoopControlsINTEL);
1884 LoopControl |= spv::LoopControlDependencyArrayINTELMask;
1885 }
1886
1887 std::stable_sort(ParametersToSort.begin(), ParametersToSort.end(),
1888 [](const std::pair<SPIRVWord, SPIRVWord> &CompareLeft,
1889 const std::pair<SPIRVWord, SPIRVWord> &CompareRight) {
1890 return CompareLeft.first < CompareRight.first;
1891 });
1892 for (const auto &Param : ParametersToSort)
1893 Parameters.push_back(Param.second);
1894
1895 return static_cast<spv::LoopControlMask>(LoopControl);
1896 }
1897
1898 static int transAtomicOrdering(llvm::AtomicOrdering Ordering) {
1899 return OCLMemOrderMap::map(
1900 static_cast<OCLMemOrderKind>(llvm::toCABI(Ordering)));
1901 }
1902
1903 SPIRVValue *LLVMToSPIRVBase::transAtomicStore(StoreInst *ST,
1904 SPIRVBasicBlock *BB) {
1905 std::vector<Value *> Ops{ST->getPointerOperand(),
1906 getUInt32(M, spv::ScopeDevice),
1907 getUInt32(M, transAtomicOrdering(ST->getOrdering())),
1908 ST->getValueOperand()};
1909 std::vector<SPIRVValue *> SPIRVOps = transValue(Ops, BB);
1910
1911 return mapValue(ST, BM->addInstTemplate(OpAtomicStore, BM->getIds(SPIRVOps),
1912 BB, nullptr));
1913 }
1914
1915 SPIRVValue *LLVMToSPIRVBase::transAtomicLoad(LoadInst *LD,
1916 SPIRVBasicBlock *BB) {
1917 std::vector<Value *> Ops{
1918 LD->getPointerOperand(), getUInt32(M, spv::ScopeDevice),
1919 getUInt32(M, transAtomicOrdering(LD->getOrdering()))};
1920 std::vector<SPIRVValue *> SPIRVOps = transValue(Ops, BB);
1921
1922 return mapValue(LD, BM->addInstTemplate(OpAtomicLoad, BM->getIds(SPIRVOps),
1923 BB, transType(LD->getType())));
1924 }
1925
1926 // Aliasing list MD contains several scope MD nodes whithin it. Each scope MD
1927 // has a selfreference and an extra MD node for aliasing domain and also it
1928 // can contain an optional string operand. Domain MD contains a self-reference
1929 // with an optional string operand. Here we unfold the list, creating SPIR-V
1930 // aliasing instructions.
1931 // TODO: add support for an optional string operand.
1932 SPIRVEntry *addMemAliasingINTELInstructions(SPIRVModule *M,
1933 MDNode *AliasingListMD) {
1934 if (AliasingListMD->getNumOperands() == 0)
1935 return nullptr;
1936 std::vector<SPIRVId> ListId;
1937 for (const MDOperand &MDListOp : AliasingListMD->operands()) {
1938 if (MDNode *ScopeMD = dyn_cast<MDNode>(MDListOp)) {
1939 if (ScopeMD->getNumOperands() < 2)
1940 return nullptr;
1941 MDNode *DomainMD = dyn_cast<MDNode>(ScopeMD->getOperand(1));
1942 if (!DomainMD)
1943 return nullptr;
1944 auto *Domain =
1945 M->getOrAddAliasDomainDeclINTELInst(std::vector<SPIRVId>(), DomainMD);
1946 auto *Scope =
1947 M->getOrAddAliasScopeDeclINTELInst({Domain->getId()}, ScopeMD);
1948 ListId.push_back(Scope->getId());
1949 }
1950 }
1951 return M->getOrAddAliasScopeListDeclINTELInst(ListId, AliasingListMD);
1952 }
1953
1954 // Translate alias.scope/noalias metadata attached to store and load
1955 // instructions.
1956 void transAliasingMemAccess(SPIRVModule *BM, MDNode *AliasingListMD,
1957 std::vector<uint32_t> &MemoryAccess,
1958 SPIRVWord MemAccessMask) {
1959 if (!BM->isAllowedToUseExtension(
1960 ExtensionID::SPV_INTEL_memory_access_aliasing))
1961 return;
1962 auto *MemAliasList = addMemAliasingINTELInstructions(BM, AliasingListMD);
1963 if (!MemAliasList)
1964 return;
1965 MemoryAccess[0] |= MemAccessMask;
1966 MemoryAccess.push_back(MemAliasList->getId());
1967 }
1968
1969 /// An instruction may use an instruction from another BB which has not been
1970 /// translated. SPIRVForward should be created as place holder for these
1971 /// instructions and replaced later by the real instructions.
1972 /// Use CreateForward = true to indicate such situation.
1973 SPIRVValue *
1974 LLVMToSPIRVBase::transValueWithoutDecoration(Value *V, SPIRVBasicBlock *BB,
1975 bool CreateForward,
1976 FuncTransMode FuncTrans) {
1977 if (auto LBB = dyn_cast<BasicBlock>(V)) {
1978 auto BF =
1979 static_cast<SPIRVFunction *>(getTranslatedValue(LBB->getParent()));
1980 assert(BF && "Function not translated");
1981 BB = static_cast<SPIRVBasicBlock *>(mapValue(V, BM->addBasicBlock(BF)));
1982 BM->setName(BB, LBB->getName().str());
1983 return BB;
1984 }
1985
1986 if (auto *F = dyn_cast<Function>(V)) {
1987 if (FuncTrans == FuncTransMode::Decl)
1988 return transFunctionDecl(F);
1989 if (!BM->checkExtension(ExtensionID::SPV_INTEL_function_pointers,
1990 SPIRVEC_FunctionPointers, toString(V)))
1991 return nullptr;
1992 return BM->addConstantFunctionPointerINTEL(
1993 transPointerType(transScavengedType(F), F->getAddressSpace()),
1994 static_cast<SPIRVFunction *>(transValue(F, nullptr)));
1995 }
1996
1997 if (auto GV = dyn_cast<GlobalVariable>(V)) {
1998 llvm::Type *Ty = Scavenger->getScavengedType(GV);
1999 // Though variables with common linkage type are initialized by 0,
2000 // they can be represented in SPIR-V as uninitialized variables with
2001 // 'Export' linkage type, just as tentative definitions look in C
2002 llvm::Value *Init = GV->hasInitializer() && !GV->hasCommonLinkage()
2003 ? GV->getInitializer()
2004 : nullptr;
2005 SPIRVValue *BVarInit = nullptr;
2006 StructType *ST = Init ? dyn_cast<StructType>(Init->getType()) : nullptr;
2007 if (ST && ST->hasName() && isSPIRVConstantName(ST->getName())) {
2008 auto BV = transConstant(Init);
2009 assert(BV);
2010 return mapValue(V, BV);
2011 } else if (ConstantExpr *ConstUE = dyn_cast_or_null<ConstantExpr>(Init)) {
2012 Value *SpecialInit = unwrapSpecialTypeInitializer(ConstUE);
2013 if (auto *SpecialGV = dyn_cast_or_null<GlobalValue>(SpecialInit)) {
2014 Init = SpecialGV;
2015 Ty = Scavenger->getScavengedType(SpecialGV);
2016 }
2017 BVarInit = transValue(Init, nullptr);
2018 } else if (ST && isa<UndefValue>(Init)) {
2019 // Undef initializer for LLVM structure be can translated to
2020 // OpConstantComposite with OpUndef constituents.
2021 auto I = ValueMap.find(Init);
2022 if (I == ValueMap.end()) {
2023 std::vector<SPIRVValue *> Elements;
2024 for (Type *E : ST->elements())
2025 Elements.push_back(transValue(UndefValue::get(E), nullptr));
2026 BVarInit = BM->addCompositeConstant(transType(ST), Elements);
2027 ValueMap[Init] = BVarInit;
2028 } else
2029 BVarInit = I->second;
2030 } else if (Init && !isa<UndefValue>(Init)) {
2031 if (!BM->isAllowedToUseExtension(
2032 ExtensionID::SPV_INTEL_long_constant_composite)) {
2033 if (auto ArrTy = dyn_cast_or_null<ArrayType>(Init->getType())) {
2034 // First 3 words of OpConstantComposite encode: 1) word count &
2035 // opcode, 2) Result Type and 3) Result Id. Max length of SPIRV
2036 // instruction = 65535 words.
2037 constexpr int MaxNumElements =
2038 MaxWordCount - SPIRVSpecConstantComposite::FixedWC;
2039 if (ArrTy->getNumElements() > MaxNumElements &&
2040 !isa<ConstantAggregateZero>(Init)) {
2041 std::stringstream SS;
2042 SS << "Global variable has a constant array initializer with a "
2043 << "number of elements greater than OpConstantComposite can "
2044 << "have (" << MaxNumElements << "). Should the array be "
2045 << "split?\n Original LLVM value:\n"
2046 << toString(GV);
2047 getErrorLog().checkError(false, SPIRVEC_InvalidWordCount, SS.str());
2048 }
2049 }
2050 }
2051 // As global variables define a pointer to their "content" type, we should
2052 // translate here only pointer without declaration even if it is a
2053 // function pointer.
2054 BVarInit = transValue(Init, nullptr, true, FuncTransMode::Pointer);
2055 }
2056
2057 SPIRVStorageClassKind StorageClass;
2058 auto AddressSpace = static_cast<SPIRAddressSpace>(GV->getAddressSpace());
2059 bool IsVectorCompute =
2060 BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_vector_compute) &&
2061 GV->hasAttribute(kVCMetadata::VCGlobalVariable);
2062 if (IsVectorCompute)
2063 StorageClass =
2064 VectorComputeUtil::getVCGlobalVarStorageClass(AddressSpace);
2065 else {
2066 // Lower global_device and global_host address spaces that were added in
2067 // SYCL as part of SYCL_INTEL_usm_address_spaces extension to just global
2068 // address space if device doesn't support SPV_INTEL_usm_storage_classes
2069 // extension
2070 if ((AddressSpace == SPIRAS_GlobalDevice ||
2071 AddressSpace == SPIRAS_GlobalHost) &&
2072 !BM->isAllowedToUseExtension(
2073 ExtensionID::SPV_INTEL_usm_storage_classes))
2074 AddressSpace = SPIRAS_Global;
2075 StorageClass = SPIRSPIRVAddrSpaceMap::map(AddressSpace);
2076 }
2077
2078 SPIRVType *TranslatedTy = transType(Ty);
2079 auto BVar = static_cast<SPIRVVariable *>(
2080 BM->addVariable(TranslatedTy, GV->isConstant(), transLinkageType(GV),
2081 BVarInit, GV->getName().str(), StorageClass, nullptr));
2082
2083 if (IsVectorCompute) {
2084 BVar->addDecorate(DecorationVectorComputeVariableINTEL);
2085 if (GV->hasAttribute(kVCMetadata::VCByteOffset)) {
2086 SPIRVWord Offset = {};
2087 GV->getAttribute(kVCMetadata::VCByteOffset)
2088 .getValueAsString()
2089 .getAsInteger(0, Offset);
2090 BVar->addDecorate(DecorationGlobalVariableOffsetINTEL, Offset);
2091 }
2092 if (GV->hasAttribute(kVCMetadata::VCVolatile))
2093 BVar->addDecorate(DecorationVolatile);
2094
2095 if (GV->hasAttribute(kVCMetadata::VCSingleElementVector))
2096 translateSEVDecoration(
2097 GV->getAttribute(kVCMetadata::VCSingleElementVector), BVar);
2098 }
2099
2100 mapValue(V, BVar);
2101 spv::BuiltIn Builtin = spv::BuiltInPosition;
2102 if (!GV->hasName() || !getSPIRVBuiltin(GV->getName().str(), Builtin))
2103 return BVar;
2104 if (static_cast<uint32_t>(Builtin) >= internal::BuiltInSubDeviceIDINTEL &&
2105 static_cast<uint32_t>(Builtin) <=
2106 internal::BuiltInGlobalHWThreadIDINTEL) {
2107 std::string ErrorStr = "SPV_INTEL_hw_thread_queries\n"
2108 "Please report to "
2109 "https://github.com/intel/llvm in case if you see "
2110 "this error.\nRef LLVM Value:";
2111 getErrorLog().checkError(false, SPIRVEC_DeprecatedExtension, V, ErrorStr);
2112 }
2113
2114 BVar->setBuiltin(Builtin);
2115 return BVar;
2116 }
2117
2118 if (isa<Constant>(V)) {
2119 auto BV = transConstant(V);
2120 assert(BV);
2121 // Don't store opaque pointer constants in the map--we might reuse the wrong
2122 // type for (e.g.) a null value if we do so.
2123 if (V->getType()->isOpaquePointerTy())
2124 return BV;
2125 return mapValue(V, BV);
2126 }
2127
2128 if (auto Arg = dyn_cast<Argument>(V)) {
2129 unsigned ArgNo = Arg->getArgNo();
2130 SPIRVFunction *BF = BB->getParent();
2131 // assert(BF->existArgument(ArgNo));
2132 return mapValue(V, BF->getArgument(ArgNo));
2133 }
2134
2135 if (CreateForward)
2136 return mapValue(V, BM->addForward(transScavengedType(V)));
2137
2138 if (StoreInst *ST = dyn_cast<StoreInst>(V)) {
2139 if (ST->isAtomic())
2140 return transAtomicStore(ST, BB);
2141
2142 // Keep this vector to store MemoryAccess operands for both Alignment and
2143 // Aliasing information.
2144 std::vector<SPIRVWord> MemoryAccess(1, 0);
2145 if (ST->isVolatile())
2146 MemoryAccess[0] |= MemoryAccessVolatileMask;
2147 MemoryAccess[0] |= MemoryAccessAlignedMask;
2148 MemoryAccess.push_back(ST->getAlign().value());
2149 if (ST->getMetadata(LLVMContext::MD_nontemporal))
2150 MemoryAccess[0] |= MemoryAccessNontemporalMask;
2151 if (MDNode *AliasingListMD = ST->getMetadata(LLVMContext::MD_alias_scope))
2152 transAliasingMemAccess(BM, AliasingListMD, MemoryAccess,
2153 MemoryAccessAliasScopeINTELMaskMask);
2154 if (MDNode *AliasingListMD = ST->getMetadata(LLVMContext::MD_noalias))
2155 transAliasingMemAccess(BM, AliasingListMD, MemoryAccess,
2156 MemoryAccessNoAliasINTELMaskMask);
2157 if (MemoryAccess.front() == 0)
2158 MemoryAccess.clear();
2159
2160 return mapValue(V,
2161 BM->addStoreInst(transValue(ST->getPointerOperand(), BB),
2162 transValue(ST->getValueOperand(), BB, true,
2163 FuncTransMode::Pointer),
2164 MemoryAccess, BB));
2165 }
2166
2167 if (LoadInst *LD = dyn_cast<LoadInst>(V)) {
2168 if (LD->isAtomic())
2169 return transAtomicLoad(LD, BB);
2170
2171 // Keep this vector to store MemoryAccess operands for both Alignment and
2172 // Aliasing information.
2173 std::vector<uint32_t> MemoryAccess(1, 0);
2174 if (LD->isVolatile())
2175 MemoryAccess[0] |= MemoryAccessVolatileMask;
2176 MemoryAccess[0] |= MemoryAccessAlignedMask;
2177 MemoryAccess.push_back(LD->getAlign().value());
2178 if (LD->getMetadata(LLVMContext::MD_nontemporal))
2179 MemoryAccess[0] |= MemoryAccessNontemporalMask;
2180 if (MDNode *AliasingListMD = LD->getMetadata(LLVMContext::MD_alias_scope))
2181 transAliasingMemAccess(BM, AliasingListMD, MemoryAccess,
2182 MemoryAccessAliasScopeINTELMaskMask);
2183 if (MDNode *AliasingListMD = LD->getMetadata(LLVMContext::MD_noalias))
2184 transAliasingMemAccess(BM, AliasingListMD, MemoryAccess,
2185 MemoryAccessNoAliasINTELMaskMask);
2186 if (MemoryAccess.front() == 0)
2187 MemoryAccess.clear();
2188 return mapValue(V, BM->addLoadInst(transValue(LD->getPointerOperand(), BB),
2189 MemoryAccess, BB));
2190 }
2191
2192 if (BinaryOperator *B = dyn_cast<BinaryOperator>(V)) {
2193 SPIRVInstruction *BI = transBinaryInst(B, BB);
2194 return mapValue(V, BI);
2195 }
2196
2197 if (dyn_cast<UnreachableInst>(V))
2198 return mapValue(V, BM->addUnreachableInst(BB));
2199
2200 if (auto RI = dyn_cast<ReturnInst>(V)) {
2201 if (auto RV = RI->getReturnValue())
2202 return mapValue(V, BM->addReturnValueInst(transValue(RV, BB), BB));
2203 return mapValue(V, BM->addReturnInst(BB));
2204 }
2205
2206 if (CmpInst *Cmp = dyn_cast<CmpInst>(V)) {
2207 SPIRVInstruction *BI = transCmpInst(Cmp, BB);
2208 return mapValue(V, BI);
2209 }
2210
2211 if (SelectInst *Sel = dyn_cast<SelectInst>(V))
2212 return mapValue(
2213 V,
2214 BM->addSelectInst(
2215 transValue(Sel->getCondition(), BB),
2216 transValue(Sel->getTrueValue(), BB, true, FuncTransMode::Pointer),
2217 transValue(Sel->getFalseValue(), BB, true, FuncTransMode::Pointer),
2218 BB));
2219
2220 if (AllocaInst *Alc = dyn_cast<AllocaInst>(V)) {
2221 SPIRVType *TranslatedTy = transScavengedType(V);
2222 if (Alc->isArrayAllocation()) {
2223 if (!BM->checkExtension(ExtensionID::SPV_INTEL_variable_length_array,
2224 SPIRVEC_InvalidInstruction,
2225 toString(Alc) +
2226 "\nTranslation of dynamic alloca requires "
2227 "SPV_INTEL_variable_length_array extension."))
2228 return nullptr;
2229
2230 SPIRVValue *Length = transValue(Alc->getArraySize(), BB);
2231 assert(Length && "Couldn't translate array size!");
2232 return mapValue(V,
2233 BM->addInstTemplate(OpVariableLengthArrayINTEL,
2234 {Length->getId()}, BB, TranslatedTy));
2235 }
2236 return mapValue(V, BM->addVariable(TranslatedTy, false,
2237 spv::internal::LinkageTypeInternal,
2238 nullptr, Alc->getName().str(),
2239 StorageClassFunction, BB));
2240 }
2241
2242 if (auto *Switch = dyn_cast<SwitchInst>(V)) {
2243 std::vector<SPIRVSwitch::PairTy> Pairs;
2244 auto Select = transValue(Switch->getCondition(), BB);
2245
2246 for (auto I = Switch->case_begin(), E = Switch->case_end(); I != E; ++I) {
2247 SPIRVSwitch::LiteralTy Lit;
2248 uint64_t CaseValue = I->getCaseValue()->getZExtValue();
2249
2250 Lit.push_back(CaseValue);
2251 assert(Select->getType()->getBitWidth() <= 64 &&
2252 "unexpected selector bitwidth");
2253 if (Select->getType()->getBitWidth() == 64)
2254 Lit.push_back(CaseValue >> 32);
2255
2256 Pairs.push_back(
2257 std::make_pair(Lit, static_cast<SPIRVBasicBlock *>(
2258 transValue(I->getCaseSuccessor(), nullptr))));
2259 }
2260
2261 return mapValue(
2262 V, BM->addSwitchInst(Select,
2263 static_cast<SPIRVBasicBlock *>(
2264 transValue(Switch->getDefaultDest(), nullptr)),
2265 Pairs, BB));
2266 }
2267
2268 if (BranchInst *Branch = dyn_cast<BranchInst>(V)) {
2269 SPIRVLabel *SuccessorTrue =
2270 static_cast<SPIRVLabel *>(transValue(Branch->getSuccessor(0), BB));
2271
2272 /// Clang attaches !llvm.loop metadata to "latch" BB. This kind of blocks
2273 /// has an edge directed to the loop header. Thus latch BB matching to
2274 /// "Continue Target" per the SPIR-V spec. This statement is true only after
2275 /// applying the loop-simplify pass to the LLVM module.
2276 /// For "for" and "while" loops latch BB is terminated by an
2277 /// unconditional branch. Also for this kind of loops "Merge Block" can
2278 /// be found as block targeted by false edge of the "Header" BB.
2279 /// For "do while" loop the latch is terminated by a conditional branch
2280 /// with true edge going to the header and the false edge going out of
2281 /// the loop, which corresponds to a "Merge Block" per the SPIR-V spec.
2282 std::vector<SPIRVWord> Parameters;
2283 spv::LoopControlMask LoopControl = getLoopControl(Branch, Parameters);
2284
2285 if (Branch->isUnconditional()) {
2286 // Usually, "for" and "while" loops llvm.loop metadata is attached to an
2287 // unconditional branch instruction.
2288 if (LoopControl != spv::LoopControlMaskNone) {
2289 // SuccessorTrue is the loop header BB.
2290 const SPIRVInstruction *Term = SuccessorTrue->getTerminateInstr();
2291 if (Term && Term->getOpCode() == OpBranchConditional) {
2292 const auto *Br = static_cast<const SPIRVBranchConditional *>(Term);
2293 BM->addLoopMergeInst(Br->getFalseLabel()->getId(), // Merge Block
2294 BB->getId(), // Continue Target
2295 LoopControl, Parameters, SuccessorTrue);
2296 } else {
2297 if (BM->isAllowedToUseExtension(
2298 ExtensionID::SPV_INTEL_unstructured_loop_controls)) {
2299 // For unstructured loop we add a special loop control instruction.
2300 // Simple example of unstructured loop is an infinite loop, that has
2301 // no terminate instruction.
2302 BM->addLoopControlINTELInst(LoopControl, Parameters, SuccessorTrue);
2303 }
2304 }
2305 }
2306 return mapValue(V, BM->addBranchInst(SuccessorTrue, BB));
2307 }
2308 // For "do-while" (and in some cases, for "for" and "while") loops,
2309 // llvm.loop metadata is attached to a conditional branch instructions
2310 SPIRVLabel *SuccessorFalse =
2311 static_cast<SPIRVLabel *>(transValue(Branch->getSuccessor(1), BB));
2312 if (LoopControl != spv::LoopControlMaskNone) {
2313 Function *Fun = Branch->getFunction();
2314 DominatorTree DomTree(*Fun);
2315 LoopInfo LI(DomTree);
2316 for (const auto *LoopObj : LI.getLoopsInPreorder()) {
2317 // Check whether SuccessorFalse or SuccessorTrue is the loop header BB.
2318 // For example consider following LLVM IR:
2319 // br i1 %compare, label %for.body, label %for.end
2320 // <- SuccessorTrue is 'for.body' aka successor(0)
2321 // br i1 %compare.not, label %for.end, label %for.body
2322 // <- SuccessorTrue is 'for.end' aka successor(1)
2323 // meanwhile the true successor (by definition) should be a loop header
2324 // aka 'for.body'
2325 if (LoopObj->getHeader() == Branch->getSuccessor(1))
2326 // SuccessorFalse is the loop header BB.
2327 BM->addLoopMergeInst(SuccessorTrue->getId(), // Merge Block
2328 BB->getId(), // Continue Target
2329 LoopControl, Parameters, SuccessorFalse);
2330 else
2331 // SuccessorTrue is the loop header BB.
2332 BM->addLoopMergeInst(SuccessorFalse->getId(), // Merge Block
2333 BB->getId(), // Continue Target
2334 LoopControl, Parameters, SuccessorTrue);
2335 }
2336 }
2337 return mapValue(
2338 V, BM->addBranchConditionalInst(transValue(Branch->getCondition(), BB),
2339 SuccessorTrue, SuccessorFalse, BB));
2340 }
2341
2342 if (auto Phi = dyn_cast<PHINode>(V)) {
2343 std::vector<SPIRVValue *> IncomingPairs;
2344
2345 for (size_t I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
2346 IncomingPairs.push_back(transValue(Phi->getIncomingValue(I), BB, true,
2347 FuncTransMode::Pointer));
2348 IncomingPairs.push_back(transValue(Phi->getIncomingBlock(I), nullptr));
2349 }
2350 return mapValue(V,
2351 BM->addPhiInst(transScavengedType(Phi), IncomingPairs, BB));
2352 }
2353
2354 if (auto Ext = dyn_cast<ExtractValueInst>(V)) {
2355 return mapValue(V, BM->addCompositeExtractInst(
2356 transType(Ext->getType()),
2357 transValue(Ext->getAggregateOperand(), BB),
2358 Ext->getIndices(), BB));
2359 }
2360
2361 if (auto Ins = dyn_cast<InsertValueInst>(V)) {
2362 return mapValue(V, BM->addCompositeInsertInst(
2363 transValue(Ins->getInsertedValueOperand(), BB),
2364 transValue(Ins->getAggregateOperand(), BB),
2365 Ins->getIndices(), BB));
2366 }
2367
2368 if (UnaryInstruction *U = dyn_cast<UnaryInstruction>(V)) {
2369 if (auto *Init = unwrapSpecialTypeInitializer(U))
2370 return mapValue(V, transValue(Init, BB));
2371 auto UI = transUnaryInst(U, BB);
2372 return mapValue(V, UI ? UI : transValue(U->getOperand(0), BB));
2373 }
2374
2375 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
2376 std::vector<SPIRVValue *> Indices;
2377 for (unsigned I = 0, E = GEP->getNumIndices(); I != E; ++I)
2378 Indices.push_back(transValue(GEP->getOperand(I + 1), BB));
2379 auto *PointerOperand = GEP->getPointerOperand();
2380 auto *TransPointerOperand = transValue(PointerOperand, BB);
2381
2382 // Certain array-related optimization hints can be expressed via
2383 // LLVM metadata. For the purpose of linking this metadata with
2384 // the accessed array variables, our GEP may have been marked into
2385 // a so-called index group, an MDNode by itself.
2386 if (MDNode *IndexGroup = GEP->getMetadata("llvm.index.group")) {
2387 SPIRVValue *ActualMemoryPtr = TransPointerOperand;
2388 if (auto *Load = dyn_cast<LoadInst>(PointerOperand)) {
2389 ActualMemoryPtr = transValue(Load->getPointerOperand(), BB);
2390 }
2391 SPIRVId AccessedArrayId = ActualMemoryPtr->getId();
2392 unsigned NumOperands = IndexGroup->getNumOperands();
2393 // When we're working with embedded loops, it's natural that
2394 // the outer loop's hints apply to all code contained within.
2395 // The inner loop's specific hints, however, should stay private
2396 // to the inner loop's scope.
2397 // Consequently, the following division of the index group metadata
2398 // nodes emerges:
2399
2400 // 1) The metadata node has no operands. It will be directly referenced
2401 // from within the optimization hint metadata.
2402 if (NumOperands == 0)
2403 IndexGroupArrayMap[IndexGroup].insert(AccessedArrayId);
2404 // 2) The metadata node has several operands. It serves to link an index
2405 // group specific to some embedded loop with other index groups that
2406 // mark the same array variable for the outer loop(s).
2407 for (unsigned I = 0; I < NumOperands; ++I) {
2408 auto *ContainedIndexGroup = getMDOperandAsMDNode(IndexGroup, I);
2409 IndexGroupArrayMap[ContainedIndexGroup].insert(AccessedArrayId);
2410 }
2411 }
2412 // GEP can return a vector of pointers, in this case GEP will calculate
2413 // addresses for each pointer in the vector
2414 SPIRVType *TranslatedTy = transScavengedType(GEP);
2415 return mapValue(V,
2416 BM->addPtrAccessChainInst(TranslatedTy, TransPointerOperand,
2417 Indices, BB, GEP->isInBounds()));
2418 }
2419
2420 if (auto Ext = dyn_cast<ExtractElementInst>(V)) {
2421 auto Index = Ext->getIndexOperand();
2422 if (auto Const = dyn_cast<ConstantInt>(Index))
2423 return mapValue(V, BM->addCompositeExtractInst(
2424 transType(Ext->getType()),
2425 transValue(Ext->getVectorOperand(), BB),
2426 std::vector<SPIRVWord>(1, Const->getZExtValue()),
2427 BB));
2428 else
2429 return mapValue(V, BM->addVectorExtractDynamicInst(
2430 transValue(Ext->getVectorOperand(), BB),
2431 transValue(Index, BB), BB));
2432 }
2433
2434 if (auto Ins = dyn_cast<InsertElementInst>(V)) {
2435 auto Index = Ins->getOperand(2);
2436 if (auto Const = dyn_cast<ConstantInt>(Index)) {
2437 return mapValue(
2438 V,
2439 BM->addCompositeInsertInst(
2440 transValue(Ins->getOperand(1), BB, true, FuncTransMode::Pointer),
2441 transValue(Ins->getOperand(0), BB),
2442 std::vector<SPIRVWord>(1, Const->getZExtValue()), BB));
2443 } else
2444 return mapValue(
2445 V, BM->addVectorInsertDynamicInst(transValue(Ins->getOperand(0), BB),
2446 transValue(Ins->getOperand(1), BB),
2447 transValue(Index, BB), BB));
2448 }
2449
2450 if (auto SF = dyn_cast<ShuffleVectorInst>(V)) {
2451 std::vector<SPIRVWord> Comp;
2452 for (auto &I : SF->getShuffleMask())
2453 Comp.push_back(I);
2454 return mapValue(V, BM->addVectorShuffleInst(
2455 transType(SF->getType()),
2456 transValue(SF->getOperand(0), BB),
2457 transValue(SF->getOperand(1), BB), Comp, BB));
2458 }
2459
2460 if (AtomicRMWInst *ARMW = dyn_cast<AtomicRMWInst>(V)) {
2461 AtomicRMWInst::BinOp Op = ARMW->getOperation();
2462 bool SupportedAtomicInst =
2463 AtomicRMWInst::isFPOperation(Op)
2464 ? (Op == AtomicRMWInst::FAdd || Op == AtomicRMWInst::FSub ||
2465 Op == AtomicRMWInst::FMin || Op == AtomicRMWInst::FMax)
2466 : Op != AtomicRMWInst::Nand;
2467 if (!BM->getErrorLog().checkError(
2468 SupportedAtomicInst, SPIRVEC_InvalidInstruction, V,
2469 "Atomic " + AtomicRMWInst::getOperationName(Op).str() +
2470 " is not supported in SPIR-V!\n"))
2471 return nullptr;
2472
2473 AtomicOrderingCABI Ordering = llvm::toCABI(ARMW->getOrdering());
2474 auto MemSem = OCLMemOrderMap::map(static_cast<OCLMemOrderKind>(Ordering));
2475 std::vector<Value *> Operands(4);
2476 Operands[0] = ARMW->getPointerOperand();
2477 // To get the memory scope argument we might use ARMW->getSyncScopeID(), but
2478 // atomicrmw LLVM instruction is not aware of OpenCL(or SPIR-V) memory scope
2479 // enumeration. And assuming the produced SPIR-V module will be consumed in
2480 // an OpenCL environment, we can use the same memory scope as OpenCL atomic
2481 // functions that don't have memory_scope argument i.e. memory_scope_device.
2482 // See the OpenCL C specification p6.13.11. "Atomic Functions"
2483 Operands[1] = getUInt32(M, spv::ScopeDevice);
2484 Operands[2] = getUInt32(M, MemSem);
2485 Operands[3] = ARMW->getValOperand();
2486 std::vector<SPIRVValue *> OpVals = transValue(Operands, BB);
2487 std::vector<SPIRVId> Ops = BM->getIds(OpVals);
2488 SPIRVType *Ty = transType(ARMW->getType());
2489
2490 spv::Op OC;
2491 if (Op == AtomicRMWInst::FSub) {
2492 // Implement FSub through FNegate and AtomicFAddExt
2493 Ops[3] = BM->addUnaryInst(OpFNegate, Ty, OpVals[3], BB)->getId();
2494 OC = OpAtomicFAddEXT;
2495 } else
2496 OC = LLVMSPIRVAtomicRmwOpCodeMap::map(Op);
2497
2498 return mapValue(V, BM->addInstTemplate(OC, Ops, BB, Ty));
2499 }
2500
2501 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(V)) {
2502 SPIRVValue *BV = transIntrinsicInst(II, BB);
2503 return BV ? mapValue(V, BV) : nullptr;
2504 }
2505
2506 if (FenceInst *FI = dyn_cast<FenceInst>(V)) {
2507 SPIRVValue *BV = transFenceInst(FI, BB);
2508 return BV ? mapValue(V, BV) : nullptr;
2509 }
2510
2511 if (InlineAsm *IA = dyn_cast<InlineAsm>(V))
2512 if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_inline_assembly))
2513 return mapValue(V, transAsmINTEL(IA));
2514
2515 if (CallInst *CI = dyn_cast<CallInst>(V)) {
2516 if (auto Alias =
2517 dyn_cast_or_null<llvm::GlobalAlias>(CI->getCalledOperand())) {
2518 CI->setCalledFunction(cast<Function>(Alias->getAliasee()));
2519 }
2520 return mapValue(V, transCallInst(CI, BB));
2521 }
2522
2523 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
2524 BM->SPIRVCK(false, InvalidInstruction, toString(Inst));
2525 }
2526
2527 llvm_unreachable("Not implemented");
2528 return nullptr;
2529 }
2530
2531 SPIRVType *LLVMToSPIRVBase::mapType(Type *T, SPIRVType *BT) {
2532 assert(!T->isPointerTy() && "Pointer types cannot be stored in the type map");
2533 auto EmplaceStatus = TypeMap.try_emplace(T, BT);
2534 // TODO: Uncomment the assertion, once the type mapping issue is resolved
2535 // assert(EmplaceStatus.second && "The type was already added to the map");
2536 SPIRVDBG(dbgs() << "[mapType] " << *T << " => "; spvdbgs() << *BT << '\n');
2537 if (!EmplaceStatus.second)
2538 return TypeMap[T];
2539 return BT;
2540 }
2541
2542 SPIRVValue *LLVMToSPIRVBase::mapValue(Value *V, SPIRVValue *BV) {
2543 auto Loc = ValueMap.find(V);
2544 if (Loc != ValueMap.end()) {
2545 if (Loc->second == BV)
2546 return BV;
2547 assert(Loc->second->isForward() &&
2548 "LLVM Value is mapped to different SPIRV Values");
2549 auto Forward = static_cast<SPIRVForward *>(Loc->second);
2550 BM->replaceForward(Forward, BV);
2551 }
2552 ValueMap[V] = BV;
2553 SPIRVDBG(dbgs() << "[mapValue] " << *V << " => "; spvdbgs() << BV << "\n");
2554 return BV;
2555 }
2556
2557 bool LLVMToSPIRVBase::shouldTryToAddMemAliasingDecoration(Instruction *Inst) {
2558 // Limit translation of aliasing metadata with only this set of instructions
2559 // gracefully considering others as compilation mistakes and ignoring them
2560 if (!Inst->mayReadOrWriteMemory())
2561 return false;
2562 // Loads and Stores are handled during memory access mask addition
2563 if (isa<StoreInst>(Inst) || isa<LoadInst>(Inst))
2564 return false;
2565 CallInst *CI = dyn_cast<CallInst>(Inst);
2566 if (!CI)
2567 return true;
2568 if (Function *Fun = CI->getCalledFunction()) {
2569 // Calls to intrinsics are skipped. At some point lifetime start/end will be
2570 // handled separately, but specification isn't ready.
2571 if (Fun->isIntrinsic())
2572 return false;
2573 // Also skip SPIR-V instructions that don't have result id to attach the
2574 // decorations
2575 if (isBuiltinTransToInst(Fun))
2576 if (Fun->getReturnType()->isVoidTy())
2577 return false;
2578 }
2579 return true;
2580 }
2581
2582 void addFuncPointerCallArgumentAttributes(CallInst *CI,
2583 SPIRVValue *FuncPtrCall) {
2584 for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo) {
2585 for (const auto &I : CI->getAttributes().getParamAttrs(ArgNo)) {
2586 spv::FunctionParameterAttribute Attr = spv::FunctionParameterAttributeMax;
2587 SPIRSPIRVFuncParamAttrMap::find(I.getKindAsEnum(), &Attr);
2588 if (Attr != spv::FunctionParameterAttributeMax)
2589 FuncPtrCall->addDecorate(
2590 new SPIRVDecorate(spv::internal::DecorationArgumentAttributeINTEL,
2591 FuncPtrCall, ArgNo, Attr));
2592 }
2593 }
2594 }
2595
2596 #define ONE_STRING_DECORATION_CASE(NAME, NAMESPACE) \
2597 case NAMESPACE::Decoration##NAME: { \
2598 ErrLog.checkError(NumOperands == 2, SPIRVEC_InvalidLlvmModule, \
2599 #NAME " requires exactly 1 extra operand"); \
2600 auto *StrDecoEO = dyn_cast<MDString>(DecoMD->getOperand(1)); \
2601 ErrLog.checkError(StrDecoEO, SPIRVEC_InvalidLlvmModule, \
2602 #NAME " requires extra operand to be a string"); \
2603 Target->addDecorate( \
2604 new SPIRVDecorate##NAME##Attr(Target, StrDecoEO->getString().str())); \
2605 break; \
2606 }
2607
2608 #define ONE_INT_DECORATION_CASE(NAME, NAMESPACE, TYPE) \
2609 case NAMESPACE::Decoration##NAME: { \
2610 ErrLog.checkError(NumOperands == 2, SPIRVEC_InvalidLlvmModule, \
2611 #NAME " requires exactly 1 extra operand"); \
2612 auto *IntDecoEO = \
2613 mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(1)); \
2614 ErrLog.checkError(IntDecoEO, SPIRVEC_InvalidLlvmModule, \
2615 #NAME " requires extra operand to be an integer"); \
2616 Target->addDecorate(new SPIRVDecorate##NAME( \
2617 Target, static_cast<TYPE>(IntDecoEO->getZExtValue()))); \
2618 break; \
2619 }
2620
2621 #define TWO_INT_DECORATION_CASE(NAME, NAMESPACE, TYPE1, TYPE2) \
2622 case NAMESPACE::Decoration##NAME: { \
2623 ErrLog.checkError(NumOperands == 3, SPIRVEC_InvalidLlvmModule, \
2624 #NAME " requires exactly 2 extra operands"); \
2625 auto *IntDecoEO1 = \
2626 mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(1)); \
2627 ErrLog.checkError(IntDecoEO1, SPIRVEC_InvalidLlvmModule, \
2628 #NAME " requires first extra operand to be an integer"); \
2629 auto *IntDecoEO2 = \
2630 mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(2)); \
2631 ErrLog.checkError(IntDecoEO2, SPIRVEC_InvalidLlvmModule, \
2632 #NAME \
2633 " requires second extra operand to be an integer"); \
2634 Target->addDecorate(new SPIRVDecorate##NAME( \
2635 Target, static_cast<TYPE1>(IntDecoEO1->getZExtValue()), \
2636 static_cast<TYPE2>(IntDecoEO2->getZExtValue()))); \
2637 break; \
2638 }
2639
2640 void checkIsGlobalVar(SPIRVEntry *E, Decoration Dec) {
2641 std::string ErrStr =
2642 SPIRVDecorationNameMap::map(Dec) + " can only be applied to a variable";
2643
2644 E->getErrorLog().checkError(E->isVariable(), SPIRVEC_InvalidModule, ErrStr);
2645
2646 auto AddrSpace = SPIRSPIRVAddrSpaceMap::rmap(
2647 static_cast<SPIRVVariable *>(E)->getStorageClass());
2648 ErrStr += " in a global (module) scope";
2649 E->getErrorLog().checkError(AddrSpace == SPIRAS_Global, SPIRVEC_InvalidModule,
2650 ErrStr);
2651 }
2652
2653 static void transMetadataDecorations(Metadata *MD, SPIRVValue *Target) {
2654 SPIRVErrorLog &ErrLog = Target->getErrorLog();
2655
2656 auto *ArgDecoMD = dyn_cast<MDNode>(MD);
2657 assert(ArgDecoMD && "Decoration list must be a metadata node");
2658 for (unsigned I = 0, E = ArgDecoMD->getNumOperands(); I != E; ++I) {
2659 auto *DecoMD = dyn_cast<MDNode>(ArgDecoMD->getOperand(I));
2660 ErrLog.checkError(DecoMD, SPIRVEC_InvalidLlvmModule,
2661 "Decoration does not name metadata");
2662 ErrLog.checkError(DecoMD->getNumOperands() > 0, SPIRVEC_InvalidLlvmModule,
2663 "Decoration metadata must have at least one operand");
2664 auto *DecoKindConst =
2665 mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(0));
2666 ErrLog.checkError(DecoKindConst, SPIRVEC_InvalidLlvmModule,
2667 "First operand of decoration must be the kind");
2668 auto DecoKind = static_cast<Decoration>(DecoKindConst->getZExtValue());
2669
2670 const size_t NumOperands = DecoMD->getNumOperands();
2671 switch (static_cast<size_t>(DecoKind)) {
2672 case DecorationAlignment: {
2673 // Handle Alignment via SPIRVValue::setAlignment() to avoid duplicate
2674 // Alignment decorations.
2675 auto *Alignment =
2676 mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(1));
2677 ErrLog.checkError(Alignment, SPIRVEC_InvalidLlvmModule,
2678 "Alignment operand must be an integer.");
2679 Target->setAlignment(Alignment->getZExtValue());
2680 break;
2681 }
2682
2683 ONE_STRING_DECORATION_CASE(MemoryINTEL, spv)
2684 ONE_STRING_DECORATION_CASE(UserSemantic, spv)
2685 ONE_INT_DECORATION_CASE(AliasScopeINTEL, spv, SPIRVId)
2686 ONE_INT_DECORATION_CASE(NoAliasINTEL, spv, SPIRVId)
2687 ONE_INT_DECORATION_CASE(InitiationIntervalINTEL, spv, SPIRVWord)
2688 ONE_INT_DECORATION_CASE(MaxConcurrencyINTEL, spv, SPIRVWord)
2689 ONE_INT_DECORATION_CASE(PipelineEnableINTEL, spv, SPIRVWord)
2690 TWO_INT_DECORATION_CASE(FunctionRoundingModeINTEL, spv, SPIRVWord,
2691 FPRoundingMode);
2692 TWO_INT_DECORATION_CASE(FunctionDenormModeINTEL, spv, SPIRVWord,
2693 FPDenormMode);
2694 TWO_INT_DECORATION_CASE(FunctionFloatingPointModeINTEL, spv, SPIRVWord,
2695 FPOperationMode);
2696 TWO_INT_DECORATION_CASE(FuseLoopsInFunctionINTEL, spv, SPIRVWord,
2697 SPIRVWord);
2698 TWO_INT_DECORATION_CASE(MathOpDSPModeINTEL, spv, SPIRVWord, SPIRVWord);
2699
2700 case DecorationConduitKernelArgumentINTEL:
2701 case DecorationRegisterMapKernelArgumentINTEL:
2702 case DecorationStableKernelArgumentINTEL:
2703 case DecorationRestrict: {
2704 Target->addDecorate(new SPIRVDecorate(DecoKind, Target));
2705 break;
2706 }
2707 case DecorationBufferLocationINTEL:
2708 case DecorationMMHostInterfaceReadWriteModeINTEL:
2709 case DecorationMMHostInterfaceAddressWidthINTEL:
2710 case DecorationMMHostInterfaceDataWidthINTEL:
2711 case DecorationMMHostInterfaceLatencyINTEL:
2712 case DecorationMMHostInterfaceMaxBurstINTEL:
2713 case DecorationMMHostInterfaceWaitRequestINTEL: {
2714 ErrLog.checkError(NumOperands == 2, SPIRVEC_InvalidLlvmModule,
2715 "MMHost Kernel Argument Annotation requires exactly 2 "
2716 "extra operands");
2717 auto *DecoValEO1 =
2718 mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(1));
2719 Target->addDecorate(
2720 new SPIRVDecorate(DecoKind, Target, DecoValEO1->getZExtValue()));
2721 break;
2722 }
2723 case DecorationStallEnableINTEL: {
2724 Target->addDecorate(new SPIRVDecorateStallEnableINTEL(Target));
2725 break;
2726 }
2727 case DecorationMergeINTEL: {
2728 ErrLog.checkError(NumOperands == 3, SPIRVEC_InvalidLlvmModule,
2729 "MergeINTEL requires exactly 3 extra operands");
2730 auto *Name = dyn_cast<MDString>(DecoMD->getOperand(1));
2731 ErrLog.checkError(
2732 Name, SPIRVEC_InvalidLlvmModule,
2733 "MergeINTEL requires first extra operand to be a string");
2734 auto *Direction = dyn_cast<MDString>(DecoMD->getOperand(2));
2735 ErrLog.checkError(
2736 Direction, SPIRVEC_InvalidLlvmModule,
2737 "MergeINTEL requires second extra operand to be a string");
2738 Target->addDecorate(new SPIRVDecorateMergeINTELAttr(
2739 Target, Name->getString().str(), Direction->getString().str()));
2740 break;
2741 }
2742 case DecorationLinkageAttributes: {
2743 ErrLog.checkError(NumOperands == 3, SPIRVEC_InvalidLlvmModule,
2744 "LinkageAttributes requires exactly 3 extra operands");
2745 auto *Name = dyn_cast<MDString>(DecoMD->getOperand(1));
2746 ErrLog.checkError(
2747 Name, SPIRVEC_InvalidLlvmModule,
2748 "LinkageAttributes requires first extra operand to be a string");
2749 auto *Type = mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(2));
2750 ErrLog.checkError(
2751 Type, SPIRVEC_InvalidLlvmModule,
2752 "LinkageAttributes requires second extra operand to be an int");
2753 auto TypeKind = static_cast<SPIRVLinkageTypeKind>(Type->getZExtValue());
2754 Target->addDecorate(new SPIRVDecorateLinkageAttr(
2755 Target, Name->getString().str(), TypeKind));
2756 break;
2757 }
2758
2759 case spv::internal::DecorationHostAccessINTEL:
2760 case DecorationHostAccessINTEL: {
2761 checkIsGlobalVar(Target, DecoKind);
2762
2763 ErrLog.checkError(NumOperands == 3, SPIRVEC_InvalidLlvmModule,
2764 "HostAccessINTEL requires exactly 2 extra operands "
2765 "after the decoration kind number");
2766 auto *AccessMode =
2767 mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(1));
2768 ErrLog.checkError(
2769 AccessMode, SPIRVEC_InvalidLlvmModule,
2770 "HostAccessINTEL requires first extra operand to be an int");
2771
2772 HostAccessQualifier Q =
2773 static_cast<HostAccessQualifier>(AccessMode->getZExtValue());
2774 auto *Name = dyn_cast<MDString>(DecoMD->getOperand(2));
2775 ErrLog.checkError(
2776 Name, SPIRVEC_InvalidLlvmModule,
2777 "HostAccessINTEL requires second extra operand to be a string");
2778
2779 if (DecoKind == DecorationHostAccessINTEL)
2780 Target->addDecorate(new SPIRVDecorateHostAccessINTEL(
2781 Target, Q, Name->getString().str()));
2782 else
2783 Target->addDecorate(new SPIRVDecorateHostAccessINTELLegacy(
2784 Target, Q, Name->getString().str()));
2785 break;
2786 }
2787
2788 case spv::internal::DecorationInitModeINTEL:
2789 case DecorationInitModeINTEL: {
2790 checkIsGlobalVar(Target, DecoKind);
2791 ErrLog.checkError(static_cast<SPIRVVariable *>(Target)->getInitializer(),
2792 SPIRVEC_InvalidLlvmModule,
2793 "InitModeINTEL only be applied to a global (module "
2794 "scope) variable which has an Initializer operand");
2795
2796 ErrLog.checkError(NumOperands == 2, SPIRVEC_InvalidLlvmModule,
2797 "InitModeINTEL requires exactly 1 extra operand");
2798 auto *Trigger = mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(1));
2799 ErrLog.checkError(Trigger, SPIRVEC_InvalidLlvmModule,
2800 "InitModeINTEL requires extra operand to be an int");
2801
2802 InitializationModeQualifier Q =
2803 static_cast<InitializationModeQualifier>(Trigger->getZExtValue());
2804
2805 if (DecoKind == DecorationInitModeINTEL)
2806 Target->addDecorate(new SPIRVDecorateInitModeINTEL(Target, Q));
2807 else
2808 Target->addDecorate(new SPIRVDecorateInitModeINTELLegacy(Target, Q));
2809
2810 break;
2811 }
2812 case spv::internal::DecorationImplementInCSRINTEL: {
2813 checkIsGlobalVar(Target, DecoKind);
2814 ErrLog.checkError(NumOperands == 2, SPIRVEC_InvalidLlvmModule,
2815 "ImplementInCSRINTEL requires exactly 1 extra operand");
2816 auto *Value = mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(1));
2817 ErrLog.checkError(
2818 Value, SPIRVEC_InvalidLlvmModule,
2819 "ImplementInCSRINTEL requires extra operand to be an integer");
2820
2821 Target->addDecorate(
2822 new SPIRVDecorateImplementInCSRINTEL(Target, Value->getZExtValue()));
2823 break;
2824 }
2825 case DecorationImplementInRegisterMapINTEL: {
2826 checkIsGlobalVar(Target, DecoKind);
2827 ErrLog.checkError(
2828 NumOperands == 2, SPIRVEC_InvalidLlvmModule,
2829 "ImplementInRegisterMapINTEL requires exactly 1 extra operand");
2830 auto *Value = mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(1));
2831 ErrLog.checkError(Value, SPIRVEC_InvalidLlvmModule,
2832 "ImplementInRegisterMapINTEL requires extra operand to "
2833 "be an integer");
2834
2835 Target->addDecorate(new SPIRVDecorateImplementInRegisterMapINTEL(
2836 Target, Value->getZExtValue()));
2837
2838 break;
2839 }
2840
2841 case DecorationCacheControlLoadINTEL: {
2842 ErrLog.checkError(
2843 NumOperands == 3, SPIRVEC_InvalidLlvmModule,
2844 "CacheControlLoadINTEL requires exactly 2 extra operands");
2845 auto *CacheLevel =
2846 mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(1));
2847 auto *CacheControl =
2848 mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(2));
2849 ErrLog.checkError(CacheLevel, SPIRVEC_InvalidLlvmModule,
2850 "CacheControlLoadINTEL cache level operand is required "
2851 "to be an integer");
2852 ErrLog.checkError(CacheControl, SPIRVEC_InvalidLlvmModule,
2853 "CacheControlLoadINTEL cache control operand is "
2854 "required to be an integer");
2855
2856 Target->addDecorate(new SPIRVDecorateCacheControlLoadINTEL(
2857 Target, CacheLevel->getZExtValue(),
2858 static_cast<LoadCacheControl>(CacheControl->getZExtValue())));
2859 break;
2860 }
2861 case DecorationCacheControlStoreINTEL: {
2862 ErrLog.checkError(
2863 NumOperands == 3, SPIRVEC_InvalidLlvmModule,
2864 "CacheControlStoreINTEL requires exactly 2 extra operands");
2865 auto *CacheLevel =
2866 mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(1));
2867 auto *CacheControl =
2868 mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(2));
2869 ErrLog.checkError(CacheLevel, SPIRVEC_InvalidLlvmModule,
2870 "CacheControlStoreINTEL cache level operand is "
2871 "required to be an integer");
2872 ErrLog.checkError(CacheControl, SPIRVEC_InvalidLlvmModule,
2873 "CacheControlStoreINTEL cache control operand is "
2874 "required to be an integer");
2875
2876 Target->addDecorate(new SPIRVDecorateCacheControlStoreINTEL(
2877 Target, CacheLevel->getZExtValue(),
2878 static_cast<StoreCacheControl>(CacheControl->getZExtValue())));
2879 break;
2880 }
2881 default: {
2882 if (NumOperands == 1) {
2883 Target->addDecorate(new SPIRVDecorate(DecoKind, Target));
2884 break;
2885 }
2886
2887 auto *DecoValEO1 =
2888 mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(1));
2889 ErrLog.checkError(
2890 DecoValEO1, SPIRVEC_InvalidLlvmModule,
2891 "First extra operand in default decoration case must be integer.");
2892 if (NumOperands == 2) {
2893 Target->addDecorate(
2894 new SPIRVDecorate(DecoKind, Target, DecoValEO1->getZExtValue()));
2895 break;
2896 }
2897
2898 auto *DecoValEO2 =
2899 mdconst::dyn_extract<ConstantInt>(DecoMD->getOperand(2));
2900 ErrLog.checkError(
2901 DecoValEO2, SPIRVEC_InvalidLlvmModule,
2902 "Second extra operand in default decoration case must be integer.");
2903
2904 ErrLog.checkError(NumOperands == 3, SPIRVEC_InvalidLlvmModule,
2905 "At most 2 extra operands expected.");
2906 Target->addDecorate(new SPIRVDecorate(DecoKind, Target,
2907 DecoValEO1->getZExtValue(),
2908 DecoValEO2->getZExtValue()));
2909 }
2910 }
2911 }
2912 }
2913
2914 #undef ONE_STRING_DECORATION_CASE
2915 #undef ONE_INT_DECORATION_CASE
2916 #undef TWO_INT_DECORATION_CASE
2917
2918 bool LLVMToSPIRVBase::transDecoration(Value *V, SPIRVValue *BV) {
2919 if (!transAlign(V, BV))
2920 return false;
2921 if ((isa<AtomicCmpXchgInst>(V) && cast<AtomicCmpXchgInst>(V)->isVolatile()) ||
2922 (isa<AtomicRMWInst>(V) && cast<AtomicRMWInst>(V)->isVolatile()))
2923 BV->setVolatile(true);
2924
2925 if (auto BVO = dyn_cast_or_null<OverflowingBinaryOperator>(V)) {
2926 if (BVO->hasNoSignedWrap()) {
2927 BV->setNoIntegerDecorationWrap<DecorationNoSignedWrap>(true);
2928 }
2929 if (BVO->hasNoUnsignedWrap()) {
2930 BV->setNoIntegerDecorationWrap<DecorationNoUnsignedWrap>(true);
2931 }
2932 }
2933
2934 if (auto BVF = dyn_cast_or_null<FPMathOperator>(V)) {
2935 auto Opcode = BVF->getOpcode();
2936 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub ||
2937 Opcode == Instruction::FMul || Opcode == Instruction::FDiv ||
2938 Opcode == Instruction::FRem ||
2939 ((Opcode == Instruction::FNeg || Opcode == Instruction::FCmp ||
2940 BV->isExtInst()) &&
2941 BM->isAllowedToUseVersion(VersionNumber::SPIRV_1_6))) {
2942 FastMathFlags FMF = BVF->getFastMathFlags();
2943 SPIRVWord M{0};
2944 if (FMF.isFast())
2945 M |= FPFastMathModeFastMask;
2946 else {
2947 if (FMF.noNaNs())
2948 M |= FPFastMathModeNotNaNMask;
2949 if (FMF.noInfs())
2950 M |= FPFastMathModeNotInfMask;
2951 if (FMF.noSignedZeros())
2952 M |= FPFastMathModeNSZMask;
2953 if (FMF.allowReciprocal())
2954 M |= FPFastMathModeAllowRecipMask;
2955 if (BM->isAllowedToUseExtension(
2956 ExtensionID::SPV_INTEL_fp_fast_math_mode)) {
2957 if (FMF.allowContract()) {
2958 M |= FPFastMathModeAllowContractFastINTELMask;
2959 BM->addCapability(CapabilityFPFastMathModeINTEL);
2960 BM->addExtension(ExtensionID::SPV_INTEL_fp_fast_math_mode);
2961 }
2962 if (FMF.allowReassoc()) {
2963 M |= FPFastMathModeAllowReassocINTELMask;
2964 BM->addCapability(CapabilityFPFastMathModeINTEL);
2965 BM->addExtension(ExtensionID::SPV_INTEL_fp_fast_math_mode);
2966 }
2967 }
2968 }
2969 if (M != 0) {
2970 BV->setFPFastMathMode(M);
2971 if (Opcode == Instruction::FNeg || Opcode == Instruction::FCmp ||
2972 BV->isExtInst())
2973 BM->setMinSPIRVVersion(VersionNumber::SPIRV_1_6);
2974 }
2975 }
2976 }
2977 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
2978 if (shouldTryToAddMemAliasingDecoration(Inst))
2979 transMemAliasingINTELDecorations(Inst, BV);
2980 if (auto *IDecoMD = Inst->getMetadata(SPIRV_MD_DECORATIONS))
2981 transMetadataDecorations(IDecoMD, BV);
2982 }
2983
2984 if (auto *CI = dyn_cast<CallInst>(V)) {
2985 auto OC = BV->getOpCode();
2986 if (OC == OpSpecConstantTrue || OC == OpSpecConstantFalse ||
2987 OC == OpSpecConstant) {
2988 auto SpecId = cast<ConstantInt>(CI->getArgOperand(0))->getZExtValue();
2989 BV->addDecorate(DecorationSpecId, SpecId);
2990 }
2991 if (OC == OpFunctionPointerCallINTEL)
2992 addFuncPointerCallArgumentAttributes(CI, BV);
2993 }
2994
2995 if (auto *GV = dyn_cast<GlobalVariable>(V))
2996 if (auto *GVDecoMD = GV->getMetadata(SPIRV_MD_DECORATIONS))
2997 transMetadataDecorations(GVDecoMD, BV);
2998
2999 return true;
3000 }
3001
3002 bool LLVMToSPIRVBase::transAlign(Value *V, SPIRVValue *BV) {
3003 if (auto AL = dyn_cast<AllocaInst>(V)) {
3004 BM->setAlignment(BV, AL->getAlign().value());
3005 return true;
3006 }
3007 if (auto GV = dyn_cast<GlobalVariable>(V)) {
3008 BM->setAlignment(BV, GV->getAlignment());
3009 return true;
3010 }
3011 return true;
3012 }
3013
3014 // Apply aliasing decorations to instructions annotated with aliasing metadata.
3015 // Do it for any instruction but loads and stores.
3016 void LLVMToSPIRVBase::transMemAliasingINTELDecorations(Instruction *Inst,
3017 SPIRVValue *BV) {
3018 if (!BM->isAllowedToUseExtension(
3019 ExtensionID::SPV_INTEL_memory_access_aliasing))
3020 return;
3021 if (MDNode *AliasingListMD = Inst->getMetadata(LLVMContext::MD_alias_scope)) {
3022 auto *MemAliasList = addMemAliasingINTELInstructions(BM, AliasingListMD);
3023 if (!MemAliasList)
3024 return;
3025 BV->addDecorate(new SPIRVDecorateId(DecorationAliasScopeINTEL, BV,
3026 MemAliasList->getId()));
3027 }
3028 if (MDNode *AliasingListMD = Inst->getMetadata(LLVMContext::MD_noalias)) {
3029 auto *MemAliasList = addMemAliasingINTELInstructions(BM, AliasingListMD);
3030 if (!MemAliasList)
3031 return;
3032 BV->addDecorate(
3033 new SPIRVDecorateId(DecorationNoAliasINTEL, BV, MemAliasList->getId()));
3034 }
3035 }
3036
3037 /// Do this after source language is set.
3038 bool LLVMToSPIRVBase::transBuiltinSet() {
3039 SPIRVId EISId;
3040 if (!BM->importBuiltinSet("OpenCL.std", &EISId))
3041 return false;
3042 if (SPIRVMDWalker(*M).getNamedMD("llvm.dbg.cu")) {
3043 if (!BM->importBuiltinSet(
3044 SPIRVBuiltinSetNameMap::map(BM->getDebugInfoEIS()), &EISId))
3045 return false;
3046 }
3047 if (BM->preserveAuxData()) {
3048 if (!BM->importBuiltinSet(
3049 SPIRVBuiltinSetNameMap::map(SPIRVEIS_NonSemantic_AuxData), &EISId))
3050 return false;
3051 }
3052 return true;
3053 }
3054
3055 /// Translate sampler* spcv.cast(i32 arg) or
3056 /// sampler* __translate_sampler_initializer(i32 arg)
3057 /// Three cases are possible:
3058 /// arg = ConstantInt x -> SPIRVConstantSampler
3059 /// arg = i32 argument -> transValue(arg)
3060 /// arg = load from sampler -> look through load
3061 SPIRVValue *LLVMToSPIRVBase::oclTransSpvcCastSampler(CallInst *CI,
3062 SPIRVBasicBlock *BB) {
3063 assert(CI->getCalledFunction() && "Unexpected indirect call");
3064 llvm::Function *F = CI->getCalledFunction();
3065 auto FT = F->getFunctionType();
3066 auto RT = FT->getReturnType();
3067 assert(FT->getNumParams() == 1);
3068 if (RT->isPointerTy() && !RT->isOpaquePointerTy()) {
3069 StructType *ST = dyn_cast<StructType>(RT->getNonOpaquePointerElementType());
3070 (void)ST;
3071 assert(isSPIRVStructType(ST, kSPIRVTypeName::Sampler) ||
3072 (ST->isOpaque() && ST->getName() == kSPR2TypeName::Sampler));
3073 }
3074 assert(FT->getParamType(0)->isIntegerTy() && "Invalid sampler type");
3075 auto Arg = CI->getArgOperand(0);
3076
3077 auto *TransRT = transType(getSPIRVType(OpTypeSampler));
3078
3079 auto GetSamplerConstant = [&](uint64_t SamplerValue) {
3080 auto AddrMode = (SamplerValue & 0xE) >> 1;
3081 auto Param = SamplerValue & 0x1;
3082 auto Filter = SamplerValue ? ((SamplerValue & 0x30) >> 4) - 1 : 0;
3083 auto *BV = BM->addSamplerConstant(TransRT, AddrMode, Param, Filter);
3084 return BV;
3085 };
3086
3087 if (auto Const = dyn_cast<ConstantInt>(Arg)) {
3088 // Sampler is declared as a kernel scope constant
3089 return GetSamplerConstant(Const->getZExtValue());
3090 } else if (auto Load = dyn_cast<LoadInst>(Arg)) {
3091 // If value of the sampler is loaded from a global constant, use its
3092 // initializer for initialization of the sampler.
3093 auto Op = Load->getPointerOperand();
3094 assert(isa<GlobalVariable>(Op) && "Unknown sampler pattern!");
3095 auto GV = cast<GlobalVariable>(Op);
3096 assert(GV->isConstant() ||
3097 GV->getType()->getPointerAddressSpace() == SPIRAS_Constant);
3098 auto Initializer = GV->getInitializer();
3099 assert(isa<ConstantInt>(Initializer) && "sampler not constant int?");
3100 return GetSamplerConstant(cast<ConstantInt>(Initializer)->getZExtValue());
3101 }
3102 // Sampler is a function argument
3103 auto BV = transValue(Arg, BB);
3104 assert(BV && BV->getType() == TransRT);
3105 return BV;
3106 }
3107
3108 using DecorationsInfoVec =
3109 std::vector<std::pair<Decoration, std::vector<std::string>>>;
3110
3111 struct AnnotationDecorations {
3112 DecorationsInfoVec MemoryAttributesVec;
3113 DecorationsInfoVec MemoryAccessesVec;
3114 };
3115
3116 struct IntelLSUControlsInfo {
3117 void setWithBitMask(unsigned ParamsBitMask) {
3118 if (ParamsBitMask & IntelFPGAMemoryAccessesVal::BurstCoalesce)
3119 BurstCoalesce = true;
3120 if (ParamsBitMask & IntelFPGAMemoryAccessesVal::CacheSizeFlag)
3121 CacheSizeInfo = 0;
3122 if (ParamsBitMask & IntelFPGAMemoryAccessesVal::DontStaticallyCoalesce)
3123 DontStaticallyCoalesce = true;
3124 if (ParamsBitMask & IntelFPGAMemoryAccessesVal::PrefetchFlag)
3125 PrefetchInfo = 0;
3126 }
3127
3128 DecorationsInfoVec getDecorationsFromCurrentState() {
3129 DecorationsInfoVec ResultVec;
3130 // Simple flags
3131 if (BurstCoalesce)
3132 ResultVec.emplace_back(DecorationBurstCoalesceINTEL,
3133 std::vector<std::string>());
3134 if (DontStaticallyCoalesce)
3135 ResultVec.emplace_back(DecorationDontStaticallyCoalesceINTEL,
3136 std::vector<std::string>());
3137 // Conditional values
3138 if (CacheSizeInfo.has_value()) {
3139 ResultVec.emplace_back(
3140 DecorationCacheSizeINTEL,
3141 std::vector<std::string>{std::to_string(CacheSizeInfo.value())});
3142 }
3143 if (PrefetchInfo.has_value()) {
3144 ResultVec.emplace_back(
3145 DecorationPrefetchINTEL,
3146 std::vector<std::string>{std::to_string(PrefetchInfo.value())});
3147 }
3148 return ResultVec;
3149 }
3150
3151 bool BurstCoalesce = false;
3152 std::optional<unsigned> CacheSizeInfo;
3153 bool DontStaticallyCoalesce = false;
3154 std::optional<unsigned> PrefetchInfo;
3155 };
3156
3157 // Handle optional var/ptr/global annotation parameter. It can be for example
3158 // { %struct.S, i8*, void ()* } { %struct.S undef, i8* null,
3159 // void ()* @_Z4blahv }
3160 // Now we will just handle integer constants (wrapped in a constant
3161 // struct, that is being bitcasted to i8*), converting them to string.
3162 // TODO: remove this workaround when/if an extension spec that allows or adds
3163 // variadic-arguments UserSemantic decoration
3164 void processOptionalAnnotationInfo(Constant *Const,
3165 std::string &AnnotationString) {
3166 if (!Const->getNumOperands())
3167 return;
3168 if (auto *CStruct = dyn_cast<ConstantStruct>(Const->getOperand(0))) {
3169 uint32_t NumOperands = CStruct->getNumOperands();
3170 if (!NumOperands)
3171 return;
3172 if (auto *CInt = dyn_cast<ConstantInt>(CStruct->getOperand(0))) {
3173 AnnotationString += ": ";
3174 // For boolean, emit 0/1 for ease of readability.
3175 if (CInt->getType()->getIntegerBitWidth() == 1)
3176 AnnotationString += std::to_string(CInt->getZExtValue());
3177 else
3178 AnnotationString += std::to_string(CInt->getSExtValue());
3179 }
3180 for (uint32_t I = 1; I != NumOperands; ++I) {
3181 if (auto *CInt = dyn_cast<ConstantInt>(CStruct->getOperand(I))) {
3182 AnnotationString += ", ";
3183 AnnotationString += std::to_string(CInt->getSExtValue());
3184 }
3185 }
3186 } else if (auto *ZeroStruct =
3187 dyn_cast<ConstantAggregateZero>(Const->getOperand(0))) {
3188 // It covers case when all elements of struct are 0 and they become
3189 // zeroinitializer. It represents like: { i32 i32 ... } zeroinitializer
3190 uint32_t NumOperands = ZeroStruct->getType()->getStructNumElements();
3191 AnnotationString += ": ";
3192 AnnotationString += "0";
3193 for (uint32_t I = 1; I != NumOperands; ++I) {
3194 AnnotationString += ", ";
3195 AnnotationString += "0";
3196 }
3197 }
3198 }
3199
3200 // Process main var/ptr/global annotation string with the attached optional
3201 // integer parameters
3202 void processAnnotationString(IntrinsicInst *II, std::string &AnnotationString) {
3203 auto *StrVal = II->getArgOperand(1);
3204 auto *StrValTy = StrVal->getType();
3205 if (StrValTy->isOpaquePointerTy()) {
3206 StringRef StrRef;
3207 if (getConstantStringInfo(dyn_cast<Constant>(StrVal), StrRef))
3208 AnnotationString += StrRef.str();
3209 if (auto *C = dyn_cast_or_null<Constant>(II->getArgOperand(4)))
3210 processOptionalAnnotationInfo(C, AnnotationString);
3211 return;
3212 }
3213 if (auto *GEP = dyn_cast<GetElementPtrInst>(StrVal)) {
3214 if (auto *C = dyn_cast<Constant>(GEP->getOperand(0))) {
3215 StringRef StrRef;
3216 if (getConstantStringInfo(C, StrRef))
3217 AnnotationString += StrRef.str();
3218 }
3219 }
3220 if (auto *Cast = dyn_cast<BitCastInst>(II->getArgOperand(4)))
3221 if (auto *C = dyn_cast_or_null<Constant>(Cast->getOperand(0)))
3222 processOptionalAnnotationInfo(C, AnnotationString);
3223 }
3224
3225 // Try to parse the annotation decoration values in a string. These values must
3226 // be separated by a "," and must be either a word (including numbers) or a
3227 // quotation mark enclosed string.
3228 static bool tryParseAnnotationDecoValues(StringRef ValueStr,
3229 std::vector<std::string> &ParsedArgs) {
3230 unsigned ValueStart = 0;
3231 bool IsParsingStringLiteral = false;
3232 for (unsigned I = 0; I < ValueStr.size(); ++I) {
3233 const char CurrentC = ValueStr[I];
3234 if (IsParsingStringLiteral) {
3235 if (CurrentC == '"') {
3236 // We have reached the end of a string literal and have the arg string
3237 // between this character and the start of the string literal.
3238 IsParsingStringLiteral = false;
3239 ParsedArgs.push_back(ValueStr.substr(ValueStart, I - ValueStart).str());
3240 // End of a string literal must either be at the end of the values or
3241 // right before a comma.
3242 if (I + 1 != ValueStr.size() && ValueStr[I + 1] != ',')
3243 return false;
3244 // Skip the , delimiter and go directly to the start of next value.
3245 ValueStart = (++I) + 1;
3246 }
3247 continue;
3248 }
3249 if (CurrentC == ',') {
3250 // Since we are not currently in a string literal, comma denotes a
3251 // separation of decoration arguments and we can copy the substring we are
3252 // currently parsing.
3253 ParsedArgs.push_back(ValueStr.substr(ValueStart, I - ValueStart).str());
3254 ValueStart = I + 1;
3255 continue;
3256 }
3257 if (CurrentC == '"') {
3258 // We are entering a string literal. This must be either at the beginning
3259 // of the values or right after a comma.
3260 if (I != 0 && ValueStr[I - 1] != ',')
3261 return false;
3262 IsParsingStringLiteral = true;
3263 ValueStart = I + 1;
3264 continue;
3265 }
3266 // Any other character will be consumed as part of the argument.
3267 }
3268 // If we were still parsing a decoration argument when reaching the end of the
3269 // parsed string, we must be at the end of the argument.
3270 if (ValueStart < ValueStr.size())
3271 ParsedArgs.push_back(
3272 ValueStr.substr(ValueStart, ValueStr.size() - ValueStart).str());
3273
3274 // At the end, the arguments parsed are valid if we were not parsing a string
3275 // literal with no end.
3276 return !IsParsingStringLiteral;
3277 }
3278
3279 AnnotationDecorations tryParseAnnotationString(SPIRVModule *BM,
3280 StringRef AnnotatedCode) {
3281 AnnotationDecorations Decorates;
3282
3283 // Annotation string decorations are separated into {word} OR
3284 // {word:value,value,...} blocks, where value is either a word (including
3285 // numbers) or a quotation mark enclosed string.
3286 std::regex DecorationRegex("\\{\\w([\\w:,-]|\"[^\"]*\")*\\}");
3287 using RegexIterT = std::regex_iterator<StringRef::const_iterator>;
3288 RegexIterT DecorationsIt(AnnotatedCode.begin(), AnnotatedCode.end(),
3289 DecorationRegex);
3290 RegexIterT DecorationsEnd;
3291
3292 // If we didn't find any annotations that are separated as described above,
3293 // then add a UserSemantic decoration
3294 if (DecorationsIt == DecorationsEnd) {
3295 Decorates.MemoryAttributesVec.emplace_back(
3296 DecorationUserSemantic, std::vector<std::string>{AnnotatedCode.str()});
3297 return Decorates;
3298 }
3299
3300 const bool AllowFPGAMemAccesses =
3301 BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_fpga_memory_accesses);
3302 const bool AllowFPGAMemAttr = BM->isAllowedToUseExtension(
3303 ExtensionID::SPV_INTEL_fpga_memory_attributes);
3304
3305 bool ValidDecorationFound = false;
3306 DecorationsInfoVec DecorationsVec;
3307 IntelLSUControlsInfo LSUControls;
3308 for (; DecorationsIt != DecorationsEnd; ++DecorationsIt) {
3309 // Drop the braces surrounding the actual decoration
3310 const StringRef AnnotatedDecoration = AnnotatedCode.substr(
3311 DecorationsIt->position() + 1, DecorationsIt->length() - 2);
3312
3313 std::pair<StringRef, StringRef> Split = AnnotatedDecoration.split(':');
3314 StringRef Name = Split.first, ValueStr = Split.second;
3315
3316 unsigned DecorationKind = 0;
3317 if (!Name.getAsInteger(10, DecorationKind)) {
3318 // If the name is a number it represents the decoration by its kind.
3319 std::vector<std::string> DecValues;
3320 if (tryParseAnnotationDecoValues(ValueStr, DecValues)) {
3321 ValidDecorationFound = true;
3322 DecorationsVec.emplace_back(static_cast<Decoration>(DecorationKind),
3323 std::move(DecValues));
3324 }
3325 continue;
3326 }
3327
3328 if (AllowFPGAMemAccesses) {
3329 if (Name == "params") {
3330 ValidDecorationFound = true;
3331 unsigned ParamsBitMask = 0;
3332 bool Failure = ValueStr.getAsInteger(10, ParamsBitMask);
3333 assert(!Failure && "Non-integer LSU controls value");
3334 (void)Failure;
3335 LSUControls.setWithBitMask(ParamsBitMask);
3336 } else if (Name == "cache-size") {
3337 ValidDecorationFound = true;
3338 if (!LSUControls.CacheSizeInfo.has_value())
3339 continue;
3340 unsigned CacheSizeValue = 0;
3341 bool Failure = ValueStr.getAsInteger(10, CacheSizeValue);
3342 assert(!Failure && "Non-integer cache size value");
3343 (void)Failure;
3344 LSUControls.CacheSizeInfo = CacheSizeValue;
3345 } // TODO: Support LSU prefetch size, which currently defaults to 0
3346 }
3347 if (AllowFPGAMemAttr) {
3348 std::vector<std::string> DecValues;
3349 Decoration Dec;
3350 if (Name == "pump") {
3351 ValidDecorationFound = true;
3352 Dec = llvm::StringSwitch<Decoration>(ValueStr)
3353 .Case("1", DecorationSinglepumpINTEL)
3354 .Case("2", DecorationDoublepumpINTEL);
3355 } else if (Name == "register") {
3356 ValidDecorationFound = true;
3357 Dec = DecorationRegisterINTEL;
3358 } else if (Name == "simple_dual_port") {
3359 ValidDecorationFound = true;
3360 Dec = DecorationSimpleDualPortINTEL;
3361 } else {
3362 Dec = llvm::StringSwitch<Decoration>(Name)
3363 .Case("memory", DecorationMemoryINTEL)
3364 .Case("numbanks", DecorationNumbanksINTEL)
3365 .Case("bankwidth", DecorationBankwidthINTEL)
3366 .Case("private_copies", DecorationMaxPrivateCopiesINTEL)
3367 .Case("max_replicates", DecorationMaxReplicatesINTEL)
3368 .Case("bank_bits", DecorationBankBitsINTEL)
3369 .Case("merge", DecorationMergeINTEL)
3370 .Case("force_pow2_depth", DecorationForcePow2DepthINTEL)
3371 .Default(DecorationUserSemantic);
3372 if (Dec == DecorationUserSemantic)
3373 DecValues = std::vector<std::string>({AnnotatedDecoration.str()});
3374 else if (Dec == DecorationMergeINTEL) {
3375 ValidDecorationFound = true;
3376 std::pair<StringRef, StringRef> MergeValues = ValueStr.split(':');
3377 DecValues = std::vector<std::string>(
3378 {MergeValues.first.str(), MergeValues.second.str()});
3379 } else if (Dec == DecorationBankBitsINTEL) {
3380 ValidDecorationFound = true;
3381 SmallVector<StringRef, 4> BitsStrs;
3382 ValueStr.split(BitsStrs, ',');
3383 DecValues.reserve(BitsStrs.size());
3384 for (const StringRef &BitsStr : BitsStrs)
3385 DecValues.push_back(BitsStr.str());
3386 } else {
3387 ValidDecorationFound = true;
3388 DecValues = std::vector<std::string>({ValueStr.str()});
3389 }
3390 }
3391 DecorationsVec.emplace_back(Dec, std::move(DecValues));
3392 }
3393 }
3394 // Even if there is an annotation string that is split in blocks like Intel
3395 // FPGA annotation, it's not necessarily an FPGA annotation. Translate the
3396 // whole string as UserSemantic decoration in this case.
3397 if (ValidDecorationFound)
3398 Decorates.MemoryAttributesVec = DecorationsVec;
3399 else
3400 Decorates.MemoryAttributesVec.emplace_back(
3401 DecorationUserSemantic,
3402 std::vector<std::string>({AnnotatedCode.str()}));
3403 Decorates.MemoryAccessesVec = LSUControls.getDecorationsFromCurrentState();
3404
3405 return Decorates;
3406 }
3407
3408 std::vector<SPIRVWord>
3409 getBankBitsFromStrings(const std::vector<std::string> &BitsStrings) {
3410 std::vector<SPIRVWord> Bits(BitsStrings.size());
3411 for (size_t J = 0; J < BitsStrings.size(); ++J)
3412 if (StringRef(BitsStrings[J]).getAsInteger(10, Bits[J]))
3413 return {};
3414 return Bits;
3415 }
3416
3417 void addAnnotationDecorations(SPIRVEntry *E, DecorationsInfoVec &Decorations) {
3418 SPIRVModule *M = E->getModule();
3419 for (const auto &I : Decorations) {
3420 // Such decoration already exists on a type, try to skip it
3421 if (E->hasDecorate(I.first, /*Index=*/0, /*Result=*/nullptr))
3422 // Allow multiple UserSemantic Decorations
3423 if (I.first != DecorationUserSemantic)
3424 continue;
3425
3426 switch (I.first) {
3427 case DecorationUserSemantic:
3428 M->getErrorLog().checkError(I.second.size() == 1,
3429 SPIRVEC_InvalidLlvmModule,
3430 "UserSemantic requires a single argument.");
3431 E->addDecorate(new SPIRVDecorateUserSemanticAttr(E, I.second[0]));
3432 break;
3433 case DecorationMemoryINTEL: {
3434 if (M->isAllowedToUseExtension(
3435 ExtensionID::SPV_INTEL_fpga_memory_attributes)) {
3436 M->getErrorLog().checkError(I.second.size() == 1,
3437 SPIRVEC_InvalidLlvmModule,
3438 "MemoryINTEL requires a single argument.");
3439 E->addDecorate(new SPIRVDecorateMemoryINTELAttr(E, I.second[0]));
3440 }
3441 } break;
3442 case DecorationMergeINTEL: {
3443 if (M->isAllowedToUseExtension(
3444 ExtensionID::SPV_INTEL_fpga_memory_attributes)) {
3445 M->getErrorLog().checkError(I.second.size() == 2,
3446 SPIRVEC_InvalidLlvmModule,
3447 "MergeINTEL requires two arguments.");
3448 // First argument is the name and the second argument is the direction.
3449 E->addDecorate(
3450 new SPIRVDecorateMergeINTELAttr(E, I.second[0], I.second[1]));
3451 }
3452 } break;
3453 case DecorationBankBitsINTEL: {
3454 if (M->isAllowedToUseExtension(
3455 ExtensionID::SPV_INTEL_fpga_memory_attributes)) {
3456 M->getErrorLog().checkError(
3457 I.second.size() > 0, SPIRVEC_InvalidLlvmModule,
3458 "BankBitsINTEL requires at least one argument.");
3459 E->addDecorate(new SPIRVDecorateBankBitsINTELAttr(
3460 E, getBankBitsFromStrings(I.second)));
3461 }
3462 } break;
3463 case DecorationRegisterINTEL:
3464 case DecorationSinglepumpINTEL:
3465 case DecorationDoublepumpINTEL:
3466 case DecorationSimpleDualPortINTEL: {
3467 if (M->isAllowedToUseExtension(
3468 ExtensionID::SPV_INTEL_fpga_memory_attributes)) {
3469 M->getErrorLog().checkError(I.second.empty(), SPIRVEC_InvalidLlvmModule,
3470 "Decoration takes no arguments.");
3471 E->addDecorate(I.first);
3472 }
3473 } break;
3474 case DecorationBurstCoalesceINTEL:
3475 case DecorationDontStaticallyCoalesceINTEL: {
3476 if (M->isAllowedToUseExtension(
3477 ExtensionID::SPV_INTEL_fpga_memory_accesses)) {
3478 M->getErrorLog().checkError(I.second.empty(), SPIRVEC_InvalidLlvmModule,
3479 "Decoration takes no arguments.");
3480 E->addDecorate(I.first);
3481 }
3482 } break;
3483 case DecorationNumbanksINTEL:
3484 case DecorationBankwidthINTEL:
3485 case DecorationMaxPrivateCopiesINTEL:
3486 case DecorationMaxReplicatesINTEL:
3487 case DecorationForcePow2DepthINTEL: {
3488 if (M->isAllowedToUseExtension(
3489 ExtensionID::SPV_INTEL_fpga_memory_attributes)) {
3490 M->getErrorLog().checkError(I.second.size() == 1,
3491 SPIRVEC_InvalidLlvmModule,
3492 "Decoration requires a single argument.");
3493 SPIRVWord Result = 0;
3494 StringRef(I.second[0]).getAsInteger(10, Result);
3495 E->addDecorate(I.first, Result);
3496 }
3497 } break;
3498 case DecorationCacheSizeINTEL:
3499 case DecorationPrefetchINTEL: {
3500 if (M->isAllowedToUseExtension(
3501 ExtensionID::SPV_INTEL_fpga_memory_accesses)) {
3502 M->getErrorLog().checkError(I.second.size() == 1,
3503 SPIRVEC_InvalidLlvmModule,
3504 "Decoration requires a single argument.");
3505 SPIRVWord Result = 0;
3506 StringRef(I.second[0]).getAsInteger(10, Result);
3507 E->addDecorate(I.first, Result);
3508 }
3509 } break;
3510 default:
3511 // Other decorations are either not supported by the translator or
3512 // handled in other places.
3513 break;
3514 }
3515 }
3516 }
3517
3518 void addAnnotationDecorationsForStructMember(SPIRVEntry *E,
3519 SPIRVWord MemberNumber,
3520 DecorationsInfoVec &Decorations) {
3521 SPIRVModule *M = E->getModule();
3522 for (const auto &I : Decorations) {
3523 // Such decoration already exists on a type, skip it
3524 if (E->hasMemberDecorate(I.first, /*Index=*/0, MemberNumber,
3525 /*Result=*/nullptr))
3526 // Allow multiple UserSemantic Decorations
3527 if (I.first != DecorationUserSemantic)
3528 continue;
3529
3530 switch (I.first) {
3531 case DecorationUserSemantic:
3532 M->getErrorLog().checkError(I.second.size() == 1,
3533 SPIRVEC_InvalidLlvmModule,
3534 "UserSemantic requires a single argument.");
3535 E->addMemberDecorate(new SPIRVMemberDecorateUserSemanticAttr(
3536 E, MemberNumber, I.second[0]));
3537 break;
3538 case DecorationMemoryINTEL:
3539 M->getErrorLog().checkError(I.second.size() == 1,
3540 SPIRVEC_InvalidLlvmModule,
3541 "MemoryINTEL requires a single argument.");
3542 E->addMemberDecorate(
3543 new SPIRVMemberDecorateMemoryINTELAttr(E, MemberNumber, I.second[0]));
3544 break;
3545 case DecorationMergeINTEL: {
3546 M->getErrorLog().checkError(I.second.size() == 2,
3547 SPIRVEC_InvalidLlvmModule,
3548 "MergeINTEL requires two arguments.");
3549 // First argument is the name, the other is the direction.
3550 E->addMemberDecorate(new SPIRVMemberDecorateMergeINTELAttr(
3551 E, MemberNumber, I.second[0], I.second[1]));
3552 } break;
3553 case DecorationBankBitsINTEL:
3554 M->getErrorLog().checkError(
3555 I.second.size() > 0, SPIRVEC_InvalidLlvmModule,
3556 "BankBitsINTEL requires at least one argument.");
3557 E->addMemberDecorate(new SPIRVMemberDecorateBankBitsINTELAttr(
3558 E, MemberNumber, getBankBitsFromStrings(I.second)));
3559 break;
3560 case DecorationRegisterINTEL:
3561 case DecorationSinglepumpINTEL:
3562 case DecorationDoublepumpINTEL:
3563 case DecorationSimpleDualPortINTEL:
3564 M->getErrorLog().checkError(I.second.empty(), SPIRVEC_InvalidLlvmModule,
3565 "Member decoration takes no arguments.");
3566 E->addMemberDecorate(MemberNumber, I.first);
3567 break;
3568 // The rest of IntelFPGA decorations:
3569 // DecorationNumbanksINTEL
3570 // DecorationBankwidthINTEL
3571 // DecorationMaxPrivateCopiesINTEL
3572 // DecorationMaxReplicatesINTEL
3573 // DecorationForcePow2DepthINTEL
3574 default:
3575 M->getErrorLog().checkError(
3576 I.second.size() == 1, SPIRVEC_InvalidLlvmModule,
3577 "Member decoration requires a single argument.");
3578 SPIRVWord Result = 0;
3579 StringRef(I.second[0]).getAsInteger(10, Result);
3580 E->addMemberDecorate(MemberNumber, I.first, Result);
3581 break;
3582 }
3583 }
3584 }
3585
3586 bool LLVMToSPIRVBase::isKnownIntrinsic(Intrinsic::ID Id) {
3587 // Known intrinsics usually do not need translation of their declaration
3588 switch (Id) {
3589 case Intrinsic::abs:
3590 case Intrinsic::assume:
3591 case Intrinsic::bitreverse:
3592 case Intrinsic::ceil:
3593 case Intrinsic::copysign:
3594 case Intrinsic::cos:
3595 case Intrinsic::exp:
3596 case Intrinsic::exp2:
3597 case Intrinsic::fabs:
3598 case Intrinsic::floor:
3599 case Intrinsic::fma:
3600 case Intrinsic::log:
3601 case Intrinsic::log10:
3602 case Intrinsic::log2:
3603 case Intrinsic::maximum:
3604 case Intrinsic::maxnum:
3605 case Intrinsic::smax:
3606 case Intrinsic::umax:
3607 case Intrinsic::minimum:
3608 case Intrinsic::minnum:
3609 case Intrinsic::smin:
3610 case Intrinsic::umin:
3611 case Intrinsic::nearbyint:
3612 case Intrinsic::pow:
3613 case Intrinsic::powi:
3614 case Intrinsic::rint:
3615 case Intrinsic::round:
3616 case Intrinsic::roundeven:
3617 case Intrinsic::sin:
3618 case Intrinsic::sqrt:
3619 case Intrinsic::trunc:
3620 case Intrinsic::ctpop:
3621 case Intrinsic::ctlz:
3622 case Intrinsic::cttz:
3623 case Intrinsic::expect:
3624 case Intrinsic::experimental_noalias_scope_decl:
3625 case Intrinsic::experimental_constrained_fadd:
3626 case Intrinsic::experimental_constrained_fsub:
3627 case Intrinsic::experimental_constrained_fmul:
3628 case Intrinsic::experimental_constrained_fdiv:
3629 case Intrinsic::experimental_constrained_frem:
3630 case Intrinsic::experimental_constrained_fma:
3631 case Intrinsic::experimental_constrained_fptoui:
3632 case Intrinsic::experimental_constrained_fptosi:
3633 case Intrinsic::experimental_constrained_uitofp:
3634 case Intrinsic::experimental_constrained_sitofp:
3635 case Intrinsic::experimental_constrained_fptrunc:
3636 case Intrinsic::experimental_constrained_fpext:
3637 case Intrinsic::experimental_constrained_fcmp:
3638 case Intrinsic::experimental_constrained_fcmps:
3639 case Intrinsic::experimental_constrained_fmuladd:
3640 case Intrinsic::fmuladd:
3641 case Intrinsic::memset:
3642 case Intrinsic::memcpy:
3643 case Intrinsic::lifetime_start:
3644 case Intrinsic::lifetime_end:
3645 case Intrinsic::dbg_declare:
3646 case Intrinsic::dbg_value:
3647 case Intrinsic::annotation:
3648 case Intrinsic::var_annotation:
3649 case Intrinsic::ptr_annotation:
3650 case Intrinsic::invariant_start:
3651 case Intrinsic::invariant_end:
3652 case Intrinsic::dbg_label:
3653 case Intrinsic::trap:
3654 case Intrinsic::arithmetic_fence:
3655 case Intrinsic::uadd_with_overflow:
3656 case Intrinsic::usub_with_overflow:
3657 return true;
3658 default:
3659 // Unknown intrinsics' declarations should always be translated
3660 return false;
3661 }
3662 }
3663
3664 // Add decoration if needed
3665 SPIRVInstruction *addFPBuiltinDecoration(SPIRVModule *BM, IntrinsicInst *II,
3666 SPIRVInstruction *I) {
3667 const bool AllowFPMaxError =
3668 BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_fp_max_error);
3669 assert(II->getCalledFunction()->getName().startswith("llvm.fpbuiltin"));
3670 // Add a new decoration for llvm.builtin intrinsics, if needed
3671 if (AllowFPMaxError)
3672 if (II->getAttributes().hasFnAttr("fpbuiltin-max-error")) {
3673 double F = 0.0;
3674 II->getAttributes()
3675 .getFnAttr("fpbuiltin-max-error")
3676 .getValueAsString()
3677 .getAsDouble(F);
3678 I->addDecorate(DecorationFPMaxErrorDecorationINTEL,
3679 convertFloatToSPIRVWord(F));
3680 }
3681 return I;
3682 }
3683
3684 // Performs mapping of LLVM IR rounding mode to SPIR-V rounding mode
3685 // Value *V is metadata <rounding mode> argument of
3686 // llvm.experimental.constrained.* intrinsics
3687 SPIRVInstruction *
3688 LLVMToSPIRVBase::applyRoundingModeConstraint(Value *V, SPIRVInstruction *I) {
3689 StringRef RMode =
3690 cast<MDString>(cast<MetadataAsValue>(V)->getMetadata())->getString();
3691 if (RMode.endswith("tonearest"))
3692 I->addFPRoundingMode(FPRoundingModeRTE);
3693 else if (RMode.endswith("towardzero"))
3694 I->addFPRoundingMode(FPRoundingModeRTZ);
3695 else if (RMode.endswith("upward"))
3696 I->addFPRoundingMode(FPRoundingModeRTP);
3697 else if (RMode.endswith("downward"))
3698 I->addFPRoundingMode(FPRoundingModeRTN);
3699 return I;
3700 }
3701
3702 static SPIRVWord getBuiltinIdForIntrinsic(Intrinsic::ID IID) {
3703 switch (IID) {
3704 // Note: In some cases the semantics of the OpenCL builtin are not identical
3705 // to the semantics of the corresponding LLVM IR intrinsic. The LLVM
3706 // intrinsics handled here assume the default floating point environment
3707 // (no unmasked exceptions, round-to-nearest-ties-even rounding mode)
3708 // and assume that the operations have no side effects (FP status flags
3709 // aren't maintained), so the OpenCL builtin behavior should be
3710 // acceptable.
3711 case Intrinsic::ceil:
3712 return OpenCLLIB::Ceil;
3713 case Intrinsic::copysign:
3714 return OpenCLLIB::Copysign;
3715 case Intrinsic::cos:
3716 return OpenCLLIB::Cos;
3717 case Intrinsic::exp:
3718 return OpenCLLIB::Exp;
3719 case Intrinsic::exp2:
3720 return OpenCLLIB::Exp2;
3721 case Intrinsic::fabs:
3722 return OpenCLLIB::Fabs;
3723 case Intrinsic::floor:
3724 return OpenCLLIB::Floor;
3725 case Intrinsic::fma:
3726 return OpenCLLIB::Fma;
3727 case Intrinsic::log:
3728 return OpenCLLIB::Log;
3729 case Intrinsic::log10:
3730 return OpenCLLIB::Log10;
3731 case Intrinsic::log2:
3732 return OpenCLLIB::Log2;
3733 case Intrinsic::maximum:
3734 return OpenCLLIB::Fmax;
3735 case Intrinsic::maxnum:
3736 return OpenCLLIB::Fmax;
3737 case Intrinsic::minimum:
3738 return OpenCLLIB::Fmin;
3739 case Intrinsic::minnum:
3740 return OpenCLLIB::Fmin;
3741 case Intrinsic::nearbyint:
3742 return OpenCLLIB::Rint;
3743 case Intrinsic::pow:
3744 return OpenCLLIB::Pow;
3745 case Intrinsic::powi:
3746 return OpenCLLIB::Pown;
3747 case Intrinsic::rint:
3748 return OpenCLLIB::Rint;
3749 case Intrinsic::round:
3750 return OpenCLLIB::Round;
3751 case Intrinsic::roundeven:
3752 return OpenCLLIB::Rint;
3753 case Intrinsic::sin:
3754 return OpenCLLIB::Sin;
3755 case Intrinsic::sqrt:
3756 return OpenCLLIB::Sqrt;
3757 case Intrinsic::trunc:
3758 return OpenCLLIB::Trunc;
3759 default:
3760 assert(false && "Builtin ID requested for Unhandled intrinsic!");
3761 return 0;
3762 }
3763 }
3764
3765 static SPIRVWord getNativeBuiltinIdForIntrinsic(Intrinsic::ID IID) {
3766 switch (IID) {
3767 case Intrinsic::cos:
3768 return OpenCLLIB::Native_cos;
3769 case Intrinsic::exp:
3770 return OpenCLLIB::Native_exp;
3771 case Intrinsic::exp2:
3772 return OpenCLLIB::Native_exp2;
3773 case Intrinsic::log:
3774 return OpenCLLIB::Native_log;
3775 case Intrinsic::log10:
3776 return OpenCLLIB::Native_log10;
3777 case Intrinsic::log2:
3778 return OpenCLLIB::Native_log2;
3779 case Intrinsic::sin:
3780 return OpenCLLIB::Native_sin;
3781 case Intrinsic::sqrt:
3782 return OpenCLLIB::Native_sqrt;
3783 default:
3784 return getBuiltinIdForIntrinsic(IID);
3785 }
3786 }
3787
3788 static bool allowsApproxFunction(IntrinsicInst *II) {
3789 auto *Ty = II->getType();
3790 // OpenCL native_* built-ins only support single precision data type
3791 return II->hasApproxFunc() &&
3792 (Ty->isFloatTy() ||
3793 (Ty->isVectorTy() &&
3794 cast<VectorType>(Ty)->getElementType()->isFloatTy()));
3795 }
3796
3797 SPIRVValue *LLVMToSPIRVBase::transIntrinsicInst(IntrinsicInst *II,
3798 SPIRVBasicBlock *BB) {
3799 auto GetMemoryAccess =
3800 [](MemIntrinsic *MI,
3801 bool AllowTwoMemAccessMasks) -> std::vector<SPIRVWord> {
3802 std::vector<SPIRVWord> MemoryAccess(1, MemoryAccessMaskNone);
3803 MaybeAlign DestAlignVal = MI->getDestAlign();
3804 if (DestAlignVal) {
3805 Align AlignVal = *DestAlignVal;
3806 MemoryAccess[0] |= MemoryAccessAlignedMask;
3807 if (auto *MTI = dyn_cast<MemCpyInst>(MI)) {
3808 MaybeAlign SourceAlignVal = MTI->getSourceAlign();
3809 assert(SourceAlignVal && "Missed Source alignment!");
3810
3811 // In a case when alignment of source differs from dest one
3812 // we either preserve both (allowed since SPIR-V 1.4), or the least
3813 // value is guaranteed anyway.
3814 if (AllowTwoMemAccessMasks) {
3815 if (*DestAlignVal != *SourceAlignVal) {
3816 MemoryAccess.push_back(DestAlignVal.valueOrOne().value());
3817 MemoryAccess.push_back(MemoryAccessAlignedMask);
3818 AlignVal = *SourceAlignVal;
3819 }
3820 } else {
3821 AlignVal = std::min(*DestAlignVal, *SourceAlignVal);
3822 }
3823 }
3824 MemoryAccess.push_back(AlignVal.value());
3825 }
3826 if (MI->isVolatile())
3827 MemoryAccess[0] |= MemoryAccessVolatileMask;
3828 return MemoryAccess;
3829 };
3830
3831 // LLVM intrinsics with known translation to SPIR-V are handled here. They
3832 // also must be registered at isKnownIntrinsic function in order to make
3833 // -spirv-allow-unknown-intrinsics work correctly.
3834 auto IID = II->getIntrinsicID();
3835 switch (IID) {
3836 case Intrinsic::fabs:
3837 case Intrinsic::fma:
3838 case Intrinsic::maxnum:
3839 case Intrinsic::minnum:
3840 case Intrinsic::fmuladd: {
3841 Type *Ty = II->getType();
3842 if (Ty->isBFloatTy())
3843 BM->addCapability(internal::CapabilityBFloat16ArithmeticINTEL);
3844 break;
3845 }
3846 default:
3847 break;
3848 }
3849 switch (IID) {
3850 case Intrinsic::assume: {
3851 // llvm.assume translation is currently supported only within
3852 // SPV_KHR_expect_assume extension, ignore it otherwise, since it's
3853 // an optimization hint
3854 if (BM->isAllowedToUseExtension(ExtensionID::SPV_KHR_expect_assume)) {
3855 SPIRVValue *Condition = transValue(II->getArgOperand(0), BB);
3856 return BM->addAssumeTrueKHRInst(Condition, BB);
3857 }
3858 return nullptr;
3859 }
3860 case Intrinsic::bitreverse: {
3861 BM->addCapability(CapabilityShader);
3862 SPIRVType *Ty = transType(II->getType());
3863 SPIRVValue *Op = transValue(II->getArgOperand(0), BB);
3864 return BM->addUnaryInst(OpBitReverse, Ty, Op, BB);
3865 }
3866
3867 // Unary FP intrinsic
3868 case Intrinsic::ceil:
3869 case Intrinsic::cos:
3870 case Intrinsic::exp:
3871 case Intrinsic::exp2:
3872 case Intrinsic::fabs:
3873 case Intrinsic::floor:
3874 case Intrinsic::log:
3875 case Intrinsic::log10:
3876 case Intrinsic::log2:
3877 case Intrinsic::nearbyint:
3878 case Intrinsic::rint:
3879 case Intrinsic::round:
3880 case Intrinsic::roundeven:
3881 case Intrinsic::sin:
3882 case Intrinsic::sqrt:
3883 case Intrinsic::trunc: {
3884 if (!checkTypeForSPIRVExtendedInstLowering(II, BM))
3885 break;
3886 SPIRVWord ExtOp = allowsApproxFunction(II)
3887 ? getNativeBuiltinIdForIntrinsic(IID)
3888 : getBuiltinIdForIntrinsic(IID);
3889 SPIRVType *STy = transType(II->getType());
3890 std::vector<SPIRVValue *> Ops(1, transValue(II->getArgOperand(0), BB));
3891 return BM->addExtInst(STy, BM->getExtInstSetId(SPIRVEIS_OpenCL), ExtOp, Ops,
3892 BB);
3893 }
3894 // Binary FP intrinsics
3895 case Intrinsic::copysign:
3896 case Intrinsic::pow:
3897 case Intrinsic::powi:
3898 case Intrinsic::maximum:
3899 case Intrinsic::maxnum:
3900 case Intrinsic::minimum:
3901 case Intrinsic::minnum: {
3902 if (!checkTypeForSPIRVExtendedInstLowering(II, BM))
3903 break;
3904 SPIRVWord ExtOp = allowsApproxFunction(II)
3905 ? getNativeBuiltinIdForIntrinsic(IID)
3906 : getBuiltinIdForIntrinsic(IID);
3907 SPIRVType *STy = transType(II->getType());
3908 std::vector<SPIRVValue *> Ops{transValue(II->getArgOperand(0), BB),
3909 transValue(II->getArgOperand(1), BB)};
3910 return BM->addExtInst(STy, BM->getExtInstSetId(SPIRVEIS_OpenCL), ExtOp, Ops,
3911 BB);
3912 }
3913 case Intrinsic::umin:
3914 case Intrinsic::umax:
3915 case Intrinsic::smin:
3916 case Intrinsic::smax: {
3917 Type *BoolTy = IntegerType::getInt1Ty(M->getContext());
3918 SPIRVValue *FirstArgVal = transValue(II->getArgOperand(0), BB);
3919 SPIRVValue *SecondArgVal = transValue(II->getArgOperand(1), BB);
3920
3921 Op OC =
3922 (IID == Intrinsic::smin)
3923 ? OpSLessThan
3924 : ((IID == Intrinsic::smax)
3925 ? OpSGreaterThan
3926 : ((IID == Intrinsic::umin) ? OpULessThan : OpUGreaterThan));
3927 if (auto *VecTy = dyn_cast<VectorType>(II->getArgOperand(0)->getType()))
3928 BoolTy = VectorType::get(BoolTy, VecTy->getElementCount());
3929 SPIRVValue *Cmp =
3930 BM->addCmpInst(OC, transType(BoolTy), FirstArgVal, SecondArgVal, BB);
3931 return BM->addSelectInst(Cmp, FirstArgVal, SecondArgVal, BB);
3932 }
3933 case Intrinsic::fma: {
3934 if (!checkTypeForSPIRVExtendedInstLowering(II, BM))
3935 break;
3936 SPIRVType *STy = transType(II->getType());
3937 std::vector<SPIRVValue *> Ops{transValue(II->getArgOperand(0), BB),
3938 transValue(II->getArgOperand(1), BB),
3939 transValue(II->getArgOperand(2), BB)};
3940 if (BM->isAllowedToUseExtension(ExtensionID::SPV_KHR_fma))
3941 return BM->addInstTemplate(OpFmaKHR, BM->getIds(Ops), BB, STy);
3942 return BM->addExtInst(STy, BM->getExtInstSetId(SPIRVEIS_OpenCL),
3943 OpenCLLIB::Fma, Ops, BB);
3944 }
3945 case Intrinsic::abs: {
3946 if (!checkTypeForSPIRVExtendedInstLowering(II, BM))
3947 break;
3948 // LLVM has only one version of abs and it is only for signed integers. We
3949 // unconditionally choose SAbs here
3950 SPIRVWord ExtOp = OpenCLLIB::SAbs;
3951 SPIRVType *STy = transType(II->getType());
3952 std::vector<SPIRVValue *> Ops(1, transValue(II->getArgOperand(0), BB));
3953 return BM->addExtInst(STy, BM->getExtInstSetId(SPIRVEIS_OpenCL), ExtOp, Ops,
3954 BB);
3955 }
3956 case Intrinsic::ctpop: {
3957 return BM->addUnaryInst(OpBitCount, transType(II->getType()),
3958 transValue(II->getArgOperand(0), BB), BB);
3959 }
3960 case Intrinsic::ctlz:
3961 case Intrinsic::cttz: {
3962 SPIRVWord ExtOp = IID == Intrinsic::ctlz ? OpenCLLIB::Clz : OpenCLLIB::Ctz;
3963 SPIRVType *Ty = transType(II->getType());
3964 std::vector<SPIRVValue *> Ops(1, transValue(II->getArgOperand(0), BB));
3965 return BM->addExtInst(Ty, BM->getExtInstSetId(SPIRVEIS_OpenCL), ExtOp, Ops,
3966 BB);
3967 }
3968 case Intrinsic::expect: {
3969 // llvm.expect translation is currently supported only within
3970 // SPV_KHR_expect_assume extension, replace it with a translated value of #0
3971 // operand otherwise, since it's an optimization hint
3972 SPIRVValue *Value = transValue(II->getArgOperand(0), BB);
3973 if (BM->isAllowedToUseExtension(ExtensionID::SPV_KHR_expect_assume)) {
3974 SPIRVType *Ty = transType(II->getType());
3975 SPIRVValue *ExpectedValue = transValue(II->getArgOperand(1), BB);
3976 return BM->addExpectKHRInst(Ty, Value, ExpectedValue, BB);
3977 }
3978 return Value;
3979 }
3980 case Intrinsic::experimental_constrained_fadd: {
3981 auto BI = BM->addBinaryInst(OpFAdd, transType(II->getType()),
3982 transValue(II->getArgOperand(0), BB),
3983 transValue(II->getArgOperand(1), BB), BB);
3984 return applyRoundingModeConstraint(II->getOperand(2), BI);
3985 }
3986 case Intrinsic::experimental_constrained_fsub: {
3987 auto BI = BM->addBinaryInst(OpFSub, transType(II->getType()),
3988 transValue(II->getArgOperand(0), BB),
3989 transValue(II->getArgOperand(1), BB), BB);
3990 return applyRoundingModeConstraint(II->getOperand(2), BI);
3991 }
3992 case Intrinsic::experimental_constrained_fmul: {
3993 auto BI = BM->addBinaryInst(OpFMul, transType(II->getType()),
3994 transValue(II->getArgOperand(0), BB),
3995 transValue(II->getArgOperand(1), BB), BB);
3996 return applyRoundingModeConstraint(II->getOperand(2), BI);
3997 }
3998 case Intrinsic::experimental_constrained_fdiv: {
3999 auto BI = BM->addBinaryInst(OpFDiv, transType(II->getType()),
4000 transValue(II->getArgOperand(0), BB),
4001 transValue(II->getArgOperand(1), BB), BB);
4002 return applyRoundingModeConstraint(II->getOperand(2), BI);
4003 }
4004 case Intrinsic::experimental_constrained_frem: {
4005 auto BI = BM->addBinaryInst(OpFRem, transType(II->getType()),
4006 transValue(II->getArgOperand(0), BB),
4007 transValue(II->getArgOperand(1), BB), BB);
4008 return applyRoundingModeConstraint(II->getOperand(2), BI);
4009 }
4010 case Intrinsic::experimental_constrained_fma: {
4011 std::vector<SPIRVValue *> Args{transValue(II->getArgOperand(0), BB),
4012 transValue(II->getArgOperand(1), BB),
4013 transValue(II->getArgOperand(2), BB)};
4014 SPIRVInstruction *BI;
4015 if (BM->isAllowedToUseExtension(ExtensionID::SPV_KHR_fma))
4016 BI = BM->addInstTemplate(OpFmaKHR, BM->getIds(Args), BB,
4017 transType(II->getType()));
4018 else
4019 BI = BM->addExtInst(transType(II->getType()),
4020 BM->getExtInstSetId(SPIRVEIS_OpenCL), OpenCLLIB::Fma,
4021 Args, BB);
4022 return applyRoundingModeConstraint(II->getOperand(3), BI);
4023 }
4024 case Intrinsic::experimental_constrained_fptoui: {
4025 return BM->addUnaryInst(OpConvertFToU, transType(II->getType()),
4026 transValue(II->getArgOperand(0), BB), BB);
4027 }
4028 case Intrinsic::experimental_constrained_fptosi: {
4029 return BM->addUnaryInst(OpConvertFToS, transType(II->getType()),
4030 transValue(II->getArgOperand(0), BB), BB);
4031 }
4032 case Intrinsic::experimental_constrained_uitofp: {
4033 auto BI = BM->addUnaryInst(OpConvertUToF, transType(II->getType()),
4034 transValue(II->getArgOperand(0), BB), BB);
4035 return applyRoundingModeConstraint(II->getOperand(1), BI);
4036 }
4037 case Intrinsic::experimental_constrained_sitofp: {
4038 auto BI = BM->addUnaryInst(OpConvertSToF, transType(II->getType()),
4039 transValue(II->getArgOperand(0), BB), BB);
4040 return applyRoundingModeConstraint(II->getOperand(1), BI);
4041 }
4042 case Intrinsic::experimental_constrained_fpext: {
4043 return BM->addUnaryInst(OpFConvert, transType(II->getType()),
4044 transValue(II->getArgOperand(0), BB), BB);
4045 }
4046 case Intrinsic::experimental_constrained_fptrunc: {
4047 auto BI = BM->addUnaryInst(OpFConvert, transType(II->getType()),
4048 transValue(II->getArgOperand(0), BB), BB);
4049 return applyRoundingModeConstraint(II->getOperand(1), BI);
4050 }
4051 case Intrinsic::experimental_constrained_fcmp:
4052 case Intrinsic::experimental_constrained_fcmps: {
4053 auto MetaMod = cast<MetadataAsValue>(II->getOperand(2))->getMetadata();
4054 Op CmpTypeOp = StringSwitch<Op>(cast<MDString>(MetaMod)->getString())
4055 .Case("oeq", OpFOrdEqual)
4056 .Case("ogt", OpFOrdGreaterThan)
4057 .Case("oge", OpFOrdGreaterThanEqual)
4058 .Case("olt", OpFOrdLessThan)
4059 .Case("ole", OpFOrdLessThanEqual)
4060 .Case("one", OpFOrdNotEqual)
4061 .Case("ord", OpOrdered)
4062 .Case("ueq", OpFUnordEqual)
4063 .Case("ugt", OpFUnordGreaterThan)
4064 .Case("uge", OpFUnordGreaterThanEqual)
4065 .Case("ult", OpFUnordLessThan)
4066 .Case("ule", OpFUnordLessThanEqual)
4067 .Case("une", OpFUnordNotEqual)
4068 .Case("uno", OpUnordered)
4069 .Default(OpNop);
4070 assert(CmpTypeOp != OpNop && "Invalid condition code!");
4071 return BM->addCmpInst(CmpTypeOp, transType(II->getType()),
4072 transValue(II->getOperand(0), BB),
4073 transValue(II->getOperand(1), BB), BB);
4074 }
4075 case Intrinsic::experimental_constrained_fmuladd: {
4076 SPIRVType *Ty = transType(II->getType());
4077 SPIRVValue *Mul =
4078 BM->addBinaryInst(OpFMul, Ty, transValue(II->getArgOperand(0), BB),
4079 transValue(II->getArgOperand(1), BB), BB);
4080 auto BI = BM->addBinaryInst(OpFAdd, Ty, Mul,
4081 transValue(II->getArgOperand(2), BB), BB);
4082 return applyRoundingModeConstraint(II->getOperand(3), BI);
4083 }
4084 case Intrinsic::fmuladd: {
4085 // For llvm.fmuladd.* fusion is not guaranteed. If a fused multiply-add
4086 // is required the corresponding llvm.fma.* intrinsic function should be
4087 // used instead.
4088 // If allowed, let's replace llvm.fmuladd.* with mad from OpenCL extended
4089 // instruction set, as it has the same semantic for FULL_PROFILE OpenCL
4090 // devices (implementation-defined for EMBEDDED_PROFILE).
4091 if (BM->shouldReplaceLLVMFmulAddWithOpenCLMad()) {
4092 std::vector<SPIRVValue *> Ops{transValue(II->getArgOperand(0), BB),
4093 transValue(II->getArgOperand(1), BB),
4094 transValue(II->getArgOperand(2), BB)};
4095 return BM->addExtInst(transType(II->getType()),
4096 BM->getExtInstSetId(SPIRVEIS_OpenCL),
4097 OpenCLLIB::Mad, Ops, BB);
4098 }
4099
4100 // Otherwise, just break llvm.fmuladd.* into a pair of fmul + fadd
4101 SPIRVType *Ty = transType(II->getType());
4102 SPIRVValue *Mul =
4103 BM->addBinaryInst(OpFMul, Ty, transValue(II->getArgOperand(0), BB),
4104 transValue(II->getArgOperand(1), BB), BB);
4105 return BM->addBinaryInst(OpFAdd, Ty, Mul,
4106 transValue(II->getArgOperand(2), BB), BB);
4107 }
4108 case Intrinsic::uadd_sat:
4109 case Intrinsic::usub_sat:
4110 case Intrinsic::sadd_sat:
4111 case Intrinsic::ssub_sat: {
4112 SPIRVWord ExtOp;
4113 if (IID == Intrinsic::uadd_sat)
4114 ExtOp = OpenCLLIB::UAdd_sat;
4115 else if (IID == Intrinsic::usub_sat)
4116 ExtOp = OpenCLLIB::USub_sat;
4117 else if (IID == Intrinsic::sadd_sat)
4118 ExtOp = OpenCLLIB::SAdd_sat;
4119 else
4120 ExtOp = OpenCLLIB::SSub_sat;
4121
4122 SPIRVType *Ty = transType(II->getType());
4123 std::vector<SPIRVValue *> Operands = {transValue(II->getArgOperand(0), BB),
4124 transValue(II->getArgOperand(1), BB)};
4125 return BM->addExtInst(Ty, BM->getExtInstSetId(SPIRVEIS_OpenCL), ExtOp,
4126 std::move(Operands), BB);
4127 }
4128 case Intrinsic::uadd_with_overflow: {
4129 return BM->addBinaryInst(OpIAddCarry, transType(II->getType()),
4130 transValue(II->getArgOperand(0), BB),
4131 transValue(II->getArgOperand(1), BB), BB);
4132 }
4133 case Intrinsic::usub_with_overflow: {
4134 return BM->addBinaryInst(OpISubBorrow, transType(II->getType()),
4135 transValue(II->getArgOperand(0), BB),
4136 transValue(II->getArgOperand(1), BB), BB);
4137 }
4138 case Intrinsic::memset: {
4139 // Generally there is no direct mapping of memset to SPIR-V. But it turns
4140 // out that memset is emitted by Clang for initialization in default
4141 // constructors so we need some basic support. The code below only handles
4142 // cases with constant value and constant length.
4143 MemSetInst *MSI = cast<MemSetInst>(II);
4144 Value *Val = MSI->getValue();
4145 if (!isa<Constant>(Val)) {
4146 assert(false &&
4147 "Can't translate llvm.memset with non-const `value` argument");
4148 return nullptr;
4149 }
4150 Value *Len = MSI->getLength();
4151 if (!isa<ConstantInt>(Len)) {
4152 assert(false &&
4153 "Can't translate llvm.memset with non-const `length` argument");
4154 return nullptr;
4155 }
4156 uint64_t NumElements = static_cast<ConstantInt *>(Len)->getZExtValue();
4157 auto *AT = ArrayType::get(Val->getType(), NumElements);
4158 SPIRVTypeArray *CompositeTy = static_cast<SPIRVTypeArray *>(transType(AT));
4159 SPIRVValue *Init;
4160 if (cast<Constant>(Val)->isZeroValue()) {
4161 Init = BM->addNullConstant(CompositeTy);
4162 } else {
4163 // On 32-bit systems, size_type of std::vector is not a 64-bit type. Let's
4164 // assume that we won't encounter memset for more than 2^32 elements and
4165 // insert explicit cast to avoid possible warning/error about narrowing
4166 // conversion
4167 auto TNumElts =
4168 static_cast<std::vector<SPIRVValue *>::size_type>(NumElements);
4169 std::vector<SPIRVValue *> Elts(TNumElts, transValue(Val, BB));
4170 Init = BM->addCompositeConstant(CompositeTy, Elts);
4171 }
4172 SPIRVType *VarTy = transPointerType(AT, SPIRV::SPIRAS_Constant);
4173 SPIRVValue *Var = BM->addVariable(VarTy, /*isConstant*/ true,
4174 spv::internal::LinkageTypeInternal, Init,
4175 "", StorageClassUniformConstant, nullptr);
4176 SPIRVType *SourceTy =
4177 transPointerType(Val->getType(), SPIRV::SPIRAS_Constant);
4178 SPIRVValue *Source = BM->addUnaryInst(OpBitcast, SourceTy, Var, BB);
4179 SPIRVValue *Target = transValue(MSI->getRawDest(), BB);
4180 return BM->addCopyMemorySizedInst(
4181 Target, Source, CompositeTy->getLength(),
4182 GetMemoryAccess(MSI,
4183 BM->isAllowedToUseVersion(VersionNumber::SPIRV_1_4)),
4184 BB);
4185 } break;
4186 case Intrinsic::memcpy:
4187 return BM->addCopyMemorySizedInst(
4188 transValue(II->getOperand(0), BB), transValue(II->getOperand(1), BB),
4189 transValue(II->getOperand(2), BB),
4190 GetMemoryAccess(cast<MemIntrinsic>(II),
4191 BM->isAllowedToUseVersion(VersionNumber::SPIRV_1_4)),
4192 BB);
4193 case Intrinsic::lifetime_start:
4194 case Intrinsic::lifetime_end: {
4195 Op OC = (II->getIntrinsicID() == Intrinsic::lifetime_start)
4196 ? OpLifetimeStart
4197 : OpLifetimeStop;
4198 int64_t Size = dyn_cast<ConstantInt>(II->getOperand(0))->getSExtValue();
4199 if (Size == -1)
4200 Size = 0;
4201 return BM->addLifetimeInst(OC, transValue(II->getOperand(1), BB), Size, BB);
4202 }
4203 // We don't want to mix translation of regular code and debug info, because
4204 // it creates a mess, therefore translation of debug intrinsics is
4205 // postponed until LLVMToSPIRVDbgTran::finalizeDebug...() methods.
4206 case Intrinsic::dbg_declare:
4207 return DbgTran->createDebugDeclarePlaceholder(cast<DbgDeclareInst>(II), BB);
4208 case Intrinsic::dbg_value:
4209 return DbgTran->createDebugValuePlaceholder(cast<DbgValueInst>(II), BB);
4210 case Intrinsic::annotation: {
4211 SPIRVType *Ty = transType(II->getType());
4212
4213 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(II->getArgOperand(1));
4214 if (!GEP)
4215 return nullptr;
4216 Constant *C = cast<Constant>(GEP->getOperand(0));
4217 StringRef AnnotationString;
4218 if (!getConstantStringInfo(C, AnnotationString))
4219 return nullptr;
4220
4221 if (AnnotationString == kOCLBuiltinName::FPGARegIntel) {
4222 if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_fpga_reg))
4223 return BM->addFPGARegINTELInst(Ty, transValue(II->getOperand(0), BB),
4224 BB);
4225 else
4226 return transValue(II->getOperand(0), BB);
4227 }
4228
4229 return nullptr;
4230 }
4231 case Intrinsic::var_annotation: {
4232 SPIRVValue *SV;
4233 if (auto *BI = dyn_cast<BitCastInst>(II->getArgOperand(0))) {
4234 SV = transValue(BI->getOperand(0), BB);
4235 } else {
4236 SV = transValue(II->getOperand(0), BB);
4237 }
4238
4239 std::string AnnotationString;
4240 processAnnotationString(II, AnnotationString);
4241 DecorationsInfoVec Decorations =
4242 tryParseAnnotationString(BM, AnnotationString).MemoryAttributesVec;
4243
4244 // If we didn't find any IntelFPGA-specific decorations, let's add the whole
4245 // annotation string as UserSemantic Decoration
4246 if (Decorations.empty()) {
4247 SV->addDecorate(
4248 new SPIRVDecorateUserSemanticAttr(SV, AnnotationString.c_str()));
4249 } else {
4250 addAnnotationDecorations(SV, Decorations);
4251 }
4252 return SV;
4253 }
4254 // The layout of llvm.ptr.annotation is:
4255 // declare iN* @llvm.ptr.annotation.p<address space>iN(
4256 // iN* <val>, i8* <str>, i8* <str>, i32 <int>, i8* <ptr>)
4257 // where N is a power of two number,
4258 // first i8* <str> stands for the annotation itself,
4259 // second i8* <str> is for the location (file name),
4260 // i8* <ptr> is a pointer on a GV, which can carry optinal variadic
4261 // clang::annotation attribute expression arguments.
4262 case Intrinsic::ptr_annotation: {
4263 // Strip all bitcast and addrspace casts from the pointer argument:
4264 // llvm annotation intrinsic only takes i8*, so the original pointer
4265 // probably had to loose its addrspace and its original type.
4266 Value *AnnotSubj = II->getArgOperand(0);
4267 while (isa<BitCastInst>(AnnotSubj) || isa<AddrSpaceCastInst>(AnnotSubj)) {
4268 AnnotSubj = cast<CastInst>(AnnotSubj)->getOperand(0);
4269 }
4270
4271 std::string AnnotationString;
4272 processAnnotationString(II, AnnotationString);
4273 AnnotationDecorations Decorations =
4274 tryParseAnnotationString(BM, AnnotationString);
4275
4276 // Translate FPGARegIntel annotations to OpFPGARegINTEL.
4277 if (AnnotationString == kOCLBuiltinName::FPGARegIntel) {
4278 // TODO: Check for opaque pointer requirements.
4279 auto *Ty = transType(II->getType());
4280 auto *BI = dyn_cast<BitCastInst>(II->getOperand(0));
4281 if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_fpga_reg))
4282 return BM->addFPGARegINTELInst(Ty, transValue(BI, BB), BB);
4283 return transValue(BI, BB);
4284 }
4285
4286 // If the pointer is a GEP on a struct, then we have to emit a member
4287 // decoration for the GEP-accessed struct, or a memory access decoration
4288 // for the GEP itself. There may not be a GEP in this case if the access is
4289 // to the first member of the struct; if so, attempt to get a struct type
4290 // from an alloca instead.
4291 SPIRVType *StructTy = nullptr;
4292 [[maybe_unused]] SPIRVValue *ResPtr = nullptr;
4293 [[maybe_unused]] SPIRVWord MemberNumber = 0;
4294 if (auto *const GI = dyn_cast<GetElementPtrInst>(AnnotSubj)) {
4295 if (auto *const STy = dyn_cast<StructType>(GI->getSourceElementType())) {
4296 StructTy = transType(STy);
4297 ResPtr = transValue(GI, BB);
4298 MemberNumber = dyn_cast<ConstantInt>(GI->getOperand(2))->getZExtValue();
4299 }
4300 } else if (auto *const AI = dyn_cast<AllocaInst>(AnnotSubj)) {
4301 if (auto *const STy = dyn_cast<StructType>(AI->getAllocatedType())) {
4302 StructTy = transType(STy);
4303 ResPtr = transValue(AI, BB);
4304 MemberNumber = 0;
4305 }
4306 }
4307 if (StructTy) {
4308
4309 // If we didn't find any IntelFPGA-specific decorations, let's add the
4310 // whole annotation string as UserSemantic Decoration
4311 if (Decorations.MemoryAttributesVec.empty() &&
4312 Decorations.MemoryAccessesVec.empty()) {
4313 // TODO: Is there a way to detect that the annotation belongs solely
4314 // to struct member memory atributes or struct member memory access
4315 // controls? This would allow emitting just the necessary decoration.
4316 StructTy->addMemberDecorate(new SPIRVMemberDecorateUserSemanticAttr(
4317 StructTy, MemberNumber, AnnotationString.c_str()));
4318 ResPtr->addDecorate(new SPIRVDecorateUserSemanticAttr(
4319 ResPtr, AnnotationString.c_str()));
4320 } else {
4321 addAnnotationDecorationsForStructMember(
4322 StructTy, MemberNumber, Decorations.MemoryAttributesVec);
4323 // Apply the LSU parameter decoration to the pointer result of a GEP
4324 // to the given struct member (InBoundsPtrAccessChain in SPIR-V).
4325 // Decorating the member itself with a MemberDecoration is not feasible,
4326 // because multiple accesses to the struct-held memory can require
4327 // different LSU parameters.
4328 addAnnotationDecorations(ResPtr, Decorations.MemoryAccessesVec);
4329 }
4330 II->replaceAllUsesWith(II->getOperand(0));
4331 } else {
4332 // Memory accesses to a standalone pointer variable
4333 auto *DecSubj = transValue(II->getArgOperand(0), BB);
4334 if (Decorations.MemoryAccessesVec.empty())
4335 DecSubj->addDecorate(new SPIRVDecorateUserSemanticAttr(
4336 DecSubj, AnnotationString.c_str()));
4337 else
4338 // Apply the LSU parameter decoration to the pointer result of an
4339 // instruction. Note it's the address to the accessed memory that's
4340 // loaded from the original pointer variable, and not the value
4341 // accessed by the latter.
4342 addAnnotationDecorations(DecSubj, Decorations.MemoryAccessesVec);
4343 II->replaceAllUsesWith(II->getOperand(0));
4344 }
4345 return nullptr;
4346 }
4347 case Intrinsic::stacksave: {
4348 if (BM->isAllowedToUseExtension(
4349 ExtensionID::SPV_INTEL_variable_length_array)) {
4350 auto *Ty = transPointerType(Type::getInt8Ty(M->getContext()), 0);
4351 return BM->addInstTemplate(OpSaveMemoryINTEL, BB, Ty);
4352 }
4353 BM->getErrorLog().checkError(
4354 BM->isUnknownIntrinsicAllowed(II), SPIRVEC_InvalidFunctionCall, II,
4355 "Translation of llvm.stacksave intrinsic requires "
4356 "SPV_INTEL_variable_length_array extension or "
4357 "-spirv-allow-unknown-intrinsics option.");
4358 break;
4359 }
4360 case Intrinsic::stackrestore: {
4361 if (BM->isAllowedToUseExtension(
4362 ExtensionID::SPV_INTEL_variable_length_array)) {
4363 auto *Ptr = transValue(II->getArgOperand(0), BB);
4364 return BM->addInstTemplate(OpRestoreMemoryINTEL, {Ptr->getId()}, BB,
4365 nullptr);
4366 }
4367 BM->getErrorLog().checkError(
4368 BM->isUnknownIntrinsicAllowed(II), SPIRVEC_InvalidFunctionCall, II,
4369 "Translation of llvm.restore intrinsic requires "
4370 "SPV_INTEL_variable_length_array extension or "
4371 "-spirv-allow-unknown-intrinsics option.");
4372 break;
4373 }
4374 // We can just ignore/drop some intrinsics, like optimizations hint.
4375 case Intrinsic::experimental_noalias_scope_decl:
4376 case Intrinsic::invariant_start:
4377 case Intrinsic::invariant_end:
4378 case Intrinsic::dbg_label:
4379 // llvm.trap intrinsic is not implemented. But for now don't crash. This
4380 // change is pending the trap/abort intrinsic implementation.
4381 case Intrinsic::trap:
4382 // llvm.instrprof.* intrinsics are not supported
4383 case Intrinsic::instrprof_increment:
4384 case Intrinsic::instrprof_increment_step:
4385 case Intrinsic::instrprof_value_profile:
4386 return nullptr;
4387 case Intrinsic::is_constant: {
4388 auto *CO = dyn_cast<Constant>(II->getOperand(0));
4389 if (CO && isManifestConstant(CO))
4390 return transValue(ConstantInt::getTrue(II->getType()), BB, false);
4391 else
4392 return transValue(ConstantInt::getFalse(II->getType()), BB, false);
4393 }
4394 case Intrinsic::arithmetic_fence: {
4395 SPIRVType *Ty = transType(II->getType());
4396 SPIRVValue *Op = transValue(II->getArgOperand(0), BB);
4397 if (BM->isAllowedToUseExtension(ExtensionID::SPV_EXT_arithmetic_fence)) {
4398 BM->addCapability(CapabilityArithmeticFenceEXT);
4399 BM->addExtension(ExtensionID::SPV_EXT_arithmetic_fence);
4400 return BM->addUnaryInst(OpArithmeticFenceEXT, Ty, Op, BB);
4401 }
4402 if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_arithmetic_fence)) {
4403 // Note: SPV_INTEL_arithmetic_fence was unpublished and superseded by
4404 // SPV_EXT_arithmetic_fence.
4405 BM->addCapability(CapabilityArithmeticFenceEXT);
4406 BM->addExtension(ExtensionID::SPV_INTEL_arithmetic_fence);
4407 return BM->addUnaryInst(OpArithmeticFenceEXT, Ty, Op, BB);
4408 }
4409 return Op;
4410 }
4411 case Intrinsic::masked_gather: {
4412 if (!BM->isAllowedToUseExtension(
4413 ExtensionID::SPV_INTEL_masked_gather_scatter)) {
4414 BM->getErrorLog().checkError(
4415 BM->isUnknownIntrinsicAllowed(II), SPIRVEC_InvalidFunctionCall, II,
4416 "Translation of llvm.masked.gather intrinsic requires "
4417 "SPV_INTEL_masked_gather_scatter extension or "
4418 "-spirv-allow-unknown-intrinsics option.");
4419 return nullptr;
4420 }
4421 SPIRVType *Ty = transType(II->getType());
4422 auto *PtrVector = transValue(II->getArgOperand(0), BB);
4423 uint32_t Alignment =
4424 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
4425 auto *Mask = transValue(II->getArgOperand(2), BB);
4426 auto *FillEmpty = transValue(II->getArgOperand(3), BB);
4427 std::vector<SPIRVWord> Ops = {PtrVector->getId(), Alignment, Mask->getId(),
4428 FillEmpty->getId()};
4429 return BM->addInstTemplate(internal::OpMaskedGatherINTEL, Ops, BB, Ty);
4430 }
4431 case Intrinsic::masked_scatter: {
4432 if (!BM->isAllowedToUseExtension(
4433 ExtensionID::SPV_INTEL_masked_gather_scatter)) {
4434 BM->getErrorLog().checkError(
4435 BM->isUnknownIntrinsicAllowed(II), SPIRVEC_InvalidFunctionCall, II,
4436 "Translation of llvm.masked.scatter intrinsic requires "
4437 "SPV_INTEL_masked_gather_scatter extension or "
4438 "-spirv-allow-unknown-intrinsics option.");
4439 return nullptr;
4440 }
4441 auto *InputVector = transValue(II->getArgOperand(0), BB);
4442 auto *PtrVector = transValue(II->getArgOperand(1), BB);
4443 uint32_t Alignment =
4444 cast<ConstantInt>(II->getArgOperand(2))->getZExtValue();
4445 auto *Mask = transValue(II->getArgOperand(3), BB);
4446 std::vector<SPIRVWord> Ops = {InputVector->getId(), PtrVector->getId(),
4447 Alignment, Mask->getId()};
4448 return BM->addInstTemplate(internal::OpMaskedScatterINTEL, Ops, BB,
4449 nullptr);
4450 }
4451
4452 default:
4453 if (auto *BVar = transFPBuiltinIntrinsicInst(II, BB))
4454 return BVar;
4455 if (BM->isUnknownIntrinsicAllowed(II))
4456 return BM->addCallInst(
4457 transFunctionDecl(II->getCalledFunction()),
4458 transArguments(II, BB,
4459 SPIRVEntry::createUnique(OpFunctionCall).get()),
4460 BB);
4461 else
4462 // Other LLVM intrinsics shouldn't get to SPIRV, because they
4463 // can't be represented in SPIRV or aren't implemented yet.
4464 BM->SPIRVCK(false, InvalidFunctionCall,
4465 II->getCalledOperand()->getName().str());
4466 }
4467 return nullptr;
4468 }
4469
4470 LLVMToSPIRVBase::FPBuiltinType
4471 LLVMToSPIRVBase::getFPBuiltinType(IntrinsicInst *II, StringRef &OpName) {
4472 StringRef Name = II->getCalledFunction()->getName();
4473 if (!Name.startswith("llvm.fpbuiltin"))
4474 return FPBuiltinType::UNKNOWN;
4475 Name.consume_front("llvm.fpbuiltin.");
4476 OpName = Name.split('.').first;
4477 FPBuiltinType Type =
4478 StringSwitch<FPBuiltinType>(OpName)
4479 .Cases("fadd", "fsub", "fmul", "fdiv", "frem",
4480 FPBuiltinType::REGULAR_MATH)
4481 .Cases("sin", "cos", "tan", FPBuiltinType::EXT_1OPS)
4482 .Cases("sinh", "cosh", "tanh", FPBuiltinType::EXT_1OPS)
4483 .Cases("asin", "acos", "atan", FPBuiltinType::EXT_1OPS)
4484 .Cases("asinh", "acosh", "atanh", FPBuiltinType::EXT_1OPS)
4485 .Cases("exp", "exp2", "exp10", "expm1", FPBuiltinType::EXT_1OPS)
4486 .Cases("log", "log2", "log10", "log1p", FPBuiltinType::EXT_1OPS)
4487 .Cases("sqrt", "rsqrt", "erf", "erfc", FPBuiltinType::EXT_1OPS)
4488 .Cases("atan2", "pow", "hypot", "ldexp", FPBuiltinType::EXT_2OPS)
4489 .Case("sincos", FPBuiltinType::EXT_3OPS)
4490 .Default(FPBuiltinType::UNKNOWN);
4491 return Type;
4492 }
4493
4494 SPIRVValue *LLVMToSPIRVBase::transFPBuiltinIntrinsicInst(IntrinsicInst *II,
4495 SPIRVBasicBlock *BB) {
4496 StringRef OpName;
4497 auto FPBuiltinTypeVal = getFPBuiltinType(II, OpName);
4498 if (FPBuiltinTypeVal == FPBuiltinType::UNKNOWN)
4499 return nullptr;
4500 switch (FPBuiltinTypeVal) {
4501 case FPBuiltinType::REGULAR_MATH: {
4502 auto BinOp = StringSwitch<Op>(OpName)
4503 .Case("fadd", OpFAdd)
4504 .Case("fsub", OpFSub)
4505 .Case("fmul", OpFMul)
4506 .Case("fdiv", OpFDiv)
4507 .Case("frem", OpFRem)
4508 .Default(OpUndef);
4509 auto *BI = BM->addBinaryInst(BinOp, transType(II->getType()),
4510 transValue(II->getArgOperand(0), BB),
4511 transValue(II->getArgOperand(1), BB), BB);
4512 return addFPBuiltinDecoration(BM, II, BI);
4513 }
4514 case FPBuiltinType::EXT_1OPS: {
4515 if (!checkTypeForSPIRVExtendedInstLowering(II, BM))
4516 break;
4517 SPIRVType *STy = transType(II->getType());
4518 std::vector<SPIRVValue *> Ops(1, transValue(II->getArgOperand(0), BB));
4519 auto ExtOp = StringSwitch<SPIRVWord>(OpName)
4520 .Case("sin", OpenCLLIB::Sin)
4521 .Case("cos", OpenCLLIB::Cos)
4522 .Case("tan", OpenCLLIB::Tan)
4523 .Case("sinh", OpenCLLIB::Sinh)
4524 .Case("cosh", OpenCLLIB::Cosh)
4525 .Case("tanh", OpenCLLIB::Tanh)
4526 .Case("asin", OpenCLLIB::Asin)
4527 .Case("acos", OpenCLLIB::Acos)
4528 .Case("atan", OpenCLLIB::Atan)
4529 .Case("asinh", OpenCLLIB::Asinh)
4530 .Case("acosh", OpenCLLIB::Acosh)
4531 .Case("atanh", OpenCLLIB::Atanh)
4532 .Case("exp", OpenCLLIB::Exp)
4533 .Case("exp2", OpenCLLIB::Exp2)
4534 .Case("exp10", OpenCLLIB::Exp10)
4535 .Case("expm1", OpenCLLIB::Expm1)
4536 .Case("log", OpenCLLIB::Log)
4537 .Case("log2", OpenCLLIB::Log2)
4538 .Case("log10", OpenCLLIB::Log10)
4539 .Case("log1p", OpenCLLIB::Log1p)
4540 .Case("sqrt", OpenCLLIB::Sqrt)
4541 .Case("rsqrt", OpenCLLIB::Rsqrt)
4542 .Case("erf", OpenCLLIB::Erf)
4543 .Case("erfc", OpenCLLIB::Erfc)
4544 .Default(SPIRVWORD_MAX);
4545 assert(ExtOp != SPIRVWORD_MAX);
4546 auto *BI = BM->addExtInst(STy, BM->getExtInstSetId(SPIRVEIS_OpenCL), ExtOp,
4547 Ops, BB);
4548 return addFPBuiltinDecoration(BM, II, BI);
4549 }
4550 case FPBuiltinType::EXT_2OPS: {
4551 if (!checkTypeForSPIRVExtendedInstLowering(II, BM))
4552 break;
4553 SPIRVType *STy = transType(II->getType());
4554 std::vector<SPIRVValue *> Ops{transValue(II->getArgOperand(0), BB),
4555 transValue(II->getArgOperand(1), BB)};
4556 auto ExtOp = StringSwitch<SPIRVWord>(OpName)
4557 .Case("atan2", OpenCLLIB::Atan2)
4558 .Case("hypot", OpenCLLIB::Hypot)
4559 .Case("pow", OpenCLLIB::Pow)
4560 .Case("ldexp", OpenCLLIB::Ldexp)
4561 .Default(SPIRVWORD_MAX);
4562 assert(ExtOp != SPIRVWORD_MAX);
4563 auto *BI = BM->addExtInst(STy, BM->getExtInstSetId(SPIRVEIS_OpenCL), ExtOp,
4564 Ops, BB);
4565 return addFPBuiltinDecoration(BM, II, BI);
4566 }
4567 case FPBuiltinType::EXT_3OPS: {
4568 if (!checkTypeForSPIRVExtendedInstLowering(II, BM))
4569 break;
4570 SPIRVType *STy = transType(II->getType());
4571 std::vector<SPIRVValue *> Ops{transValue(II->getArgOperand(0), BB),
4572 transValue(II->getArgOperand(1), BB),
4573 transValue(II->getArgOperand(2), BB)};
4574 auto ExtOp = StringSwitch<SPIRVWord>(OpName)
4575 .Case("sincos", OpenCLLIB::Sincos)
4576 .Default(SPIRVWORD_MAX);
4577 assert(ExtOp != SPIRVWORD_MAX);
4578 auto *BI = BM->addExtInst(STy, BM->getExtInstSetId(SPIRVEIS_OpenCL), ExtOp,
4579 Ops, BB);
4580 return addFPBuiltinDecoration(BM, II, BI);
4581 }
4582 default:
4583 return nullptr;
4584 }
4585 return nullptr;
4586 }
4587
4588 SPIRVValue *LLVMToSPIRVBase::transFenceInst(FenceInst *FI,
4589 SPIRVBasicBlock *BB) {
4590 SPIRVWord MemorySemantics;
4591 // Fence ordering may only be Acquire, Release, AcquireRelease, or
4592 // SequentiallyConsistent
4593 switch (FI->getOrdering()) {
4594 case llvm::AtomicOrdering::Acquire:
4595 MemorySemantics = MemorySemanticsAcquireMask;
4596 break;
4597 case llvm::AtomicOrdering::Release:
4598 MemorySemantics = MemorySemanticsReleaseMask;
4599 break;
4600 case llvm::AtomicOrdering::AcquireRelease:
4601 MemorySemantics = MemorySemanticsAcquireReleaseMask;
4602 break;
4603 case llvm::AtomicOrdering::SequentiallyConsistent:
4604 MemorySemantics = MemorySemanticsSequentiallyConsistentMask;
4605 break;
4606 default:
4607 assert(false && "Unexpected fence ordering");
4608 MemorySemantics = SPIRVWORD_MAX;
4609 break;
4610 }
4611
4612 Module *M = FI->getParent()->getModule();
4613 // Treat all llvm.fence instructions as having CrossDevice scope:
4614 SPIRVValue *RetScope = transConstant(getUInt32(M, ScopeCrossDevice));
4615 SPIRVValue *Val = transConstant(getUInt32(M, MemorySemantics));
4616 assert(RetScope && Val && "RetScope and Value are not constants");
4617 return BM->addMemoryBarrierInst(static_cast<Scope>(RetScope->getId()),
4618 Val->getId(), BB);
4619 }
4620
4621 SPIRVValue *LLVMToSPIRVBase::transCallInst(CallInst *CI, SPIRVBasicBlock *BB) {
4622 assert(CI);
4623 Function *F = CI->getFunction();
4624 if (isa<InlineAsm>(CI->getCalledOperand()) &&
4625 BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_inline_assembly)) {
4626 // Inline asm is opaque, so we cannot reason about its FP contraction
4627 // requirements.
4628 SPIRVDBG(dbgs() << "[fp-contract] disabled for " << F->getName()
4629 << ": inline asm " << *CI << '\n');
4630 joinFPContract(F, FPContract::DISABLED);
4631 return transAsmCallINTEL(CI, BB);
4632 }
4633
4634 if (CI->isIndirectCall()) {
4635 // The function is not known in advance
4636 SPIRVDBG(dbgs() << "[fp-contract] disabled for " << F->getName()
4637 << ": indirect call " << *CI << '\n');
4638 joinFPContract(F, FPContract::DISABLED);
4639 return transIndirectCallInst(CI, BB);
4640 }
4641 return transDirectCallInst(CI, BB);
4642 }
4643
4644 // Helper function to process mini-float or int4 types for FP conversions.
4645 // Processes type width, packing, and creates the appropriate SPIRV type.
4646 // Returns the SPIRV type and outputs vector size information.
4647 static SPIRVType *
4648 processMiniFPOrInt4Type(Type *LLVMTy, FPEncodingWrap Encoding,
4649 std::function<Type *(Type *)> GetScalarTy,
4650 SPIRVModule *BM, unsigned &OutVecSize) {
4651 Type *ScalarTy = GetScalarTy(LLVMTy);
4652 unsigned TyWidth = cast<IntegerType>(ScalarTy)->getBitWidth();
4653 unsigned VecSize = 0;
4654
4655 if (TyWidth == 32) {
4656 // Int4 or FP4 packed in 32-bit integer, change type and vector size.
4657 assert((Encoding == FPEncodingWrap::E2M1 ||
4658 Encoding == FPEncodingWrap::Integer) &&
4659 "Unknown FP encoding");
4660 assert(!isLLVMCooperativeMatrixType(LLVMTy) &&
4661 "FP4 and Int4 matrices must not be packed");
4662 VecSize = 8;
4663 TyWidth = 4;
4664 } else if (TyWidth == 8 && (Encoding == FPEncodingWrap::E2M1 ||
4665 Encoding == FPEncodingWrap::Integer)) {
4666 assert(!isLLVMCooperativeMatrixType(LLVMTy) &&
4667 "FP4 and Int4 matrices must not be packed");
4668 // Int4 or FP4 packed in 8-bit integer, change type and vector size.
4669 VecSize = 2;
4670 TyWidth = 4;
4671 } else {
4672 if (LLVMTy->isVectorTy())
4673 VecSize = cast<VectorType>(LLVMTy)->getElementCount().getFixedValue();
4674 }
4675
4676 SPIRVType *Ty;
4677 if (Encoding == FPEncodingWrap::Integer) {
4678 Ty = BM->addIntegerType(TyWidth);
4679 } else {
4680 Ty = BM->addFloatType(TyWidth, Encoding);
4681 }
4682
4683 OutVecSize = VecSize;
4684 return Ty;
4685 }
4686
4687 SPIRVValue *LLVMToSPIRVBase::transDirectCallInst(CallInst *CI,
4688 SPIRVBasicBlock *BB) {
4689 SPIRVExtInstSetKind ExtSetKind = SPIRVEIS_Count;
4690 SPIRVWord ExtOp = SPIRVWORD_MAX;
4691 llvm::Function *F = CI->getCalledFunction();
4692 auto MangledName = F->getName();
4693 StringRef DemangledName;
4694
4695 if (MangledName.startswith(SPCV_CAST) || MangledName == SAMPLER_INIT)
4696 return oclTransSpvcCastSampler(CI, BB);
4697
4698 if (oclIsBuiltin(MangledName, DemangledName) ||
4699 isDecoratedSPIRVFunc(F, DemangledName)) {
4700 if (auto BV = transBuiltinToConstant(DemangledName, CI))
4701 return BV;
4702 if (auto BV = transBuiltinToInst(DemangledName, CI, BB))
4703 return BV;
4704 }
4705
4706 std::string DemangledNameInternal;
4707 if (isInternalSPIRVBuiltin(MangledName, DemangledNameInternal)) {
4708 // Logic of the code below is described in
4709 // docs/SPIRVMiniFloatsRepresentationInLLVM.rst
4710 // A quick recap of the document:
4711 // For FP4 and FP8 types (which don't have appropriate counterparts in LLVM)
4712 // the translator expect to see external function calls with __builtin_spirv
4713 // prefix, names of the functions encode the used in the conversion
4714 // FP types and will be used by the translator for proper TypeFloat values
4715 // generation. Since in LLVM IR FP8 types are represented by
4716 // integer type, we have to insert bitcasts for dependent values that expect
4717 // integer inputs or produces integer output that is used in the conversion.
4718 if (SPIRV::FPConvertToEncodingMap::find(DemangledNameInternal)) {
4719 FPConversionDesc FPDesc =
4720 SPIRV::FPConvertToEncodingMap::map(DemangledNameInternal);
4721 Value *Src = CI->getOperand(0);
4722 Type *LLVMSrcTy = Src->getType();
4723 Type *LLVMDstTy = CI->getType();
4724 SPIRVType *SrcTy = nullptr;
4725 SPIRVType *DstTy = nullptr;
4726
4727 auto GetScalarTy = [&](Type *Ty) -> Type * {
4728 if (isLLVMCooperativeMatrixType(Ty))
4729 return cast<TargetExtType>(Ty)->getTypeParameter(0);
4730 return Ty->getScalarType();
4731 };
4732
4733 // FP types representable in LLVM IR, no need for special handling
4734 // Also, int4 matrices remain the same.
4735 if (FPDesc.SrcEncoding == FPEncodingWrap::IEEE754 ||
4736 FPDesc.SrcEncoding == FPEncodingWrap::BF16 ||
4737 (FPDesc.SrcEncoding == FPEncodingWrap::Integer &&
4738 isLLVMCooperativeMatrixType(LLVMDstTy)))
4739 SrcTy = transType(LLVMSrcTy);
4740 if (FPDesc.DstEncoding == FPEncodingWrap::IEEE754 ||
4741 FPDesc.DstEncoding == FPEncodingWrap::BF16 ||
4742 (FPDesc.DstEncoding == FPEncodingWrap::Integer &&
4743 (isLLVMCooperativeMatrixType(LLVMDstTy) ||
4744 FPDesc.SrcEncoding == FPEncodingWrap::Integer)))
4745 DstTy = transType(LLVMDstTy);
4746
4747 SPIRVValue *SrcOp = transValue(Src, BB);
4748
4749 if (!SrcTy) {
4750 // Src type is 'mini' float or int4.
4751 unsigned SrcVecSize = 0;
4752 SrcTy = processMiniFPOrInt4Type(LLVMSrcTy, FPDesc.SrcEncoding,
4753 GetScalarTy, BM, SrcVecSize);
4754
4755 if (SrcVecSize > 0)
4756 SrcTy = BM->addVectorType(SrcTy, SrcVecSize);
4757
4758 if (isLLVMCooperativeMatrixType(LLVMSrcTy)) {
4759 // Create FP4/FP8 matrix with a new type and insert a bitcast.
4760 SrcTy = BM->addCooperativeMatrixKHRType(
4761 SrcTy,
4762 static_cast<SPIRVTypeCooperativeMatrixKHR *>(transType(LLVMSrcTy))
4763 ->getArgs());
4764 SrcOp = BM->addUnaryInst(OpBitcast, SrcTy, SrcOp, BB);
4765 } else if (FPDesc.SrcEncoding != FPEncodingWrap::Integer ||
4766 (SrcTy->isTypeVector() && !LLVMSrcTy->isVectorTy())) {
4767 // Create bitcast for FP4, FP8 and packed Int4.
4768 SrcOp = BM->addUnaryInst(OpBitcast, SrcTy, SrcOp, BB);
4769 }
4770 }
4771 if (!DstTy) {
4772 // Dst type is 'mini' float or int4.
4773 unsigned DstVecSize = 0;
4774 DstTy = processMiniFPOrInt4Type(LLVMDstTy, FPDesc.DstEncoding,
4775 GetScalarTy, BM, DstVecSize);
4776
4777 if (isLLVMCooperativeMatrixType(LLVMDstTy))
4778 // Create FP8 matrix with a new type.
4779 DstTy = BM->addCooperativeMatrixKHRType(
4780 DstTy,
4781 static_cast<SPIRVTypeCooperativeMatrixKHR *>(transType(LLVMDstTy))
4782 ->getArgs());
4783
4784 if (DstVecSize > 0)
4785 DstTy = BM->addVectorType(DstTy, DstVecSize);
4786 }
4787
4788 std::vector<SPIRVValue *> Ops = {SrcOp};
4789 const auto OC = static_cast<Op>(FPDesc.ConvOpCode);
4790
4791 // Translate operands for stochastic roundings.
4792 for (size_t I = 1; I != CI->arg_size(); ++I)
4793 Ops.push_back(transValue(CI->getOperand(I), BB));
4794
4795 SPIRVValue *Conv = BM->addInstTemplate(OC, BM->getIds(Ops), BB, DstTy);
4796
4797 // Representable in LLVM FP types: bitcast is not needed.
4798 if (FPDesc.DstEncoding == FPEncodingWrap::IEEE754 ||
4799 FPDesc.DstEncoding == FPEncodingWrap::BF16)
4800 return Conv;
4801 // Originally not-packed integer.
4802 if (FPDesc.DstEncoding == FPEncodingWrap::Integer &&
4803 (DstTy->isTypeVector() == LLVMDstTy->isVectorTy() ||
4804 isLLVMCooperativeMatrixType(LLVMDstTy)))
4805 return Conv;
4806 // Need to adjust types: create bitcast for FP8 and packed Int4.
4807 SPIRVValue *BitCast =
4808 BM->addUnaryInst(OpBitcast, transType(CI->getType()), Conv, BB);
4809 return BitCast;
4810 }
4811 }
4812
4813 SmallVector<std::string, 2> Dec;
4814 if (isBuiltinTransToExtInst(CI->getCalledFunction(), &ExtSetKind, &ExtOp,
4815 &Dec)) {
4816 if (const auto *FirstArg = F->getArg(0)) {
4817 const auto *Type = FirstArg->getType();
4818 if (Type->isBFloatTy())
4819 BM->addCapability(internal::CapabilityBFloat16ArithmeticINTEL);
4820 }
4821 if (DemangledName.find("__spirv_ocl_printf") != StringRef::npos) {
4822 auto *FormatStrPtr = cast<PointerType>(CI->getArgOperand(0)->getType());
4823 if (FormatStrPtr->getAddressSpace() !=
4824 SPIR::TypeAttributeEnum::ATTR_CONST) {
4825 if (!BM->isAllowedToUseExtension(
4826 ExtensionID::SPV_EXT_relaxed_printf_string_address_space)) {
4827 std::string ErrorStr =
4828 "Either SPV_EXT_relaxed_printf_string_address_space extension "
4829 "should be allowed to translate this module, because this LLVM "
4830 "module contains the printf function with format string, whose "
4831 "address space is not equal to 2 (constant).";
4832 getErrorLog().checkError(false, SPIRVEC_RequiresExtension, CI,
4833 ErrorStr);
4834 }
4835 BM->addExtension(
4836 ExtensionID::SPV_EXT_relaxed_printf_string_address_space);
4837 }
4838 } else if (DemangledName == "__spirv_ocl_fma") {
4839 if (BM->isAllowedToUseExtension(ExtensionID::SPV_KHR_fma))
4840 return BM->addInstTemplate(OpFmaKHR,
4841 BM->getIds(transValue(getArguments(CI), BB)),
4842 BB, transScavengedType(CI));
4843 }
4844
4845 return addDecorations(
4846 BM->addExtInst(
4847 transScavengedType(CI), BM->getExtInstSetId(ExtSetKind), ExtOp,
4848 transArguments(CI, BB,
4849 SPIRVEntry::createUnique(ExtSetKind, ExtOp).get()),
4850 BB),
4851 Dec);
4852 }
4853
4854 Function *Callee = CI->getCalledFunction();
4855 if (Callee->isDeclaration()) {
4856 SPIRVDBG(dbgs() << "[fp-contract] disabled for " << F->getName().str()
4857 << ": call to an undefined function " << *CI << '\n');
4858 joinFPContract(CI->getFunction(), FPContract::DISABLED);
4859 } else {
4860 FPContract CalleeFPC = getFPContract(Callee);
4861 joinFPContract(CI->getFunction(), CalleeFPC);
4862 if (CalleeFPC == FPContract::DISABLED) {
4863 SPIRVDBG(dbgs() << "[fp-contract] disabled for " << F->getName().str()
4864 << ": call to a function with disabled contraction: "
4865 << *CI << '\n');
4866 }
4867 }
4868
4869 return BM->addCallInst(
4870 transFunctionDecl(Callee),
4871 transArguments(CI, BB, SPIRVEntry::createUnique(OpFunctionCall).get()),
4872 BB);
4873 }
4874
4875 SPIRVValue *LLVMToSPIRVBase::transIndirectCallInst(CallInst *CI,
4876 SPIRVBasicBlock *BB) {
4877 if (BM->getErrorLog().checkError(
4878 BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_function_pointers),
4879 SPIRVEC_FunctionPointers, CI)) {
4880 return BM->addIndirectCallInst(
4881 transValue(CI->getCalledOperand(), BB), transScavengedType(CI),
4882 transArguments(CI, BB, SPIRVEntry::createUnique(OpFunctionCall).get()),
4883 BB);
4884 }
4885 return nullptr;
4886 }
4887
4888 SPIRVValue *LLVMToSPIRVBase::transAsmINTEL(InlineAsm *IA) {
4889 assert(IA);
4890
4891 // TODO: intention here is to provide information about actual target
4892 // but in fact spir-64 is substituted as triple when translator works
4893 // eventually we need to fix it (not urgent)
4894 StringRef TripleStr(M->getTargetTriple());
4895 auto AsmTarget = static_cast<SPIRVAsmTargetINTEL *>(
4896 BM->getOrAddAsmTargetINTEL(TripleStr.str()));
4897 auto SIA = BM->addAsmINTEL(
4898 static_cast<SPIRVTypeFunction *>(transType(IA->getFunctionType())),
4899 AsmTarget, IA->getAsmString(), IA->getConstraintString());
4900 if (IA->hasSideEffects())
4901 SIA->addDecorate(DecorationSideEffectsINTEL);
4902 return SIA;
4903 }
4904
4905 SPIRVValue *LLVMToSPIRVBase::transAsmCallINTEL(CallInst *CI,
4906 SPIRVBasicBlock *BB) {
4907 assert(CI);
4908 auto IA = cast<InlineAsm>(CI->getCalledOperand());
4909 return BM->addAsmCallINTELInst(
4910 static_cast<SPIRVAsmINTEL *>(transValue(IA, BB, false)),
4911 transArguments(CI, BB, SPIRVEntry::createUnique(OpAsmCallINTEL).get()),
4912 BB);
4913 }
4914
4915 bool LLVMToSPIRVBase::transAddressingMode() {
4916 Triple TargetTriple(M->getTargetTriple());
4917
4918 if (TargetTriple.isArch32Bit())
4919 BM->setAddressingModel(AddressingModelPhysical32);
4920 else
4921 BM->setAddressingModel(AddressingModelPhysical64);
4922 // Physical addressing model requires Addresses capability
4923 BM->addCapability(CapabilityAddresses);
4924 return true;
4925 }
4926 std::vector<SPIRVValue *>
4927 LLVMToSPIRVBase::transValue(const std::vector<Value *> &Args,
4928 SPIRVBasicBlock *BB) {
4929 std::vector<SPIRVValue *> BArgs;
4930 for (auto &I : Args)
4931 BArgs.push_back(transValue(I, BB));
4932 return BArgs;
4933 }
4934
4935 std::vector<SPIRVWord>
4936 LLVMToSPIRVBase::transValue(const std::vector<Value *> &Args,
4937 SPIRVBasicBlock *BB, SPIRVEntry *Entry) {
4938 std::vector<SPIRVWord> Operands;
4939 for (size_t I = 0, E = Args.size(); I != E; ++I) {
4940 Operands.push_back(Entry->isOperandLiteral(I)
4941 ? cast<ConstantInt>(Args[I])->getZExtValue()
4942 : transValue(Args[I], BB)->getId());
4943 }
4944 return Operands;
4945 }
4946
4947 std::vector<SPIRVWord> LLVMToSPIRVBase::transArguments(CallInst *CI,
4948 SPIRVBasicBlock *BB,
4949 SPIRVEntry *Entry) {
4950 return transValue(getArguments(CI), BB, Entry);
4951 }
4952
4953 SPIRVWord LLVMToSPIRVBase::transFunctionControlMask(Function *F) {
4954 SPIRVWord FCM = 0;
4955 SPIRSPIRVFuncCtlMaskMap::foreach (
4956 [&](Attribute::AttrKind Attr, SPIRVFunctionControlMaskKind Mask) {
4957 if (F->hasFnAttribute(Attr)) {
4958 if (Attr == Attribute::OptimizeNone) {
4959 if (BM->isAllowedToUseExtension(ExtensionID::SPV_EXT_optnone)) {
4960 BM->addExtension(ExtensionID::SPV_EXT_optnone);
4961 BM->addCapability(CapabilityOptNoneEXT);
4962 } else if (BM->isAllowedToUseExtension(
4963 ExtensionID::SPV_INTEL_optnone)) {
4964 BM->addExtension(ExtensionID::SPV_INTEL_optnone);
4965 BM->addCapability(CapabilityOptNoneINTEL);
4966 } else
4967 return;
4968 }
4969 FCM |= Mask;
4970 }
4971 });
4972 return FCM;
4973 }
4974
4975 void LLVMToSPIRVBase::transGlobalAnnotation(GlobalVariable *V) {
4976 SPIRVDBG(dbgs() << "[transGlobalAnnotation] " << *V << '\n');
4977
4978 // @llvm.global.annotations is an array that contains structs with 4 fields.
4979 // Get the array of structs with metadata
4980 // TODO: actually, now it contains 5 fields, the fifth by default is nullptr
4981 // or undef, but it can be defined to include variadic arguments of
4982 // clang::annotation attribute. Need to refactor this function to turn on this
4983 // translation
4984 ConstantArray *CA = cast<ConstantArray>(V->getOperand(0));
4985 for (Value *Op : CA->operands()) {
4986 ConstantStruct *CS = cast<ConstantStruct>(Op);
4987 // The first field of the struct contains a pointer to annotated variable
4988 Value *AnnotatedVar = CS->getOperand(0)->stripPointerCasts();
4989 SPIRVValue *SV = transValue(AnnotatedVar, nullptr);
4990
4991 // The second field contains a pointer to a global annotation string
4992 GlobalVariable *GV =
4993 cast<GlobalVariable>(CS->getOperand(1)->stripPointerCasts());
4994
4995 StringRef AnnotationString;
4996 if (!getConstantStringInfo(GV, AnnotationString)) {
4997 assert(!"Annotation string missing");
4998 return;
4999 }
5000 DecorationsInfoVec Decorations =
5001 tryParseAnnotationString(BM, AnnotationString).MemoryAttributesVec;
5002
5003 // If we didn't find any annotation decorations, let's add the whole
5004 // annotation string as UserSemantic Decoration
5005 if (Decorations.empty()) {
5006 SV->addDecorate(
5007 new SPIRVDecorateUserSemanticAttr(SV, AnnotationString.str()));
5008 } else {
5009 addAnnotationDecorations(SV, Decorations);
5010 }
5011 }
5012 }
5013
5014 void LLVMToSPIRVBase::transGlobalIOPipeStorage(GlobalVariable *V, MDNode *IO) {
5015 SPIRVDBG(dbgs() << "[transGlobalIOPipeStorage] " << *V << '\n');
5016 SPIRVValue *SV = transValue(V, nullptr);
5017 assert(SV && "Failed to process OCL PipeStorage object");
5018 if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_io_pipes)) {
5019 unsigned ID = getMDOperandAsInt(IO, 0);
5020 SV->addDecorate(DecorationIOPipeStorageINTEL, ID);
5021 }
5022 }
5023
5024 bool LLVMToSPIRVBase::transGlobalVariables() {
5025 for (auto I = M->global_begin(), E = M->global_end(); I != E; ++I) {
5026 if ((*I).getName() == "llvm.global.annotations")
5027 transGlobalAnnotation(&(*I));
5028 else if ([I]() -> bool {
5029 // Check if the GV is used only in var/ptr instructions. If yes -
5030 // skip processing of this since it's only an annotation GV.
5031 if (I->user_empty())
5032 return false;
5033 for (auto *U : I->users()) {
5034 Value *V = U;
5035 while (isa<BitCastInst>(V) || isa<AddrSpaceCastInst>(V))
5036 V = cast<CastInst>(V)->getOperand(0);
5037 auto *GEP = dyn_cast_or_null<GetElementPtrInst>(V);
5038 if (!GEP)
5039 return false;
5040 for (auto *GEPU : GEP->users()) {
5041 auto *II = dyn_cast<IntrinsicInst>(GEPU);
5042 if (!II)
5043 return false;
5044 switch (II->getIntrinsicID()) {
5045 case Intrinsic::var_annotation:
5046 case Intrinsic::ptr_annotation:
5047 continue;
5048 default:
5049 return false;
5050 }
5051 }
5052 }
5053 return true;
5054 }())
5055 continue;
5056 else if ((I->getName() == "llvm.global_ctors" ||
5057 I->getName() == "llvm.global_dtors") &&
5058 !BM->isAllowedToUseExtension(
5059 ExtensionID::SPV_INTEL_function_pointers)) {
5060 // Function pointers are required to represent structor lists; do not
5061 // translate the variable if function pointers are not available.
5062 continue;
5063 } else if (MDNode *IO = ((*I).getMetadata("io_pipe_id")))
5064 transGlobalIOPipeStorage(&(*I), IO);
5065 else if (!transValue(&(*I), nullptr))
5066 return false;
5067 }
5068 return true;
5069 }
5070
5071 bool LLVMToSPIRVBase::isAnyFunctionReachableFromFunction(
5072 const Function *FS,
5073 const std::unordered_set<const Function *> Funcs) const {
5074 std::unordered_set<const Function *> Done;
5075 std::unordered_set<const Function *> ToDo;
5076 ToDo.insert(FS);
5077
5078 while (!ToDo.empty()) {
5079 auto It = ToDo.begin();
5080 const Function *F = *It;
5081
5082 if (Funcs.find(F) != Funcs.end())
5083 return true;
5084
5085 ToDo.erase(It);
5086 Done.insert(F);
5087
5088 const CallGraphNode *FN = (*CG)[F];
5089 for (unsigned I = 0; I < FN->size(); ++I) {
5090 const CallGraphNode *NN = (*FN)[I];
5091 const Function *NNF = NN->getFunction();
5092 if (!NNF)
5093 continue;
5094 if (Done.find(NNF) == Done.end()) {
5095 ToDo.insert(NNF);
5096 }
5097 }
5098 }
5099
5100 return false;
5101 }
5102
5103 std::vector<SPIRVId>
5104 LLVMToSPIRVBase::collectEntryPointInterfaces(SPIRVFunction *SF, Function *F) {
5105 std::vector<SPIRVId> Interface;
5106 for (auto &GV : M->globals()) {
5107 const auto AS = GV.getAddressSpace();
5108 SPIRVModule *BM = SF->getModule();
5109 if (!BM->isAllowedToUseVersion(VersionNumber::SPIRV_1_4))
5110 if (AS != SPIRAS_Input && AS != SPIRAS_Output)
5111 continue;
5112
5113 std::unordered_set<const Function *> Funcs;
5114
5115 for (const auto &U : GV.uses()) {
5116 const Instruction *Inst = dyn_cast<Instruction>(U.getUser());
5117 if (!Inst)
5118 continue;
5119 Funcs.insert(Inst->getFunction());
5120 }
5121
5122 if (isAnyFunctionReachableFromFunction(F, Funcs)) {
5123 SPIRVWord ModuleVersion = static_cast<SPIRVWord>(BM->getSPIRVVersion());
5124 if (AS != SPIRAS_Input && AS != SPIRAS_Output &&
5125 ModuleVersion < static_cast<SPIRVWord>(VersionNumber::SPIRV_1_4))
5126 BM->setMinSPIRVVersion(VersionNumber::SPIRV_1_4);
5127 Interface.push_back(ValueMap[&GV]->getId());
5128 }
5129 }
5130 return Interface;
5131 }
5132
5133 void LLVMToSPIRVBase::mutateFuncArgType(
5134 const std::map<unsigned, Type *> &ChangedType, Function *F) {
5135 for (auto &I : ChangedType) {
5136 for (auto UI = F->user_begin(), UE = F->user_end(); UI != UE; ++UI) {
5137 auto Call = dyn_cast<CallInst>(*UI);
5138 if (!Call)
5139 continue;
5140 auto Arg = Call->getArgOperand(I.first);
5141 auto OrigTy = Arg->getType();
5142 if (OrigTy == I.second)
5143 continue;
5144 SPIRVDBG(dbgs() << "[mutate arg type] " << *Call << ", " << *Arg << '\n');
5145 auto CastF = M->getOrInsertFunction(SPCV_CAST, I.second, OrigTy);
5146 std::vector<Value *> Args;
5147 Args.push_back(Arg);
5148 auto Cast = CallInst::Create(CastF, Args, "", Call);
5149 Call->replaceUsesOfWith(Arg, Cast);
5150 SPIRVDBG(dbgs() << "[mutate arg type] -> " << *Cast << '\n');
5151 }
5152 }
5153 }
5154
5155 // Propagate contraction requirement of F up the call graph.
5156 void LLVMToSPIRVBase::fpContractUpdateRecursive(Function *F, FPContract FPC) {
5157 std::queue<User *> Users;
5158 for (User *FU : F->users()) {
5159 Users.push(FU);
5160 }
5161
5162 bool EnableLogger = FPC == FPContract::DISABLED && !Users.empty();
5163 if (EnableLogger) {
5164 SPIRVDBG(dbgs() << "[fp-contract] disabled for users of " << F->getName()
5165 << '\n');
5166 }
5167
5168 while (!Users.empty()) {
5169 User *U = Users.front();
5170 Users.pop();
5171
5172 if (EnableLogger) {
5173 SPIRVDBG(dbgs() << "[fp-contract] user: " << *U << '\n');
5174 }
5175
5176 // Move from an Instruction to its Function
5177 if (Instruction *I = dyn_cast<Instruction>(U)) {
5178 Users.push(I->getFunction());
5179 continue;
5180 }
5181
5182 if (Function *F = dyn_cast<Function>(U)) {
5183 if (!joinFPContract(F, FPC)) {
5184 // FP contract was not updated - no need to propagate
5185 // This also terminates a recursion (if any).
5186 if (EnableLogger) {
5187 SPIRVDBG(dbgs() << "[fp-contract] already disabled " << F->getName()
5188 << '\n');
5189 }
5190 continue;
5191 }
5192 if (EnableLogger) {
5193 SPIRVDBG(dbgs() << "[fp-contract] disabled for " << F->getName()
5194 << '\n');
5195 }
5196 for (User *FU : F->users()) {
5197 Users.push(FU);
5198 }
5199 continue;
5200 }
5201
5202 // Unwrap a constant until we reach an Instruction.
5203 // This is checked after the Function, because a Function is also a
5204 // Constant.
5205 if (Constant *C = dyn_cast<Constant>(U)) {
5206 for (User *CU : C->users()) {
5207 Users.push(CU);
5208 }
5209 continue;
5210 }
5211
5212 llvm_unreachable("Unexpected use.");
5213 }
5214 }
5215
5216 /// Returns a range that traverses \p F ensuring that dominator blocks are
5217 /// visited before the blocks they dominate.
5218 ///
5219 /// Compared to llvm::ReversePostOrderTraversal which also visits dominators
5220 /// before dominated blocks, this traversal aims to be more stable and will keep
5221 /// basic blocks in their original order as much as possible, only reordering
5222 /// them to visit dominators ahead of their dominated blocks when needed. \p DT
5223 /// is not copied by this function and needs to outlive any iterators created
5224 /// from this range.
5225 static auto stablePreDominatorTraversal(Function &F, const DominatorTree &DT) {
5226
5227 // A local iterator type for traversing a function in the desired order.
5228 class StablePreDominatorIterator
5229 : public iterator_facade_base<StablePreDominatorIterator,
5230 std::forward_iterator_tag, BasicBlock> {
5231
5232 // The passed DominatorTree; may be unset for end iterators.
5233 const DominatorTree *DT = nullptr;
5234
5235 // The set of basic blocks already visited in this traversal.
5236 SmallPtrSet<const BasicBlock *, 4> VisitedBBs;
5237
5238 // The next basic block in original function order, or nullptr if the
5239 // traversal is over.
5240 BasicBlock *NextBB = nullptr;
5241
5242 // The current basic block in the traversal, or nullptr for end iterators.
5243 BasicBlock *CurBB = nullptr;
5244
5245 // Returns the most immediate dominator of \p BB which does not have an
5246 // unvisited dominator and so can be visited in this traversal.
5247 BasicBlock *visitableDominator(BasicBlock *BB) const {
5248
5249 // Find BB's dominator; if there is none, BB can be visited immediately.
5250 const auto *const BBNode = DT->getNode(BB);
5251 if (!BBNode)
5252 return BB;
5253 const auto *const DomNode = BBNode->getIDom();
5254 if (!DomNode)
5255 return BB;
5256 BasicBlock *const Dominator = DomNode->getBlock();
5257
5258 // If the dominator's been visited, BB can now be visited.
5259 if (VisitedBBs.contains(Dominator))
5260 return BB;
5261
5262 // Otherwise, find the dominator's visitable dominator instead.
5263 return visitableDominator(Dominator);
5264 }
5265
5266 // Advances the iterator and returns the next basic block to be visited in
5267 // the traversal.
5268 BasicBlock *next() {
5269
5270 // If NextBB is nullptr, the end of the traversal has been reached.
5271 if (!NextBB)
5272 return nullptr;
5273
5274 // Check if NextBB has already been visited; if so, advance past it.
5275 if (VisitedBBs.contains(NextBB)) {
5276 NextBB = NextBB->getNextNode();
5277 return next();
5278 }
5279
5280 // If NextBB is unvisited, visit its next visitable dominator.
5281 BasicBlock *const ToVisit = visitableDominator(NextBB);
5282 VisitedBBs.insert(ToVisit);
5283 return ToVisit;
5284 }
5285
5286 public:
5287 // Constructs an end iterator.
5288 StablePreDominatorIterator() {}
5289
5290 // Constructs a begin iterator at the start of \p F.
5291 StablePreDominatorIterator(Function &F, const DominatorTree &DT)
5292 : DT(&DT), NextBB(&F.getEntryBlock()) {
5293 ++*this;
5294 }
5295
5296 // Methods required by iterator_facade_base.
5297 bool operator==(const StablePreDominatorIterator &Other) const {
5298 return CurBB == Other.CurBB;
5299 }
5300 BasicBlock &operator*() const { return *CurBB; }
5301 StablePreDominatorIterator &operator++() {
5302 CurBB = next();
5303 return *this;
5304 }
5305 };
5306
5307 return make_range(StablePreDominatorIterator(F, DT),
5308 StablePreDominatorIterator());
5309 }
5310
5311 void LLVMToSPIRVBase::transFunction(Function *I) {
5312 SPIRVFunction *BF = transFunctionDecl(I);
5313 // Creating all basic blocks before creating any instruction. SPIR-V requires
5314 // that blocks appear after their dominators, so stablePreDominatorTraversal
5315 // is used to ensure blocks are written in the right order.
5316 const DominatorTree DT(*I);
5317 for (BasicBlock &FI : stablePreDominatorTraversal(*I, DT)) {
5318 transValue(&FI, nullptr);
5319 }
5320 for (auto &FI : *I) {
5321 SPIRVBasicBlock *BB =
5322 static_cast<SPIRVBasicBlock *>(transValue(&FI, nullptr));
5323 for (auto &BI : FI) {
5324 transValue(&BI, BB, false);
5325 }
5326 }
5327 // Enable FP contraction unless proven otherwise
5328 joinFPContract(I, FPContract::ENABLED);
5329 fpContractUpdateRecursive(I, getFPContract(I));
5330
5331 if (isKernel(I)) {
5332 auto Interface = collectEntryPointInterfaces(BF, I);
5333 BM->addEntryPoint(ExecutionModelKernel, BF->getId(), BF->getName(),
5334 Interface);
5335 }
5336 }
5337
5338 bool isEmptyLLVMModule(Module *M) {
5339 return M->empty() && // No functions
5340 M->global_empty(); // No global variables
5341 }
5342
5343 bool LLVMToSPIRVBase::translate() {
5344 BM->setGeneratorVer(KTranslatorVer);
5345
5346 if (isEmptyLLVMModule(M))
5347 BM->addCapability(CapabilityLinkage);
5348
5349 if (!lowerBuiltinCallsToVariables(M))
5350 return false;
5351
5352 // Use the type scavenger to recover pointer element types.
5353 Scavenger = std::make_unique<SPIRVTypeScavenger>(*M);
5354
5355 if (!transSourceLanguage())
5356 return false;
5357 if (!transExtension())
5358 return false;
5359 if (!transBuiltinSet())
5360 return false;
5361 if (!transAddressingMode())
5362 return false;
5363 if (!transGlobalVariables())
5364 return false;
5365
5366 for (auto &F : *M) {
5367 auto FT = F.getFunctionType();
5368 std::map<unsigned, Type *> ChangedType;
5369 oclGetMutatedArgumentTypesByBuiltin(FT, ChangedType, &F);
5370 mutateFuncArgType(ChangedType, &F);
5371 }
5372
5373 // SPIR-V logical layout requires all function declarations go before
5374 // function definitions.
5375 std::vector<Function *> Decls, Defs;
5376 for (auto &F : *M) {
5377 if (isBuiltinTransToInst(&F) || isBuiltinTransToExtInst(&F) ||
5378 F.getName().startswith(SPCV_CAST) ||
5379 F.getName().startswith(LLVM_MEMCPY) ||
5380 F.getName().startswith(SAMPLER_INIT))
5381 continue;
5382 if (F.isDeclaration())
5383 Decls.push_back(&F);
5384 else
5385 Defs.push_back(&F);
5386 }
5387 for (auto I : Decls)
5388 transFunctionDecl(I);
5389 for (auto I : Defs)
5390 transFunction(I);
5391
5392 if (!transMetadata())
5393 return false;
5394 if (!transExecutionMode())
5395 return false;
5396
5397 BM->resolveUnknownStructFields();
5398 DbgTran->transDebugMetadata();
5399 return true;
5400 }
5401
5402 llvm::IntegerType *LLVMToSPIRVBase::getSizetType(unsigned AS) {
5403 return IntegerType::getIntNTy(M->getContext(),
5404 M->getDataLayout().getPointerSizeInBits(AS));
5405 }
5406
5407 void LLVMToSPIRVBase::oclGetMutatedArgumentTypesByBuiltin(
5408 llvm::FunctionType *FT, std::map<unsigned, Type *> &ChangedType,
5409 Function *F) {
5410 StringRef Demangled;
5411 if (!oclIsBuiltin(F->getName(), Demangled))
5412 return;
5413 // Note: kSPIRVName::ConvertHandleToSampledImageINTEL contains
5414 // kSPIRVName::SampledImage as a substring, but we still want to return in
5415 // this case.
5416 if (Demangled.find(kSPIRVName::SampledImage) == std::string::npos ||
5417 Demangled.find(kSPIRVName::ConvertHandleToSampledImageINTEL) !=
5418 std::string::npos)
5419 return;
5420 if (FT->getParamType(1)->isIntegerTy())
5421 ChangedType[1] = getSPIRVType(OpTypeSampler, true);
5422 }
5423
5424 SPIRVValue *LLVMToSPIRVBase::transBuiltinToConstant(StringRef DemangledName,
5425 CallInst *CI) {
5426 Op OC = getSPIRVFuncOC(DemangledName);
5427 if (!isSpecConstantOpCode(OC))
5428 return nullptr;
5429 if (OC == spv::OpSpecConstantComposite) {
5430 return BM->addSpecConstantComposite(transType(CI->getType()),
5431 transValue(getArguments(CI), nullptr));
5432 }
5433 Value *V = CI->getArgOperand(1);
5434 Type *Ty = CI->getType();
5435 assert(((Ty == V->getType()) ||
5436 // If bool is stored into memory, then clang will emit it as i8,
5437 // however for other usages of bool (like return type of a function),
5438 // it is emitted as i1.
5439 // Therefore, situation when we encounter
5440 // i1 _Z20__spirv_SpecConstant(i32, i8) is valid
5441 (Ty->isIntegerTy(1) && V->getType()->isIntegerTy(8))) &&
5442 "Type mismatch!");
5443 uint64_t Val = 0;
5444 if (Ty->isIntegerTy())
5445 Val = cast<ConstantInt>(V)->getZExtValue();
5446 else if (Ty->isFloatingPointTy())
5447 Val = cast<ConstantFP>(V)->getValueAPF().bitcastToAPInt().getZExtValue();
5448 else
5449 return nullptr;
5450 SPIRVValue *SC = BM->addSpecConstant(transType(Ty), Val);
5451 return SC;
5452 }
5453
5454 SPIRVInstruction *LLVMToSPIRVBase::transBuiltinToInst(StringRef DemangledName,
5455 CallInst *CI,
5456 SPIRVBasicBlock *BB) {
5457 SmallVector<std::string, 2> Dec;
5458 auto OC = getSPIRVFuncOC(DemangledName, &Dec);
5459
5460 if (OC == OpNop)
5461 return nullptr;
5462
5463 if (OpReadPipeBlockingINTEL <= OC && OC <= OpWritePipeBlockingINTEL &&
5464 !BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_blocking_pipes))
5465 return nullptr;
5466
5467 if (OpFixedSqrtINTEL <= OC && OC <= OpFixedExpINTEL)
5468 BM->getErrorLog().checkError(
5469 BM->isAllowedToUseExtension(
5470 ExtensionID::SPV_INTEL_arbitrary_precision_fixed_point),
5471 SPIRVEC_InvalidInstruction,
5472 CI->getCalledOperand()->getName().str() +
5473 "\nFixed point instructions can't be translated correctly without "
5474 "enabled SPV_INTEL_arbitrary_precision_fixed_point extension!\n");
5475
5476 if ((OpArbitraryFloatSinCosPiINTEL <= OC &&
5477 OC <= OpArbitraryFloatCastToIntINTEL) ||
5478 (OpArbitraryFloatAddINTEL <= OC && OC <= OpArbitraryFloatPowNINTEL))
5479 BM->getErrorLog().checkError(
5480 BM->isAllowedToUseExtension(
5481 ExtensionID::SPV_INTEL_arbitrary_precision_floating_point),
5482 SPIRVEC_InvalidInstruction,
5483 CI->getCalledOperand()->getName().str() +
5484 "\nFloating point instructions can't be translated correctly "
5485 "without enabled SPV_INTEL_arbitrary_precision_floating_point "
5486 "extension!\n");
5487
5488 auto Inst = transBuiltinToInstWithoutDecoration(OC, CI, BB);
5489 addDecorations(Inst, Dec);
5490 return Inst;
5491 }
5492
5493 bool LLVMToSPIRVBase::transExecutionMode() {
5494 if (auto NMD = SPIRVMDWalker(*M).getNamedMD(kSPIRVMD::ExecutionMode)) {
5495 while (!NMD.atEnd()) {
5496 unsigned EMode = ~0U;
5497 Function *F = nullptr;
5498 auto N = NMD.nextOp(); /* execution mode MDNode */
5499 N.get(F).get(EMode);
5500
5501 SPIRVFunction *BF = static_cast<SPIRVFunction *>(getTranslatedValue(F));
5502 assert(BF && "Invalid kernel function");
5503 if (!BF)
5504 return false;
5505
5506 auto AddSingleArgExecutionMode = [&](ExecutionMode EMode) {
5507 uint32_t Arg = ~0u;
5508 N.get(Arg);
5509 BF->addExecutionMode(
5510 BM->add(new SPIRVExecutionMode(OpExecutionMode, BF, EMode, Arg)));
5511 };
5512
5513 switch (EMode) {
5514 case spv::ExecutionModeContractionOff:
5515 BF->addExecutionMode(BM->add(new SPIRVExecutionMode(
5516 OpExecutionMode, BF, static_cast<ExecutionMode>(EMode))));
5517 break;
5518 case spv::ExecutionModeInitializer:
5519 case spv::ExecutionModeFinalizer:
5520 if (BM->isAllowedToUseVersion(VersionNumber::SPIRV_1_1)) {
5521 BF->addExecutionMode(BM->add(new SPIRVExecutionMode(
5522 OpExecutionMode, BF, static_cast<ExecutionMode>(EMode))));
5523 } else {
5524 getErrorLog().checkError(false, SPIRVEC_Requires1_1,
5525 "Initializer/Finalizer Execution Mode");
5526 return false;
5527 }
5528 break;
5529 case spv::ExecutionModeLocalSize:
5530 case spv::ExecutionModeLocalSizeHint: {
5531 unsigned X = 0, Y = 0, Z = 0;
5532 N.get(X).get(Y).get(Z);
5533 BF->addExecutionMode(BM->add(new SPIRVExecutionMode(
5534 OpExecutionMode, BF, static_cast<ExecutionMode>(EMode), X, Y, Z)));
5535 } break;
5536 case spv::ExecutionModeMaxWorkgroupSizeINTEL: {
5537 if (BM->isAllowedToUseExtension(
5538 ExtensionID::SPV_INTEL_kernel_attributes)) {
5539 unsigned X = 0, Y = 0, Z = 0;
5540 N.get(X).get(Y).get(Z);
5541 BF->addExecutionMode(BM->add(new SPIRVExecutionMode(
5542 OpExecutionMode, BF, static_cast<ExecutionMode>(EMode), X, Y,
5543 Z)));
5544 BM->addExtension(ExtensionID::SPV_INTEL_kernel_attributes);
5545 BM->addCapability(CapabilityKernelAttributesINTEL);
5546 }
5547 } break;
5548 case spv::ExecutionModeNoGlobalOffsetINTEL: {
5549 if (!BM->isAllowedToUseExtension(
5550 ExtensionID::SPV_INTEL_kernel_attributes))
5551 break;
5552 BF->addExecutionMode(BM->add(new SPIRVExecutionMode(
5553 OpExecutionMode, BF, static_cast<ExecutionMode>(EMode))));
5554 BM->addExtension(ExtensionID::SPV_INTEL_kernel_attributes);
5555 BM->addCapability(CapabilityKernelAttributesINTEL);
5556 } break;
5557 case spv::ExecutionModeVecTypeHint:
5558 case spv::ExecutionModeSubgroupSize:
5559 case spv::ExecutionModeSubgroupsPerWorkgroup:
5560 AddSingleArgExecutionMode(static_cast<ExecutionMode>(EMode));
5561 break;
5562 case spv::ExecutionModeNumSIMDWorkitemsINTEL:
5563 case spv::ExecutionModeSchedulerTargetFmaxMhzINTEL:
5564 case spv::ExecutionModeMaxWorkDimINTEL:
5565 case spv::ExecutionModeStreamingInterfaceINTEL: {
5566 if (!BM->isAllowedToUseExtension(
5567 ExtensionID::SPV_INTEL_kernel_attributes))
5568 break;
5569 AddSingleArgExecutionMode(static_cast<ExecutionMode>(EMode));
5570 BM->addExtension(ExtensionID::SPV_INTEL_kernel_attributes);
5571 BM->addCapability(CapabilityFPGAKernelAttributesINTEL);
5572 } break;
5573 case spv::ExecutionModeSharedLocalMemorySizeINTEL: {
5574 if (!BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_vector_compute))
5575 break;
5576 AddSingleArgExecutionMode(static_cast<ExecutionMode>(EMode));
5577 } break;
5578 case spv::ExecutionModeNamedBarrierCountINTEL: {
5579 if (!BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_vector_compute))
5580 break;
5581 unsigned NBarrierCnt = 0;
5582 N.get(NBarrierCnt);
5583 BF->addExecutionMode(BM->add(new SPIRVExecutionMode(
5584 OpExecutionMode, BF, static_cast<ExecutionMode>(EMode),
5585 NBarrierCnt)));
5586 BM->addExtension(ExtensionID::SPV_INTEL_vector_compute);
5587 BM->addCapability(CapabilityVectorComputeINTEL);
5588 } break;
5589
5590 case spv::ExecutionModeDenormPreserve:
5591 case spv::ExecutionModeDenormFlushToZero:
5592 case spv::ExecutionModeSignedZeroInfNanPreserve:
5593 case spv::ExecutionModeRoundingModeRTE:
5594 case spv::ExecutionModeRoundingModeRTZ: {
5595 if (BM->isAllowedToUseVersion(VersionNumber::SPIRV_1_4)) {
5596 BM->setMinSPIRVVersion(VersionNumber::SPIRV_1_4);
5597 AddSingleArgExecutionMode(static_cast<ExecutionMode>(EMode));
5598 } else if (BM->isAllowedToUseExtension(
5599 ExtensionID::SPV_KHR_float_controls)) {
5600 BM->addExtension(ExtensionID::SPV_KHR_float_controls);
5601 AddSingleArgExecutionMode(static_cast<ExecutionMode>(EMode));
5602 }
5603 } break;
5604 case spv::ExecutionModeRoundingModeRTPINTEL:
5605 case spv::ExecutionModeRoundingModeRTNINTEL:
5606 case spv::ExecutionModeFloatingPointModeALTINTEL:
5607 case spv::ExecutionModeFloatingPointModeIEEEINTEL: {
5608 if (!BM->isAllowedToUseExtension(
5609 ExtensionID::SPV_INTEL_float_controls2))
5610 break;
5611 AddSingleArgExecutionMode(static_cast<ExecutionMode>(EMode));
5612 } break;
5613 default:
5614 llvm_unreachable("invalid execution mode");
5615 }
5616 }
5617 }
5618
5619 transFPContract();
5620
5621 return true;
5622 }
5623
5624 void LLVMToSPIRVBase::transFPContract() {
5625 FPContractMode Mode = BM->getFPContractMode();
5626
5627 for (Function &F : *M) {
5628 SPIRVValue *TranslatedF = getTranslatedValue(&F);
5629 if (!TranslatedF) {
5630 continue;
5631 }
5632 SPIRVFunction *BF = static_cast<SPIRVFunction *>(TranslatedF);
5633
5634 bool IsKernelEntryPoint =
5635 BF->getModule()->isEntryPoint(spv::ExecutionModelKernel, BF->getId());
5636 if (!IsKernelEntryPoint)
5637 continue;
5638
5639 FPContract FPC = getFPContract(&F);
5640 assert(FPC != FPContract::UNDEF);
5641
5642 bool DisableContraction = false;
5643 switch (Mode) {
5644 case FPContractMode::Fast:
5645 DisableContraction = false;
5646 break;
5647 case FPContractMode::On:
5648 DisableContraction = FPC == FPContract::DISABLED;
5649 break;
5650 case FPContractMode::Off:
5651 DisableContraction = true;
5652 break;
5653 }
5654
5655 if (DisableContraction) {
5656 BF->addExecutionMode(BF->getModule()->add(new SPIRVExecutionMode(
5657 OpExecutionMode, BF, spv::ExecutionModeContractionOff)));
5658 }
5659 }
5660 }
5661
5662 bool LLVMToSPIRVBase::transMetadata() {
5663 if (!transOCLMetadata())
5664 return false;
5665
5666 auto Model = getMemoryModel(*M);
5667 if (Model != SPIRVMemoryModelKind::MemoryModelMax)
5668 BM->setMemoryModel(static_cast<SPIRVMemoryModelKind>(Model));
5669
5670 return true;
5671 }
5672
5673 // Work around to translate kernel_arg_type and kernel_arg_type_qual metadata
5674 static void transKernelArgTypeMD(SPIRVModule *BM, Function *F, MDNode *MD,
5675 std::string MDName) {
5676 std::string Prefix = kSPIRVName::EntrypointPrefix;
5677 std::string Name = F->getName().str().substr(Prefix.size());
5678 std::string KernelArgTypesMDStr = std::string(MDName) + "." + Name + ".";
5679 for (const auto &TyOp : MD->operands())
5680 KernelArgTypesMDStr += cast<MDString>(TyOp)->getString().str() + ",";
5681 BM->getString(KernelArgTypesMDStr);
5682 }
5683
5684 bool LLVMToSPIRVBase::transOCLMetadata() {
5685 for (auto &F : *M) {
5686 if (F.getCallingConv() != CallingConv::SPIR_KERNEL)
5687 continue;
5688
5689 SPIRVFunction *BF = static_cast<SPIRVFunction *>(getTranslatedValue(&F));
5690 assert(BF && "Kernel function should be translated first");
5691
5692 // Create 'OpString' as a workaround to store information about
5693 // *orignal* (typedef'ed, unsigned integers) type names of kernel arguments.
5694 // OpString "kernel_arg_type.%kernel_name%.typename0,typename1,..."
5695 if (auto *KernelArgType = F.getMetadata(SPIR_MD_KERNEL_ARG_TYPE))
5696 if (BM->shouldPreserveOCLKernelArgTypeMetadataThroughString())
5697 transKernelArgTypeMD(BM, &F, KernelArgType, SPIR_MD_KERNEL_ARG_TYPE);
5698
5699 if (auto *KernelArgTypeQual = F.getMetadata(SPIR_MD_KERNEL_ARG_TYPE_QUAL)) {
5700 foreachKernelArgMD(
5701 KernelArgTypeQual, BF,
5702 [](const std::string &Str, SPIRVFunctionParameter *BA) {
5703 if (Str.find("volatile") != std::string::npos)
5704 BA->addDecorate(new SPIRVDecorate(DecorationVolatile, BA));
5705 if (Str.find("restrict") != std::string::npos)
5706 BA->addDecorate(
5707 new SPIRVDecorate(DecorationFuncParamAttr, BA,
5708 FunctionParameterAttributeNoAlias));
5709 });
5710 // Create 'OpString' as a workaround to store information about
5711 // constant qualifiers of pointer kernel arguments. Store empty string
5712 // for a non constant parameter.
5713 // OpString "kernel_arg_type_qual.%kernel_name%.qual0,qual1,..."
5714 if (BM->shouldPreserveOCLKernelArgTypeMetadataThroughString())
5715 transKernelArgTypeMD(BM, &F, KernelArgTypeQual,
5716 SPIR_MD_KERNEL_ARG_TYPE_QUAL);
5717 }
5718 if (auto *KernelArgName = F.getMetadata(SPIR_MD_KERNEL_ARG_NAME)) {
5719 foreachKernelArgMD(
5720 KernelArgName, BF,
5721 [=](const std::string &Str, SPIRVFunctionParameter *BA) {
5722 BM->setName(BA, Str);
5723 });
5724 }
5725 if (auto *KernArgDecoMD = F.getMetadata(SPIRV_MD_PARAMETER_DECORATIONS))
5726 foreachKernelArgMD(KernArgDecoMD, BF, transMetadataDecorations);
5727 }
5728 return true;
5729 }
5730
5731 bool LLVMToSPIRVBase::transSourceLanguage() {
5732 auto Src = getSPIRVSource(M);
5733 SrcLang = std::get<0>(Src);
5734 SrcLangVer = std::get<1>(Src);
5735 BM->setSourceLanguage(static_cast<SourceLanguage>(SrcLang), SrcLangVer);
5736 return true;
5737 }
5738
5739 bool LLVMToSPIRVBase::transExtension() {
5740 if (auto N = SPIRVMDWalker(*M).getNamedMD(kSPIRVMD::Extension)) {
5741 while (!N.atEnd()) {
5742 std::string S;
5743 N.nextOp().get(S);
5744 assert(!S.empty() && "Invalid extension");
5745 BM->getExtension().insert(S);
5746 }
5747 }
5748 if (auto N = SPIRVMDWalker(*M).getNamedMD(kSPIRVMD::SourceExtension)) {
5749 while (!N.atEnd()) {
5750 std::string S;
5751 N.nextOp().get(S);
5752 assert(!S.empty() && "Invalid extension");
5753 BM->getSourceExtension().insert(S);
5754 }
5755 }
5756 for (auto &I :
5757 map<SPIRVCapabilityKind>(rmap<OclExt::Kind>(BM->getExtension())))
5758 BM->addCapability(I);
5759
5760 return true;
5761 }
5762
5763 void LLVMToSPIRVBase::dumpUsers(Value *V) {
5764 SPIRVDBG(dbgs() << "Users of " << *V << " :\n");
5765 for (auto UI = V->user_begin(), UE = V->user_end(); UI != UE; ++UI)
5766 SPIRVDBG(dbgs() << " " << **UI << '\n');
5767 }
5768
5769 Op LLVMToSPIRVBase::transBoolOpCode(SPIRVValue *Opn, Op OC) {
5770 if (!Opn->getType()->isTypeVectorOrScalarBool())
5771 return OC;
5772 IntBoolOpMap::find(OC, &OC);
5773 return OC;
5774 }
5775
5776 SPIRVInstruction *
5777 LLVMToSPIRVBase::transBuiltinToInstWithoutDecoration(Op OC, CallInst *CI,
5778 SPIRVBasicBlock *BB) {
5779 // We should do this replacement only for SPIR-V 1.5, as OpLessOrGreater is
5780 // deprecated there. However we do such replacement for the usual pipeline
5781 // (not via SPIR-V friendly calls) without minding the version, so we can do
5782 // such thing here as well.
5783 if (OC == OpLessOrGreater &&
5784 BM->isAllowedToUseVersion(VersionNumber::SPIRV_1_5))
5785 OC = OpFOrdNotEqual;
5786
5787 if (isGroupOpCode(OC))
5788 BM->addCapability(CapabilityGroups);
5789 switch (OC) {
5790 case OpControlBarrier: {
5791 auto BArgs = transValue(getArguments(CI), BB);
5792 return BM->addControlBarrierInst(BArgs[0], BArgs[1], BArgs[2], BB);
5793 } break;
5794 case OpGroupAsyncCopy: {
5795 auto BArgs = transValue(getArguments(CI), BB);
5796 return BM->addAsyncGroupCopy(BArgs[0], BArgs[1], BArgs[2], BArgs[3],
5797 BArgs[4], BArgs[5], BB);
5798 } break;
5799 case OpVectorExtractDynamic: {
5800 auto BArgs = transValue(getArguments(CI), BB);
5801 return BM->addVectorExtractDynamicInst(BArgs[0], BArgs[1], BB);
5802 } break;
5803 case OpVectorInsertDynamic: {
5804 auto BArgs = transValue(getArguments(CI), BB);
5805 return BM->addVectorInsertDynamicInst(BArgs[0], BArgs[1], BArgs[2], BB);
5806 } break;
5807 case OpSampledImage: {
5808 // Clang can generate SPIRV-friendly call for OpSampledImage instruction,
5809 // i.e. __spirv_SampledImage... But it can't generate correct return type
5810 // for this call, because there is no support for type corresponding to
5811 // OpTypeSampledImage. So, in this case, we create the required type here.
5812 Value *Image = CI->getArgOperand(0);
5813 Type *SampledImgTy =
5814 adjustImageType(getCallValueType(CI, 0), kSPIRVTypeName::Image,
5815 kSPIRVTypeName::SampledImg);
5816 Value *Sampler = CI->getArgOperand(1);
5817 return BM->addSampledImageInst(transType(SampledImgTy),
5818 transValue(Image, BB),
5819 transValue(Sampler, BB), BB);
5820 }
5821 case OpFixedSqrtINTEL:
5822 case OpFixedRecipINTEL:
5823 case OpFixedRsqrtINTEL:
5824 case OpFixedSinINTEL:
5825 case OpFixedCosINTEL:
5826 case OpFixedSinCosINTEL:
5827 case OpFixedSinPiINTEL:
5828 case OpFixedCosPiINTEL:
5829 case OpFixedSinCosPiINTEL:
5830 case OpFixedLogINTEL:
5831 case OpFixedExpINTEL: {
5832 // LLVM fixed point functions return value:
5833 // iN (arbitrary precision integer of N bits length)
5834 // Arguments:
5835 // A(iN), S(i1), I(i32), rI(i32), Quantization(i32), Overflow(i32)
5836 // where A - integer input of any width.
5837
5838 // SPIR-V fixed point instruction contains:
5839 // <id>ResTy Res<id> In<id> \
5840 // Literal S Literal I Literal rI Literal Q Literal O
5841
5842 Type *ResTy = CI->getType();
5843
5844 auto OpItr = CI->value_op_begin();
5845 auto OpEnd = OpItr + CI->arg_size();
5846
5847 // If the return type of an instruction is wider than 64-bit, then this
5848 // instruction will return via 'sret' argument added into the arguments
5849 // list. Here we reverse this, removing 'sret' argument and restoring
5850 // the original return type.
5851 if (CI->hasStructRetAttr()) {
5852 assert(ResTy->isVoidTy() && "Return type is not void");
5853 ResTy = CI->getParamStructRetType(0);
5854 OpItr++;
5855 }
5856
5857 // Input - integer input of any width or 'byval' pointer to this integer
5858 SPIRVValue *Input = transValue(*OpItr, BB);
5859 if (OpItr->getType()->isPointerTy())
5860 Input = BM->addLoadInst(Input, {}, BB);
5861 OpItr++;
5862
5863 std::vector<SPIRVWord> Literals;
5864 std::transform(OpItr, OpEnd, std::back_inserter(Literals), [](auto *O) {
5865 return cast<llvm::ConstantInt>(O)->getZExtValue();
5866 });
5867
5868 auto *APIntInst =
5869 BM->addFixedPointIntelInst(OC, transType(ResTy), Input, Literals, BB);
5870 if (!CI->hasStructRetAttr())
5871 return APIntInst;
5872 return BM->addStoreInst(transValue(CI->getArgOperand(0), BB), APIntInst, {},
5873 BB);
5874 }
5875 case OpArbitraryFloatCastINTEL:
5876 case OpArbitraryFloatCastFromIntINTEL:
5877 case OpArbitraryFloatCastToIntINTEL:
5878 case OpArbitraryFloatRecipINTEL:
5879 case OpArbitraryFloatRSqrtINTEL:
5880 case OpArbitraryFloatCbrtINTEL:
5881 case OpArbitraryFloatSqrtINTEL:
5882 case OpArbitraryFloatLogINTEL:
5883 case OpArbitraryFloatLog2INTEL:
5884 case OpArbitraryFloatLog10INTEL:
5885 case OpArbitraryFloatLog1pINTEL:
5886 case OpArbitraryFloatExpINTEL:
5887 case OpArbitraryFloatExp2INTEL:
5888 case OpArbitraryFloatExp10INTEL:
5889 case OpArbitraryFloatExpm1INTEL:
5890 case OpArbitraryFloatSinINTEL:
5891 case OpArbitraryFloatCosINTEL:
5892 case OpArbitraryFloatSinCosINTEL:
5893 case OpArbitraryFloatSinPiINTEL:
5894 case OpArbitraryFloatCosPiINTEL:
5895 case OpArbitraryFloatSinCosPiINTEL:
5896 case OpArbitraryFloatASinINTEL:
5897 case OpArbitraryFloatASinPiINTEL:
5898 case OpArbitraryFloatACosINTEL:
5899 case OpArbitraryFloatACosPiINTEL:
5900 case OpArbitraryFloatATanINTEL:
5901 case OpArbitraryFloatATanPiINTEL: {
5902 // Format of instruction CastFromInt:
5903 // LLVM arbitrary floating point functions return value type:
5904 // iN (arbitrary precision integer of N bits length)
5905 // Arguments: A(iN), Mout(i32), FromSign(bool), EnableSubnormals(i32),
5906 // RoundingMode(i32), RoundingAccuracy(i32)
5907 // where A and return values are of arbitrary precision integer type.
5908 // SPIR-V arbitrary floating point instruction layout:
5909 // <id>ResTy Res<id> A<id> Literal Mout Literal FromSign
5910 // Literal EnableSubnormals Literal RoundingMode
5911 // Literal RoundingAccuracy
5912
5913 // Format of instruction CastToInt:
5914 // LLVM arbitrary floating point functions return value: iN
5915 // Arguments: A(iN), MA(i32), ToSign(bool), EnableSubnormals(i32),
5916 // RoundingMode(i32), RoundingAccuracy(i32)
5917 // where A and return values are of arbitrary precision integer type.
5918 // SPIR-V arbitrary floating point instruction layout:
5919 // <id>ResTy Res<id> A<id> Literal MA Literal ToSign
5920 // Literal EnableSubnormals Literal RoundingMode
5921 // Literal RoundingAccuracy
5922
5923 // Format of other instructions:
5924 // LLVM arbitrary floating point functions return value: iN
5925 // Arguments: A(iN), MA(i32), Mout(i32), EnableSubnormals(i32),
5926 // RoundingMode(i32), RoundingAccuracy(i32)
5927 // where A and return values are of arbitrary precision integer type.
5928 // SPIR-V arbitrary floating point instruction layout:
5929 // <id>ResTy Res<id> A<id> Literal MA Literal Mout
5930 // Literal EnableSubnormals Literal RoundingMode
5931 // Literal RoundingAccuracy
5932
5933 Type *ResTy = CI->getType();
5934
5935 auto OpItr = CI->value_op_begin();
5936 auto OpEnd = OpItr + CI->arg_size();
5937
5938 // If the return type of an instruction is wider than 64-bit, then this
5939 // instruction will return via 'sret' argument added into the arguments
5940 // list. Here we reverse this, removing 'sret' argument and restoring
5941 // the original return type.
5942 if (CI->hasStructRetAttr()) {
5943 assert(ResTy->isVoidTy() && "Return type is not void");
5944 ResTy = CI->getParamStructRetType(0);
5945 OpItr++;
5946 }
5947
5948 // Input - integer input of any width or 'byval' pointer to this integer
5949 SPIRVValue *Input = transValue(*OpItr, BB);
5950 if (OpItr->getType()->isPointerTy())
5951 Input = BM->addLoadInst(Input, {}, BB);
5952 OpItr++;
5953
5954 std::vector<SPIRVWord> Literals;
5955 std::transform(OpItr, OpEnd, std::back_inserter(Literals), [](auto *O) {
5956 return cast<llvm::ConstantInt>(O)->getZExtValue();
5957 });
5958
5959 auto *APIntInst = BM->addArbFloatPointIntelInst(OC, transType(ResTy), Input,
5960 nullptr, Literals, BB);
5961 if (!CI->hasStructRetAttr())
5962 return APIntInst;
5963 return BM->addStoreInst(transValue(CI->getArgOperand(0), BB), APIntInst, {},
5964 BB);
5965 }
5966 case OpArbitraryFloatAddINTEL:
5967 case OpArbitraryFloatSubINTEL:
5968 case OpArbitraryFloatMulINTEL:
5969 case OpArbitraryFloatDivINTEL:
5970 case OpArbitraryFloatGTINTEL:
5971 case OpArbitraryFloatGEINTEL:
5972 case OpArbitraryFloatLTINTEL:
5973 case OpArbitraryFloatLEINTEL:
5974 case OpArbitraryFloatEQINTEL:
5975 case OpArbitraryFloatHypotINTEL:
5976 case OpArbitraryFloatATan2INTEL:
5977 case OpArbitraryFloatPowINTEL:
5978 case OpArbitraryFloatPowRINTEL:
5979 case OpArbitraryFloatPowNINTEL: {
5980 // Format of instructions Add, Sub, Mul, Div, Hypot, ATan2, Pow, PowR:
5981 // LLVM arbitrary floating point functions return value:
5982 // iN (arbitrary precision integer of N bits length)
5983 // Arguments: A(iN), MA(i32), B(iN), MB(i32), Mout(i32),
5984 // EnableSubnormals(i32), RoundingMode(i32),
5985 // RoundingAccuracy(i32)
5986 // where A, B and return values are of arbitrary precision integer type.
5987 // SPIR-V arbitrary floating point instruction layout:
5988 // <id>ResTy Res<id> A<id> Literal MA B<id> Literal MB Literal Mout
5989 // Literal EnableSubnormals Literal RoundingMode
5990 // Literal RoundingAccuracy
5991
5992 // Format of instruction PowN:
5993 // LLVM arbitrary floating point functions return value: iN
5994 // Arguments: A(iN), MA(i32), B(iN), SignOfB(i1), Mout(i32),
5995 // EnableSubnormals(i32), RoundingMode(i32),
5996 // RoundingAccuracy(i32)
5997 // where A, B and return values are of arbitrary precision integer type.
5998 // SPIR-V arbitrary floating point instruction layout:
5999 // <id>ResTy Res<id> A<id> Literal MA B<id> Literal SignOfB Literal Mout
6000 // Literal EnableSubnormals Literal RoundingMode
6001 // Literal RoundingAccuracy
6002
6003 // Format of instructions GT, GE, LT, LE, EQ:
6004 // LLVM arbitrary floating point functions return value: Bool
6005 // Arguments: A(iN), MA(i32), B(iN), MB(i32)
6006 // where A and B are of arbitrary precision integer type.
6007 // SPIR-V arbitrary floating point instruction layout:
6008 // <id>ResTy Res<id> A<id> Literal MA B<id> Literal MB
6009
6010 Type *ResTy = CI->getType();
6011
6012 auto OpItr = CI->value_op_begin();
6013 auto OpEnd = OpItr + CI->arg_size();
6014
6015 // If the return type of an instruction is wider than 64-bit, then this
6016 // instruction will return via 'sret' argument added into the arguments
6017 // list. Here we reverse this, removing 'sret' argument and restoring
6018 // the original return type.
6019 if (CI->hasStructRetAttr()) {
6020 assert(ResTy->isVoidTy() && "Return type is not void");
6021 ResTy = CI->getParamStructRetType(0);
6022 OpItr++;
6023 }
6024
6025 // InA - integer input of any width or 'byval' pointer to this integer
6026 SPIRVValue *InA = transValue(*OpItr, BB);
6027 if (OpItr->getType()->isPointerTy())
6028 InA = BM->addLoadInst(InA, {}, BB);
6029 OpItr++;
6030
6031 std::vector<SPIRVWord> Literals;
6032 Literals.push_back(cast<llvm::ConstantInt>(*OpItr++)->getZExtValue());
6033
6034 // InB - integer input of any width or 'byval' pointer to this integer
6035 SPIRVValue *InB = transValue(*OpItr, BB);
6036 if (OpItr->getType()->isPointerTy()) {
6037 std::vector<SPIRVWord> Mem;
6038 InB = BM->addLoadInst(InB, Mem, BB);
6039 }
6040 OpItr++;
6041
6042 std::transform(OpItr, OpEnd, std::back_inserter(Literals), [](auto *O) {
6043 return cast<llvm::ConstantInt>(O)->getZExtValue();
6044 });
6045
6046 auto *APIntInst = BM->addArbFloatPointIntelInst(OC, transType(ResTy), InA,
6047 InB, Literals, BB);
6048 if (!CI->hasStructRetAttr())
6049 return APIntInst;
6050 return BM->addStoreInst(transValue(CI->getArgOperand(0), BB), APIntInst, {},
6051 BB);
6052 }
6053 case OpLoad: {
6054 std::vector<SPIRVWord> MemoryAccess;
6055 assert(CI->arg_size() > 0 && "Expected at least 1 operand for OpLoad call");
6056 for (size_t I = 1; I < CI->arg_size(); ++I)
6057 MemoryAccess.push_back(
6058 cast<ConstantInt>(CI->getArgOperand(I))->getZExtValue());
6059 return BM->addLoadInst(transValue(CI->getArgOperand(0), BB), MemoryAccess,
6060 BB);
6061 }
6062 case OpStore: {
6063 std::vector<SPIRVWord> MemoryAccess;
6064 assert(CI->arg_size() > 1 &&
6065 "Expected at least 2 operands for OpStore call");
6066 for (size_t I = 2; I < CI->arg_size(); ++I)
6067 MemoryAccess.push_back(
6068 cast<ConstantInt>(CI->getArgOperand(I))->getZExtValue());
6069 return BM->addStoreInst(transValue(CI->getArgOperand(0), BB),
6070 transValue(CI->getArgOperand(1), BB), MemoryAccess,
6071 BB);
6072 }
6073 case OpCompositeConstruct: {
6074 std::vector<SPIRVId> Operands = {
6075 transValue(CI->getArgOperand(0), BB)->getId()};
6076 return BM->addCompositeConstructInst(transType(CI->getType()), Operands,
6077 BB);
6078 }
6079 case OpIAddCarry:
6080 case OpISubBorrow:
6081 case OpUMulExtended:
6082 case OpSMulExtended: {
6083 Function *F = CI->getCalledFunction();
6084 StructType *St = cast<StructType>(F->getParamStructRetType(0));
6085 SPIRVValue *V = BM->addBinaryInst(OC, transType(St),
6086 transValue(CI->getArgOperand(1), BB),
6087 transValue(CI->getArgOperand(2), BB), BB);
6088 return BM->addStoreInst(transValue(CI->getArgOperand(0), BB), V, {}, BB);
6089 }
6090 case OpCooperativeMatrixLengthKHR: {
6091 return BM->addCooperativeMatrixLengthKHRInst(
6092 transScavengedType(CI), transType(CI->getArgOperand(0)->getType()), BB);
6093 }
6094 default: {
6095 if (isCvtOpCode(OC) && OC != OpGenericCastToPtrExplicit) {
6096 return BM->addUnaryInst(OC, transType(CI->getType()),
6097 transValue(CI->getArgOperand(0), BB), BB);
6098 } else if (isCmpOpCode(OC) || isUnaryPredicateOpCode(OC)) {
6099 auto ResultTy = CI->getType();
6100 Type *BoolTy = IntegerType::getInt1Ty(M->getContext());
6101 auto IsVector = ResultTy->isVectorTy();
6102 if (IsVector)
6103 BoolTy = FixedVectorType::get(
6104 BoolTy, cast<FixedVectorType>(ResultTy)->getNumElements());
6105 auto BBT = transType(BoolTy);
6106 SPIRVInstruction *Res;
6107 if (isCmpOpCode(OC)) {
6108 assert(CI && CI->arg_size() == 2 && "Invalid call inst");
6109 Res = BM->addCmpInst(OC, BBT, transValue(CI->getArgOperand(0), BB),
6110 transValue(CI->getArgOperand(1), BB), BB);
6111 } else {
6112 assert(CI && CI->arg_size() == 1 && "Invalid call inst");
6113 Res =
6114 BM->addUnaryInst(OC, BBT, transValue(CI->getArgOperand(0), BB), BB);
6115 }
6116 // OpenCL C and OpenCL C++ built-ins may have different return type
6117 if (ResultTy == BoolTy)
6118 return Res;
6119 assert(IsVector || (!IsVector && ResultTy->isIntegerTy(32)));
6120 auto Zero = transValue(Constant::getNullValue(ResultTy), BB);
6121 auto One = transValue(
6122 IsVector ? Constant::getAllOnesValue(ResultTy) : getInt32(M, 1), BB);
6123 return BM->addSelectInst(Res, One, Zero, BB);
6124 } else if (isBinaryOpCode(OC)) {
6125 assert(CI && CI->arg_size() == 2 && "Invalid call inst");
6126 return BM->addBinaryInst(OC, transType(CI->getType()),
6127 transValue(CI->getArgOperand(0), BB),
6128 transValue(CI->getArgOperand(1), BB), BB);
6129 } else if (CI->arg_size() == 1 && !CI->getType()->isVoidTy() &&
6130 !hasExecScope(OC) && !isAtomicOpCode(OC)) {
6131 return BM->addUnaryInst(OC, transType(CI->getType()),
6132 transValue(CI->getArgOperand(0), BB), BB);
6133 } else {
6134 auto Args = getArguments(CI);
6135 SPIRVType *SPRetTy = nullptr;
6136 Type *RetTy = CI->getType();
6137 auto F = CI->getCalledFunction();
6138 if (!RetTy->isVoidTy()) {
6139 SPRetTy = transScavengedType(CI);
6140 } else if (Args.size() > 0 && F->arg_begin()->hasStructRetAttr()) {
6141 SPRetTy = transType(F->getParamStructRetType(0));
6142 Args.erase(Args.begin());
6143 }
6144 auto *SPI = SPIRVInstTemplateBase::create(OC);
6145 std::vector<SPIRVWord> SPArgs;
6146 for (size_t I = 0, E = Args.size(); I != E; ++I) {
6147 if (Args[I]->getType()->isPointerTy()) {
6148 Value *Pointee = Args[I]->stripPointerCasts();
6149 (void)Pointee;
6150 assert((Pointee == Args[I] || !isa<Function>(Pointee)) &&
6151 "Illegal use of a function pointer type");
6152 }
6153 SPArgs.push_back(SPI->isOperandLiteral(I)
6154 ? cast<ConstantInt>(Args[I])->getZExtValue()
6155 : transValue(Args[I], BB)->getId());
6156 }
6157 BM->addInstTemplate(SPI, SPArgs, BB, SPRetTy);
6158 if (!SPRetTy || !SPRetTy->isTypeStruct())
6159 return SPI;
6160 std::vector<SPIRVWord> Mem;
6161 SPIRVDBG(spvdbgs() << *SPI << '\n');
6162 return BM->addStoreInst(transValue(CI->getArgOperand(0), BB), SPI, Mem,
6163 BB);
6164 }
6165 }
6166 }
6167 return nullptr;
6168 }
6169
6170 SPIRV::SPIRVLinkageTypeKind
6171 LLVMToSPIRVBase::transLinkageType(const GlobalValue *GV) {
6172 if (GV->isDeclarationForLinker())
6173 return SPIRVLinkageTypeKind::LinkageTypeImport;
6174 if (GV->hasInternalLinkage() || GV->hasPrivateLinkage())
6175 return spv::internal::LinkageTypeInternal;
6176 if (GV->hasLinkOnceODRLinkage())
6177 if (BM->isAllowedToUseExtension(ExtensionID::SPV_KHR_linkonce_odr))
6178 return SPIRVLinkageTypeKind::LinkageTypeLinkOnceODR;
6179 return SPIRVLinkageTypeKind::LinkageTypeExport;
6180 }
6181
6182 LLVMToSPIRVBase::FPContract LLVMToSPIRVBase::getFPContract(Function *F) {
6183 auto It = FPContractMap.find(F);
6184 if (It == FPContractMap.end()) {
6185 return FPContract::UNDEF;
6186 }
6187 return It->second;
6188 }
6189
6190 bool LLVMToSPIRVBase::joinFPContract(Function *F, FPContract C) {
6191 FPContract &Existing = FPContractMap[F];
6192 switch (Existing) {
6193 case FPContract::UNDEF:
6194 if (C != FPContract::UNDEF) {
6195 Existing = C;
6196 return true;
6197 }
6198 return false;
6199 case FPContract::ENABLED:
6200 if (C == FPContract::DISABLED) {
6201 Existing = C;
6202 return true;
6203 }
6204 return false;
6205 case FPContract::DISABLED:
6206 return false;
6207 }
6208 llvm_unreachable("Unhandled FPContract value.");
6209 }
6210
6211 } // namespace SPIRV
6212
6213 char LLVMToSPIRVLegacy::ID = 0;
6214
6215 INITIALIZE_PASS_BEGIN(LLVMToSPIRVLegacy, "llvmtospv",
6216 "Translate LLVM to SPIR-V", false, false)
6217 INITIALIZE_PASS_DEPENDENCY(OCLTypeToSPIRVLegacy)
6218 INITIALIZE_PASS_END(LLVMToSPIRVLegacy, "llvmtospv", "Translate LLVM to SPIR-V",
6219 false, false)
6220
6221 ModulePass *llvm::createLLVMToSPIRVLegacy(SPIRVModule *SMod) {
6222 return new LLVMToSPIRVLegacy(SMod);
6223 }
6224
6225 void addPassesForSPIRV(ModulePassManager &PassMgr,
6226 const SPIRV::TranslatorOpts &Opts) {
6227 if (Opts.isSPIRVMemToRegEnabled())
6228 PassMgr.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
6229 PassMgr.addPass(PreprocessMetadataPass());
6230 PassMgr.addPass(SPIRVLowerOCLBlocksPass());
6231 PassMgr.addPass(OCLToSPIRVPass());
6232 PassMgr.addPass(SPIRVRegularizeLLVMPass());
6233 PassMgr.addPass(SPIRVLowerConstExprPass());
6234 PassMgr.addPass(SPIRVLowerBoolPass());
6235 PassMgr.addPass(SPIRVLowerMemmovePass());
6236 PassMgr.addPass(SPIRVLowerSaddWithOverflowPass());
6237 PassMgr.addPass(createModuleToFunctionPassAdaptor(
6238 SPIRVLowerBitCastToNonStandardTypePass(Opts)));
6239 }
6240
6241 bool isValidLLVMModule(Module *M, SPIRVErrorLog &ErrorLog) {
6242 if (!M)
6243 return false;
6244
6245 if (isEmptyLLVMModule(M))
6246 return true;
6247
6248 Triple TT(M->getTargetTriple());
6249 if (!ErrorLog.checkError(isSupportedTriple(TT), SPIRVEC_InvalidTargetTriple,
6250 "Actual target triple is " + M->getTargetTriple()))
6251 return false;
6252
6253 return true;
6254 }
6255
6256 namespace {
6257
6258 VersionNumber getVersionFromTriple(const Triple &TT, SPIRVErrorLog &ErrorLog) {
6259 switch (TT.getSubArch()) {
6260 case Triple::SPIRVSubArch_v10:
6261 return VersionNumber::SPIRV_1_0;
6262 case Triple::SPIRVSubArch_v11:
6263 return VersionNumber::SPIRV_1_1;
6264 case Triple::SPIRVSubArch_v12:
6265 return VersionNumber::SPIRV_1_2;
6266 case Triple::SPIRVSubArch_v13:
6267 return VersionNumber::SPIRV_1_3;
6268 case Triple::SPIRVSubArch_v14:
6269 return VersionNumber::SPIRV_1_4;
6270 case Triple::SPIRVSubArch_v15:
6271 return VersionNumber::SPIRV_1_5;
6272 default:
6273 ErrorLog.checkError(false, SPIRVEC_InvalidSubArch, TT.getArchName().str());
6274 return VersionNumber::MaximumVersion;
6275 }
6276 }
6277
6278 bool runSpirvWriterPasses(Module *M, std::ostream *OS, std::string &ErrMsg,
6279 const SPIRV::TranslatorOpts &Opts) {
6280 // Perform the conversion and write the resulting SPIR-V if an ostream has
6281 // been given; otherwise only perform regularization.
6282 bool WriteSpirv = OS != nullptr;
6283
6284 std::unique_ptr<SPIRVModule> BM(SPIRVModule::createSPIRVModule(Opts));
6285 if (!isValidLLVMModule(M, BM->getErrorLog()))
6286 return false;
6287
6288 // If the module carries a SPIR-V triple with a version subarch, target
6289 // that SPIR-V version.
6290 Triple TargetTriple(M->getTargetTriple());
6291 if ((TargetTriple.getArch() == Triple::spirv32 ||
6292 TargetTriple.getArch() == Triple::spirv64) &&
6293 TargetTriple.getSubArch() != Triple::NoSubArch) {
6294 VersionNumber ModuleVer =
6295 getVersionFromTriple(TargetTriple, BM->getErrorLog());
6296 if (!BM->getErrorLog().checkError(ModuleVer <= Opts.getMaxVersion(),
6297 SPIRVEC_TripleMaxVersionIncompatible))
6298 return false;
6299 BM->setMinSPIRVVersion(ModuleVer);
6300 }
6301
6302 ModulePassManager PassMgr;
6303 addPassesForSPIRV(PassMgr, Opts);
6304 if (WriteSpirv) {
6305 // Run loop simplify pass in order to avoid duplicate OpLoopMerge
6306 // instruction. It can happen in case of continue operand in the loop.
6307 if (hasLoopMetadata(M))
6308 PassMgr.addPass(createModuleToFunctionPassAdaptor(LoopSimplifyPass()));
6309 PassMgr.addPass(LLVMToSPIRVPass(BM.get()));
6310 }
6311
6312 LoopAnalysisManager LAM;
6313 CGSCCAnalysisManager CGAM;
6314 FunctionAnalysisManager FAM;
6315 ModuleAnalysisManager MAM;
6316
6317 PassBuilder PB;
6318 PB.registerModuleAnalyses(MAM);
6319 PB.registerCGSCCAnalyses(CGAM);
6320 PB.registerFunctionAnalyses(FAM);
6321 PB.registerLoopAnalyses(LAM);
6322 MAM.registerPass([&] { return OCLTypeToSPIRVPass(); });
6323 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
6324
6325 PassMgr.run(*M, MAM);
6326
6327 if (BM->getError(ErrMsg) != SPIRVEC_Success)
6328 return false;
6329
6330 if (WriteSpirv)
6331 *OS << *BM;
6332
6333 return true;
6334 }
6335
6336 } // namespace
6337
6338 bool llvm::writeSpirv(Module *M, std::ostream &OS, std::string &ErrMsg) {
6339 SPIRV::TranslatorOpts DefaultOpts;
6340 // To preserve old behavior of the translator, let's enable all extensions
6341 // by default in this API
6342 DefaultOpts.enableAllExtensions();
6343 return llvm::writeSpirv(M, DefaultOpts, OS, ErrMsg);
6344 }
6345
6346 bool llvm::writeSpirv(Module *M, const SPIRV::TranslatorOpts &Opts,
6347 std::ostream &OS, std::string &ErrMsg) {
6348 return runSpirvWriterPasses(M, &OS, ErrMsg, Opts);
6349 }
6350
6351 bool llvm::regularizeLlvmForSpirv(Module *M, std::string &ErrMsg) {
6352 SPIRV::TranslatorOpts DefaultOpts;
6353 // To preserve old behavior of the translator, let's enable all extensions
6354 // by default in this API
6355 DefaultOpts.enableAllExtensions();
6356 return llvm::regularizeLlvmForSpirv(M, ErrMsg, DefaultOpts);
6357 }
6358
6359 bool llvm::regularizeLlvmForSpirv(Module *M, std::string &ErrMsg,
6360 const SPIRV::TranslatorOpts &Opts) {
6361 return runSpirvWriterPasses(M, nullptr, ErrMsg, Opts);
6362 }