LLVM 24.0.0git
SPIRVPrepareFunctions.cpp
Go to the documentation of this file.
1//===-- SPIRVPrepareFunctions.cpp - modify function signatures --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass modifies function signatures containing aggregate arguments
10// and/or return value before IRTranslator. Information about the original
11// signatures is stored in metadata. It is used during call lowering to
12// restore correct SPIR-V types of function arguments and return values.
13// This pass also substitutes some llvm intrinsic calls with calls to newly
14// generated functions (as the Khronos LLVM/SPIR-V Translator does).
15//
16// NOTE: this pass is a module-level one due to the necessity to modify
17// GVs/functions.
18//
19//===----------------------------------------------------------------------===//
20
21#include "SPIRV.h"
22#include "SPIRVBuiltins.h"
23#include "SPIRVSubtarget.h"
24#include "SPIRVTargetMachine.h"
25#include "SPIRVUtils.h"
32#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/IntrinsicsSPIRV.h"
43#include <regex>
44
45using namespace llvm;
46
47namespace {
48
49class SPIRVPrepareFunctionsImpl {
50 const SPIRVTargetMachine &TM;
51 function_ref<const TargetTransformInfo &(Function &)> GetTTI;
52 bool substituteIntrinsicCalls(Function *F);
53 bool substituteAbortKHRCalls(Function *F);
54 bool terminateBlocksAfterTrap(Module &M, Intrinsic::ID IID);
55 Function *removeAggregateTypesFromSignature(Function *F);
56 bool removeAggregateTypesFromCalls(Function *F);
57
58public:
59 SPIRVPrepareFunctionsImpl(
60 const SPIRVTargetMachine &TM,
61 function_ref<const TargetTransformInfo &(Function &)> GetTTI)
62 : TM(TM), GetTTI(GetTTI) {}
63 bool runOnModule(Module &M);
64};
65
66class SPIRVPrepareFunctionsLegacy : public ModulePass {
67 const SPIRVTargetMachine &TM;
68
69public:
70 static char ID;
71 SPIRVPrepareFunctionsLegacy(const SPIRVTargetMachine &TM)
72 : ModulePass(ID), TM(TM) {}
73
74 bool runOnModule(Module &M) override {
75 auto GetTTI = [this](Function &F) -> const TargetTransformInfo & {
76 return getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
77 };
78 return SPIRVPrepareFunctionsImpl(TM, GetTTI).runOnModule(M);
79 }
80
81 void getAnalysisUsage(AnalysisUsage &AU) const override {
82 AU.addRequired<TargetTransformInfoWrapperPass>();
83 }
84
85 StringRef getPassName() const override { return "SPIRV prepare functions"; }
86};
87} // namespace
88
89char SPIRVPrepareFunctionsLegacy::ID = 0;
90
91INITIALIZE_PASS_BEGIN(SPIRVPrepareFunctionsLegacy, "spirv-prepare-functions",
92 "SPIRV prepare functions", false, false)
94INITIALIZE_PASS_END(SPIRVPrepareFunctionsLegacy, "spirv-prepare-functions",
95 "SPIRV prepare functions", false, false)
96
98 Function *IntrinsicFunc = II->getCalledFunction();
99 assert(IntrinsicFunc && "Missing function");
100 std::string FuncName = IntrinsicFunc->getName().str();
101 llvm::replace(FuncName, '.', '_');
102 FuncName = "spirv." + FuncName;
103 return FuncName;
104}
105
107 ArrayRef<Type *> ArgTypes,
108 StringRef Name) {
109 FunctionType *FT = FunctionType::get(RetTy, ArgTypes, false);
110 Function *F = M->getFunction(Name);
111 if (F && F->getFunctionType() == FT)
112 return F;
114 if (F)
115 NewF->setDSOLocal(F->isDSOLocal());
117 return NewF;
118}
119
120// Rewrites a memset with constant value and length as a copy from a constant
121// global array.
122static bool lowerConstantMemSet(MemSetInst *MSI, const SPIRVSubtarget &STI) {
123 auto *Val = dyn_cast<Constant>(MSI->getValue());
124 auto *Len = dyn_cast<ConstantInt>(MSI->getLength());
125 if (!Val || !Len)
126 return false;
127 if (Len->isZero() || (isa<UndefValue>(Val) && !MSI->isVolatile())) {
128 MSI->eraseFromParent();
129 return true;
130 }
131 // Undef bytes may be refined to zeros.
132 if (isa<UndefValue>(Val))
133 Val = Constant::getNullValue(Val->getType());
134 uint64_t Num = Len->getZExtValue();
135 auto *ArrTy = ArrayType::get(Val->getType(), Num);
136 Constant *Init =
137 Val->isNullValue()
140 // Vulkan rejects initializers on UniformConstant variables.
141 unsigned AS = STI.isShader() ? SPIRVAS::Private : SPIRVAS::UniformConstant;
142 auto *GV = new GlobalVariable(*MSI->getModule(), ArrTy, /*isConstant=*/true,
146 GV->setAlignment(Align);
147 IRBuilder<> IRB(MSI);
148 IRB.CreateMemTransferInst(MSI->getIntrinsicID() == Intrinsic::memset_inline
149 ? Intrinsic::memcpy_inline
150 : Intrinsic::memcpy,
151 MSI->getDest(), Align, GV, Align, Len,
152 MSI->isVolatile(), MSI->getAAMetadata());
153 MSI->eraseFromParent();
154 return true;
155}
156
158 const TargetTransformInfo &TTI) {
159 // An intrinsic with a metadata argument has no SPIR-V lowering and can't be
160 // turned into a function.
162 const Function *F = Intrinsic->getFunction();
163 F->getContext().diagnose(DiagnosticInfoUnsupported(
164 *F,
165 "cannot lower the intrinsic '" +
166 Intrinsic->getCalledFunction()->getName() +
167 "' that takes a metadata argument",
168 Intrinsic->getDebugLoc()));
169 if (!Intrinsic->getType()->isVoidTy())
170 Intrinsic->replaceAllUsesWith(PoisonValue::get(Intrinsic->getType()));
171 Intrinsic->eraseFromParent();
172 return true;
173 }
174
175 Module *M = Intrinsic->getModule();
176 std::string FuncName = lowerLLVMIntrinsicName(Intrinsic);
177 if (Intrinsic->isVolatile())
178 FuncName += ".volatile";
179 // Redirect @llvm.intrinsic.* call to @spirv.llvm_intrinsic_*
180 Function *F = M->getFunction(FuncName);
181 if (F) {
182 Intrinsic->setCalledFunction(F);
183 return true;
184 }
185 FunctionCallee FC =
186 M->getOrInsertFunction(FuncName, Intrinsic->getFunctionType());
187 auto IntrinsicID = Intrinsic->getIntrinsicID();
188 Intrinsic->setCalledFunction(FC);
189 F = cast<Function>(FC.getCallee());
190 F->setAttributes(Intrinsic->getAttributes());
191
192 switch (IntrinsicID) {
193 case Intrinsic::memset: {
194 auto *MSI = static_cast<MemSetInst *>(Intrinsic);
195 Argument *Dest = F->getArg(0);
196 Argument *Val = F->getArg(1);
197 Argument *Len = F->getArg(2);
198 Argument *IsVolatile = F->getArg(3);
199 Dest->setName("dest");
200 Val->setName("val");
201 Len->setName("len");
202 IsVolatile->setName("isvolatile");
203 BasicBlock *EntryBB = BasicBlock::Create(M->getContext(), "entry", F);
204 IRBuilder<> IRB(EntryBB);
205 auto *MemSet = IRB.CreateMemSet(Dest, Val, Len, MSI->getDestAlign(),
206 MSI->isVolatile());
207 IRB.CreateRetVoid();
209 MemSet->eraseFromParent();
210 break;
211 }
212 case Intrinsic::bswap: {
213 BasicBlock *EntryBB = BasicBlock::Create(M->getContext(), "entry", F);
214 IRBuilder<> IRB(EntryBB);
216 Intrinsic::bswap, Intrinsic->getType(), F->getArg(0));
217 IRB.CreateRet(BSwap);
218 IntrinsicLowering IL(M->getDataLayout());
219 IL.LowerIntrinsicCall(BSwap);
220 break;
221 }
222 default:
223 break;
224 }
225 return true;
226}
227
228static std::string getAnnotation(Value *AnnoVal, Value *OptAnnoVal) {
229 if (auto *Ref = dyn_cast_or_null<GetElementPtrInst>(AnnoVal))
230 AnnoVal = Ref->getOperand(0);
231 if (auto *Ref = dyn_cast_or_null<BitCastInst>(OptAnnoVal))
232 OptAnnoVal = Ref->getOperand(0);
233
234 std::string Anno;
235 if (auto *C = dyn_cast_or_null<Constant>(AnnoVal)) {
236 StringRef Str;
237 if (getConstantStringInfo(C, Str))
238 Anno = Str;
239 }
240 // handle optional annotation parameter in a way that Khronos Translator do
241 // (collect integers wrapped in a struct)
242 if (auto *C = dyn_cast_or_null<Constant>(OptAnnoVal);
243 C && C->getNumOperands()) {
244 Value *MaybeStruct = C->getOperand(0);
245 if (auto *Struct = dyn_cast<ConstantStruct>(MaybeStruct)) {
246 for (unsigned I = 0, E = Struct->getNumOperands(); I != E; ++I) {
247 if (auto *CInt = dyn_cast<ConstantInt>(Struct->getOperand(I)))
248 Anno += (I == 0 ? ": " : ", ") +
249 std::to_string(CInt->getType()->getIntegerBitWidth() == 1
250 ? CInt->getZExtValue()
251 : CInt->getSExtValue());
252 }
253 } else if (auto *Struct = dyn_cast<ConstantAggregateZero>(MaybeStruct)) {
254 // { i32 i32 ... } zeroinitializer
255 for (unsigned I = 0, E = Struct->getType()->getStructNumElements();
256 I != E; ++I)
257 Anno += I == 0 ? ": 0" : ", 0";
258 }
259 }
260 return Anno;
261}
262
264 const std::string &Anno,
265 LLVMContext &Ctx,
266 Type *Int32Ty) {
267 // Try to parse the annotation string according to the following rules:
268 // annotation := ({kind} | {kind:value,value,...})+
269 // kind := number
270 // value := number | string
271 static const std::regex R(
272 "\\{(\\d+)(?:[:,](\\d+|\"[^\"]*\")(?:,(\\d+|\"[^\"]*\"))*)?\\}");
274 int Pos = 0;
275 for (std::sregex_iterator
276 It = std::sregex_iterator(Anno.begin(), Anno.end(), R),
277 ItEnd = std::sregex_iterator();
278 It != ItEnd; ++It) {
279 if (It->position() != Pos)
281 Pos = It->position() + It->length();
282 std::smatch Match = *It;
284 for (std::size_t i = 1; i < Match.size(); ++i) {
285 std::ssub_match SMatch = Match[i];
286 std::string Item = SMatch.str();
287 if (Item.length() == 0)
288 break;
289 if (Item[0] == '"') {
290 Item = Item.substr(1, Item.length() - 2);
291 // Acceptable format of the string snippet is:
292 static const std::regex RStr("^(\\d+)(?:,(\\d+))*$");
293 if (std::smatch MatchStr; std::regex_match(Item, MatchStr, RStr)) {
294 for (std::size_t SubIdx = 1; SubIdx < MatchStr.size(); ++SubIdx)
295 if (std::string SubStr = MatchStr[SubIdx].str(); SubStr.length())
297 ConstantInt::get(Int32Ty, std::stoi(SubStr))));
298 } else {
299 MDsItem.push_back(MDString::get(Ctx, Item));
300 }
301 } else if (int32_t Num; llvm::to_integer(StringRef(Item), Num, 10)) {
302 MDsItem.push_back(
303 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Num)));
304 } else {
305 MDsItem.push_back(MDString::get(Ctx, Item));
306 }
307 }
308 if (MDsItem.size() == 0)
310 MDs.push_back(MDNode::get(Ctx, MDsItem));
311 }
312 return Pos == static_cast<int>(Anno.length()) ? std::move(MDs)
314}
315
317 LLVMContext &Ctx = II->getContext();
318 Type *Int32Ty = Type::getInt32Ty(Ctx);
319
320 // Retrieve an annotation string from arguments.
321 Value *PtrArg = nullptr;
322 if (auto *BI = dyn_cast<BitCastInst>(II->getArgOperand(0)))
323 PtrArg = BI->getOperand(0);
324 else
325 PtrArg = II->getOperand(0);
326 std::string Anno =
327 getAnnotation(II->getArgOperand(1),
328 4 < II->arg_size() ? II->getArgOperand(4) : nullptr);
329
330 // Parse the annotation.
331 SmallVector<Metadata *> MDs = parseAnnotation(II, Anno, Ctx, Int32Ty);
332
333 // If the annotation string is not parsed successfully we don't know the
334 // format used and output it as a general UserSemantic decoration.
335 // Otherwise MDs is a Metadata tuple (a decoration list) in the format
336 // expected by `spirv.Decorations`.
337 if (MDs.size() == 0) {
338 auto UserSemantic = ConstantAsMetadata::get(ConstantInt::get(
339 Int32Ty, static_cast<uint32_t>(SPIRV::Decoration::UserSemantic)));
340 MDs.push_back(MDNode::get(Ctx, {UserSemantic, MDString::get(Ctx, Anno)}));
341 }
342
343 // Build the internal intrinsic function.
344 IRBuilder<> IRB(II->getParent());
345 IRB.SetInsertPoint(II);
346 IRB.CreateIntrinsic(
347 Intrinsic::spv_assign_decoration, {PtrArg->getType()},
348 {PtrArg, MetadataAsValue::get(Ctx, MDNode::get(Ctx, MDs))});
349 II->replaceAllUsesWith(II->getOperand(0));
350}
351
352static void lowerFunnelShifts(IntrinsicInst *FSHIntrinsic) {
353 // Get a separate function - otherwise, we'd have to rework the CFG of the
354 // current one. Then simply replace the intrinsic uses with a call to the new
355 // function.
356 // Generate LLVM IR for i* @spirv.llvm_fsh?_i* (i* %a, i* %b, i* %c)
357 Module *M = FSHIntrinsic->getModule();
358 FunctionType *FSHFuncTy = FSHIntrinsic->getFunctionType();
359 Type *FSHRetTy = FSHFuncTy->getReturnType();
360 const std::string FuncName = lowerLLVMIntrinsicName(FSHIntrinsic);
361 Function *FSHFunc =
362 getOrCreateFunction(M, FSHRetTy, FSHFuncTy->params(), FuncName);
363
364 if (!FSHFunc->empty()) {
365 FSHIntrinsic->setCalledFunction(FSHFunc);
366 return;
367 }
368 BasicBlock *RotateBB = BasicBlock::Create(M->getContext(), "rotate", FSHFunc);
369 IRBuilder<> IRB(RotateBB);
370 Type *Ty = FSHFunc->getReturnType();
371 // Build the actual funnel shift rotate logic.
372 // In the comments, "int" is used interchangeably with "vector of int
373 // elements".
375 Type *IntTy = VectorTy ? VectorTy->getElementType() : Ty;
376 unsigned BitWidth = IntTy->getIntegerBitWidth();
377 ConstantInt *BitWidthConstant = IRB.getInt({BitWidth, BitWidth});
378 Value *BitWidthForInsts =
379 VectorTy
380 ? IRB.CreateVectorSplat(VectorTy->getNumElements(), BitWidthConstant)
381 : BitWidthConstant;
382 Value *RotateModVal =
383 IRB.CreateURem(/*Rotate*/ FSHFunc->getArg(2), BitWidthForInsts);
384 Value *FirstShift = nullptr, *SecShift = nullptr;
385 if (FSHIntrinsic->getIntrinsicID() == Intrinsic::fshr) {
386 // Shift the less significant number right, the "rotate" number of bits
387 // will be 0-filled on the left as a result of this regular shift.
388 FirstShift = IRB.CreateLShr(FSHFunc->getArg(1), RotateModVal);
389 } else {
390 // Shift the more significant number left, the "rotate" number of bits
391 // will be 0-filled on the right as a result of this regular shift.
392 FirstShift = IRB.CreateShl(FSHFunc->getArg(0), RotateModVal);
393 }
394 // We want the "rotate" number of the more significant int's LSBs (MSBs) to
395 // occupy the leftmost (rightmost) "0 space" left by the previous operation.
396 // Therefore, subtract the "rotate" number from the integer bitsize...
397 Value *SubRotateVal = IRB.CreateSub(BitWidthForInsts, RotateModVal);
398 if (FSHIntrinsic->getIntrinsicID() == Intrinsic::fshr) {
399 // ...and left-shift the more significant int by this number, zero-filling
400 // the LSBs.
401 SecShift = IRB.CreateShl(FSHFunc->getArg(0), SubRotateVal);
402 } else {
403 // ...and right-shift the less significant int by this number, zero-filling
404 // the MSBs.
405 SecShift = IRB.CreateLShr(FSHFunc->getArg(1), SubRotateVal);
406 }
407 // A simple binary addition of the shifted ints yields the final result.
408 IRB.CreateRet(IRB.CreateOr(FirstShift, SecShift));
409
410 FSHIntrinsic->setCalledFunction(FSHFunc);
411}
412
414 ConstrainedFPCmpIntrinsic *ConstrainedCmpIntrinsic,
415 SmallVector<Instruction *> &EraseFromParent) {
416 if (!ConstrainedCmpIntrinsic)
417 return;
418 // Extract the floating-point values being compared
419 Value *LHS = ConstrainedCmpIntrinsic->getArgOperand(0);
420 Value *RHS = ConstrainedCmpIntrinsic->getArgOperand(1);
421 FCmpInst::Predicate Pred = ConstrainedCmpIntrinsic->getPredicate();
422 IRBuilder<> Builder(ConstrainedCmpIntrinsic);
423 Value *FCmp = Builder.CreateFCmp(Pred, LHS, RHS);
424 ConstrainedCmpIntrinsic->replaceAllUsesWith(FCmp);
425 EraseFromParent.push_back(dyn_cast<Instruction>(ConstrainedCmpIntrinsic));
426}
427
429 // If we cannot use the SPV_KHR_expect_assume extension, then we need to
430 // ignore the intrinsic and move on. It should be removed later on by LLVM.
431 // Otherwise we should lower the intrinsic to the corresponding SPIR-V
432 // instruction.
433 // For @llvm.assume we have OpAssumeTrueKHR.
434 // For @llvm.expect and @llvm.expect.with.probability we have OpExpectKHR.
435 //
436 // We need to lower this into a builtin and then the builtin into a SPIR-V
437 // instruction.
438 if (II->getIntrinsicID() == Intrinsic::assume) {
440 II->getModule(), Intrinsic::SPVIntrinsics::spv_assume);
441 II->setCalledFunction(F);
442 } else if (II->getIntrinsicID() == Intrinsic::expect) {
444 II->getModule(), Intrinsic::SPVIntrinsics::spv_expect,
445 {II->getOperand(0)->getType()});
446 II->setCalledFunction(F);
447 } else if (II->getIntrinsicID() == Intrinsic::expect_with_probability) {
448 // OpExpectKHR has no probability operand. Keep the hint only if the
449 // expected value is likely, as LowerExpectIntrinsic does for PHIs.
450 Value *Res = II->getArgOperand(0);
451 double Prob =
452 cast<ConstantFP>(II->getArgOperand(2))->getValueAPF().convertToDouble();
453 if (Prob > 0.5)
454 Res = IRBuilder<>(II).CreateIntrinsic(
455 Intrinsic::SPVIntrinsics::spv_expect, {II->getType()},
456 {II->getArgOperand(0), II->getArgOperand(1)});
457 BasicBlock::iterator BI = II->getIterator();
458 ReplaceInstWithValue(BI, Res);
459 } else {
460 llvm_unreachable("Unknown intrinsic");
461 }
462}
463
465 auto *LifetimeArg0 = II->getArgOperand(0);
466
467 // If the lifetime argument is a poison value, the intrinsic has no effect.
468 if (isa<PoisonValue>(LifetimeArg0)) {
469 II->eraseFromParent();
470 return true;
471 }
472
473 auto *Alloca = dyn_cast<AllocaInst>(LifetimeArg0);
474 if (!Alloca || !Alloca->isStaticAlloca()) {
475 II->eraseFromParent();
476 return true;
477 }
478
479 IRBuilder<> Builder(II);
480 std::optional<TypeSize> Size =
481 Alloca->getAllocationSize(Alloca->getDataLayout());
482 Value *SizeVal = Builder.getInt64(Size ? *Size : -1);
483 Builder.CreateIntrinsic(NewID, Alloca->getType(), {SizeVal, LifetimeArg0});
484 II->eraseFromParent();
485 return true;
486}
487
488static void
490 SmallVector<Instruction *> &EraseFromParent) {
491 auto *FPI = cast<ConstrainedFPIntrinsic>(II);
492 Value *A = FPI->getArgOperand(0);
493 Value *Mul = FPI->getArgOperand(1);
494 Value *Add = FPI->getArgOperand(2);
495 IRBuilder<> Builder(II->getParent());
496 Builder.SetInsertPoint(II);
497 std::optional<RoundingMode> Rounding = FPI->getRoundingMode();
498 Value *Product = Builder.CreateFMul(A, Mul, II->getName() + ".mul");
499 Value *Result = Builder.CreateConstrainedFPBinOp(
500 Intrinsic::experimental_constrained_fadd, Product, Add, {},
501 II->getName() + ".add", nullptr, Rounding);
502 II->replaceAllUsesWith(Result);
503 EraseFromParent.push_back(II);
504}
505
506// Give a zero minnum/maxnum result the sign llvm.minimum/maximum(num) require.
507static Value *fixZeroSign(IRBuilderBase &Builder, bool IsMax, Value *Res,
508 Value *X, Value *Y) {
509 Type *Ty = X->getType();
510 Value *XSign = Builder.CreateCopySign(ConstantFP::get(Ty, 1.0), X);
511 Value *XNeg = Builder.CreateFCmpOLT(XSign, ConstantFP::getZero(Ty));
512 Value *Sign = IsMax ? Builder.CreateSelect(XNeg, Y, X)
513 : Builder.CreateSelect(XNeg, X, Y);
514 return Builder.CreateCopySign(Res, Sign);
515}
516
517// llvm.minimum/llvm.maximum return NaN if either operand is NaN and order -0.0
518// before +0.0, whereas OpenCL.std fmin/fmax and GLSL.std.450 NMin/NMax return
519// the other operand for a NaN and may return either zero. Expand them like
520// SPIRV-LLVM-Translator does, so that both produce the same OpenCL SPIR-V. For
521// llvm.minimum (llvm.maximum is symmetrical):
522// %m = call @llvm.minnum(%x, %y)
523// ; unless nsz: for non-NaN operands, the result has the sign of %x if that
524// ; is set (maximum: clear), and the sign of %y otherwise. This only changes
525// ; %m if it is a zero of the wrong sign.
526// %xsign = call @llvm.copysign(1.0, %x)
527// %xneg = fcmp olt %xsign, 0.0
528// %s = select %xneg, %x, %y
529// %m.s = call @llvm.copysign(%m, %s)
530// ; unless nnan
531// %uno = fcmp uno %x, %y
532// %res = select %uno, NaN, %m.s
533static Value *expandFMinimumMaximum(IRBuilderBase &Builder, bool IsMax,
534 Value *X, Value *Y, FastMathFlags FMF) {
535 Type *Ty = X->getType();
536 Value *Res = Builder.CreateIntrinsic(
537 IsMax ? Intrinsic::maxnum : Intrinsic::minnum, {Ty}, {X, Y}, FMF);
538 if (!FMF.noSignedZeros())
539 Res = fixZeroSign(Builder, IsMax, Res, X, Y);
540 if (!FMF.noNaNs()) {
541 Value *Uno = Builder.CreateFCmpUNO(X, Y);
542 Res = Builder.CreateSelect(Uno, ConstantFP::getQNaN(Ty), Res);
543 }
544 return Res;
545}
546
548 SmallVector<Instruction *> &EraseFromParent) {
549 IRBuilder<> Builder(II);
551 Builder, II->getIntrinsicID() == Intrinsic::maximum, II->getArgOperand(0),
552 II->getArgOperand(1), II->getFastMathFlags());
553 Res->takeName(II);
554 II->replaceAllUsesWith(Res);
555 EraseFromParent.push_back(II);
556}
557
558// The SPIR-V fmin/fmax and NMin/NMax that minnum/maxnum lower to may return NaN
559// for an sNaN input and either zero for -0.0 vs +0.0; minimumnum/maximumnum
560// may not.
561static void
563 SmallVector<Instruction *> &EraseFromParent) {
564 IRBuilder<> Builder(II);
565 bool IsMax = II->getIntrinsicID() == Intrinsic::maximumnum;
566 Value *X = II->getArgOperand(0), *Y = II->getArgOperand(1);
567 Type *Ty = X->getType();
568 FastMathFlags FMF = II->getFastMathFlags();
569 if (!FMF.noNaNs()) {
570 X = Builder.CreateSelect(Builder.CreateFCmpUNO(X, X), Y, X);
571 Y = Builder.CreateSelect(Builder.CreateFCmpUNO(Y, Y), X, Y);
572 }
573 // Don't forward flags: SPIR-V NSZ and Fast would also drop the sign of
574 // same-sign zeros.
575 Value *Res = Builder.CreateIntrinsic(
576 IsMax ? Intrinsic::maxnum : Intrinsic::minnum, {Ty}, {X, Y});
577 if (!FMF.noSignedZeros())
578 Res = fixZeroSign(Builder, IsMax, Res, X, Y);
579 Res->takeName(II);
580 II->replaceAllUsesWith(Res);
581 EraseFromParent.push_back(II);
582}
583
584// ExpandReductions only expands llvm.vector.reduce.fminimum/fmaximum on vectors
585// with a power-of-two number of elements. Expand the others into a chain of
586// llvm.minimum/llvm.maximum, expanded as above.
587static void
589 SmallVector<Instruction *> &EraseFromParent) {
590 bool IsMax = II->getIntrinsicID() == Intrinsic::vector_reduce_fmaximum;
591 Value *Vec = II->getArgOperand(0);
592 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
593 IRBuilder<> Builder(II);
595 for (unsigned I = 0; I < NumElts; ++I)
596 Elts.push_back(Builder.CreateExtractElement(Vec, I));
597 Value *Res = Elts[0];
598 for (Value *Elt : drop_begin(Elts))
599 Res =
600 expandFMinimumMaximum(Builder, IsMax, Res, Elt, II->getFastMathFlags());
601 Res->takeName(II);
602 II->replaceAllUsesWith(Res);
603 EraseFromParent.push_back(II);
604}
605
606// Substitutes calls to LLVM intrinsics with either calls to SPIR-V intrinsics
607// or calls to proper generated functions. Returns True if F was modified.
608bool SPIRVPrepareFunctionsImpl::substituteIntrinsicCalls(Function *F) {
609 if (F->isDeclaration())
610 return false;
611
612 bool Changed = false;
613 const SPIRVSubtarget &STI = TM.getSubtarget<SPIRVSubtarget>(*F);
614 SmallVector<Instruction *> EraseFromParent;
615 const TargetTransformInfo &TTI = GetTTI(*F);
616 for (BasicBlock &BB : *F) {
617 for (Instruction &I : make_early_inc_range(BB)) {
618 auto Call = dyn_cast<CallInst>(&I);
619 if (!Call)
620 continue;
622 if (!CF || !CF->isIntrinsic())
623 continue;
624 auto *II = cast<IntrinsicInst>(Call);
625 if (Intrinsic::isTargetIntrinsic(II->getIntrinsicID()) &&
626 II->getCalledOperand()->getName().starts_with("llvm.spv"))
627 continue;
628 if (auto *MSI = dyn_cast<MemSetInst>(II);
629 MSI && lowerConstantMemSet(MSI, STI)) {
630 Changed = true;
631 continue;
632 }
633 switch (II->getIntrinsicID()) {
634 case Intrinsic::memset:
635 case Intrinsic::bswap:
637 break;
638 case Intrinsic::fshl:
639 case Intrinsic::fshr:
641 Changed = true;
642 break;
643 case Intrinsic::minimum:
644 case Intrinsic::maximum:
645 lowerFMinimumMaximum(II, EraseFromParent);
646 Changed = true;
647 break;
648 case Intrinsic::minimumnum:
649 case Intrinsic::maximumnum:
650 lowerFMinimumMaximumNum(II, EraseFromParent);
651 Changed = true;
652 break;
653 case Intrinsic::vector_reduce_fminimum:
654 case Intrinsic::vector_reduce_fmaximum:
655 lowerVectorReduceFMinimumMaximum(II, EraseFromParent);
656 Changed = true;
657 break;
658 case Intrinsic::assume:
659 case Intrinsic::expect:
660 case Intrinsic::expect_with_probability:
661 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_expect_assume))
663 Changed = true;
664 break;
665 case Intrinsic::lifetime_start:
666 if (!STI.isShader()) {
668 II, Intrinsic::SPVIntrinsics::spv_lifetime_start);
669 } else {
670 II->eraseFromParent();
671 Changed = true;
672 }
673 break;
674 case Intrinsic::lifetime_end:
675 if (!STI.isShader()) {
677 II, Intrinsic::SPVIntrinsics::spv_lifetime_end);
678 } else {
679 II->eraseFromParent();
680 Changed = true;
681 }
682 break;
683 case Intrinsic::ptr_annotation:
685 Changed = true;
686 break;
687 case Intrinsic::experimental_constrained_fmuladd:
688 lowerConstrainedFmuladd(II, EraseFromParent);
689 Changed = true;
690 break;
691 case Intrinsic::experimental_constrained_fcmp:
692 case Intrinsic::experimental_constrained_fcmps:
694 EraseFromParent);
695 Changed = true;
696 break;
697 default:
698 // Drop assume-like intrinsics that have no SPIR-V representation.
699 if (II->isAssumeLikeIntrinsic()) {
700 if (!II->getType()->isVoidTy())
701 II->replaceAllUsesWith(PoisonValue::get(II->getType()));
702 II->eraseFromParent();
703 Changed = true;
704 break;
705 }
706 if (STI.getTargetTriple().getVendor() == Triple::AMD ||
707 any_of(STI.getCLOpts().allow_unknown_intrinsics,
708 [II](StringRef Prefix) {
709 if (Prefix.empty())
710 return false;
711 return II->getCalledFunction()->getName().starts_with(
712 Prefix);
713 }))
715 break;
716 }
717 }
718 }
719 for (auto *I : EraseFromParent)
720 I->eraseFromParent();
721 return Changed;
722}
723
724static void
726 SmallVector<std::pair<int, Type *>> ChangedTys,
727 StringRef Name, StringRef AsmConstraints = "") {
728
729 LLVMContext &Ctx = NMD->getParent()->getContext();
730 Type *I32Ty = IntegerType::getInt32Ty(Ctx);
731
733 MDArgs.push_back(MDString::get(Ctx, Name));
734 transform(ChangedTys, std::back_inserter(MDArgs), [=, &Ctx](auto &&CTy) {
735 return MDNode::get(
736 Ctx, {ConstantAsMetadata::get(ConstantInt::get(I32Ty, CTy.first, true)),
738 });
739 if (!AsmConstraints.empty())
740 MDArgs.push_back(MDNode::get(Ctx, MDString::get(Ctx, AsmConstraints)));
741 NMD->addOperand(MDNode::get(Ctx, MDArgs));
742}
743
744// Drops attributes that are invalid on the i32 placeholders in the type of V.
745template <typename T> static void removeIncompatibleAttrs(T *V) {
746 FunctionType *FTy = V->getFunctionType();
747 AttributeList Attrs = V->getAttributes();
748 V->removeRetAttrs(AttributeFuncs::typeIncompatible(FTy->getReturnType(),
749 Attrs.getRetAttrs()));
750 for (auto [I, Ty] : enumerate(FTy->params()))
751 V->removeParamAttrs(
752 I, AttributeFuncs::typeIncompatible(Ty, Attrs.getParamAttrs(I)));
753}
754
755// Returns F if aggregate argument/return types are not present or cloned F
756// function with the types replaced by i32 types. The change in types is
757// noted in 'spv.cloned_funcs' metadata for later restoration.
758Function *
759SPIRVPrepareFunctionsImpl::removeAggregateTypesFromSignature(Function *F) {
760 bool IsRetAggr = F->getReturnType()->isAggregateType();
761 // Allow intrinsics with aggregate return/argument types to reach GlobalISel.
762 // Renaming/mutating the signature of an intrinsic would desync its name from
763 // its argument types and break the IR verifier.
764 if (F->isIntrinsic())
765 return F;
766
767 IRBuilder<> B(*F->getParent());
768
769 bool HasAggrArg = llvm::any_of(F->args(), [](Argument &Arg) {
770 return Arg.getType()->isAggregateType();
771 });
772 bool DoClone = IsRetAggr || HasAggrArg;
773 if (!DoClone)
774 return F;
775 SmallVector<std::pair<int, Type *>, 4> ChangedTypes;
776 Type *RetType = IsRetAggr ? B.getInt32Ty() : F->getReturnType();
777 if (IsRetAggr)
778 ChangedTypes.push_back(std::pair<int, Type *>(-1, F->getReturnType()));
779 SmallVector<Type *, 4> ArgTypes;
780 for (const auto &Arg : F->args()) {
781 if (Arg.getType()->isAggregateType()) {
782 ArgTypes.push_back(B.getInt32Ty());
783 ChangedTypes.push_back(
784 std::pair<int, Type *>(Arg.getArgNo(), Arg.getType()));
785 } else
786 ArgTypes.push_back(Arg.getType());
787 }
788 FunctionType *NewFTy =
789 FunctionType::get(RetType, ArgTypes, F->getFunctionType()->isVarArg());
790 Function *NewF =
791 Function::Create(NewFTy, F->getLinkage(), F->getAddressSpace(),
792 F->getName(), F->getParent());
793
795 auto NewFArgIt = NewF->arg_begin();
796 for (auto &Arg : F->args()) {
797 StringRef ArgName = Arg.getName();
798 NewFArgIt->setName(ArgName);
799 VMap[&Arg] = &(*NewFArgIt++);
800 }
802
803 CloneFunctionInto(NewF, F, VMap, CloneFunctionChangeType::LocalChangesOnly,
804 Returns);
805 NewF->takeName(F);
806 NewF->setComdat(F->getComdat());
808
810 NewF->getParent()->getOrInsertNamedMetadata("spv.cloned_funcs"),
811 std::move(ChangedTypes), NewF->getName());
812
813 for (User *U : F->users()) {
814 if (auto *CB = dyn_cast<CallBase>(U); CB && CB->getCalledFunction() == F) {
815 CB->mutateFunctionType(NewF->getFunctionType());
817 }
818 }
819 // NewF keeps F's address space, so their pointer types match and
820 // RAUW is safe despite the differing signatures.
821 assert(F->getType() == NewF->getType() &&
822 "RAUW requires F and NewF to share the same pointer type");
823 F->replaceAllUsesWith(NewF);
824
825 // register the mutation
826 if (RetType != F->getReturnType())
827 TM.getSubtarget<SPIRVSubtarget>(*F).getSPIRVGlobalRegistry()->addMutated(
828 NewF, F->getReturnType());
829 return NewF;
830}
831
832// Returns true iff `F`'s name resolves (after OpenCL/SPIR-V demangling and
833// builtin-name lookup) to the SPIR-V friendly built-in `__spirv_AbortKHR`.
834static bool isAbortKHRBuiltin(const Function &F) {
835 if (F.isIntrinsic())
836 return false;
837 StringRef Name = F.getName();
838 // Quick reject: the mangled or unmangled name must contain the substring.
839 if (!Name.contains("__spirv_AbortKHR"))
840 return false;
841 std::string Demangled = getOclOrSpirvBuiltinDemangledName(Name);
842 if (Demangled.empty())
843 return false;
844 return SPIRV::lookupBuiltinNameHelper(Demangled) == "__spirv_AbortKHR";
845}
846
847// Rewrites a single call to `__spirv_AbortKHR` into a call to the
848// `llvm.spv.abort` target intrinsic, then re-terminates the block with
849// `unreachable`. OpAbortKHR is itself a SPIR-V function-termination
850// instruction and must be the last instruction in its block, so any trailing
851// stores/lifetime intrinsics/`ret` emitted by the OpenCL ABI are dropped.
852// `changeToUnreachable` cleans up any successor PHI predecessor entries.
854 IRBuilder<> B(CI);
855 Value *Msg = CI->getArgOperand(0);
856 // The OpenCL C ABI may pass aggregate arguments by pointer (byval). In that
857 // case load the underlying value so that OpAbortKHR receives the composite
858 // itself, as required by the SPV_KHR_abort spec ("Message Type must be a
859 // concrete type").
860 if (CI->isByValArgument(0)) {
861 Type *AggTy = CI->getParamByValType(0);
862 Msg = B.CreateLoad(AggTy, Msg);
863 }
864 B.CreateIntrinsic(Intrinsic::spv_abort, {Msg->getType()}, {Msg});
866}
867
868// Replace OpenCL/SPIR-V style calls to `__spirv_AbortKHR(message)` (i.e.
869// calls to `F` when `F` is the `__spirv_AbortKHR` built-in) with calls to the
870// `llvm.spv.abort` target intrinsic.
871bool SPIRVPrepareFunctionsImpl::substituteAbortKHRCalls(Function *F) {
872 if (!isAbortKHRBuiltin(*F))
873 return false;
874
875 bool Changed = false;
876 for (User *U : make_early_inc_range(F->users())) {
877 auto *CI = dyn_cast<CallInst>(U);
878 if (!CI || CI->getCalledFunction() != F)
879 continue;
880 if (CI->arg_size() != 1)
881 continue;
883 Changed = true;
884 }
885
886 return Changed;
887}
888
889// When the SPV_KHR_abort extension is enabled, `llvm.trap` and
890// `llvm.ubsantrap` are lowered to `OpAbortKHR` during instruction selection.
891// `OpAbortKHR` is itself a SPIR-V block terminator, so any instructions that
892// follow the trap call within the same basic block (e.g. `ret`, lifetime
893// markers) would produce SPIR-V ops after `OpAbortKHR` and break validation.
894// Terminate the block right after each call to the trap intrinsics by replacing
895// the next instruction with `unreachable`.
896bool SPIRVPrepareFunctionsImpl::terminateBlocksAfterTrap(Module &M,
897 Intrinsic::ID IID) {
898 assert((IID == Intrinsic::trap || IID == Intrinsic::ubsantrap) &&
899 "Expected trap intrinsic ID");
900
902 if (!F)
903 return false;
904
905 // If the target doesn't support SPV_KHR_abort, we won't be able to lower
906 // the trap intrinsic to OpAbortKHR, so we can skip the block-terminating
907 // transformation.
908 const auto &ST = TM.getSubtarget<SPIRVSubtarget>(*F);
909 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_abort))
910 return false;
911
912 bool Changed = false;
913 for (User *U : make_early_inc_range(F->users())) {
914 auto *CI = dyn_cast<CallInst>(U);
915 if (!CI || CI->getCalledFunction() != F)
916 continue;
917 Instruction *Next = CI->getNextNode();
919 continue;
921 Changed = true;
922 }
923 return Changed;
924}
925
926static std::string fixMultiOutputConstraintString(StringRef Constraints) {
927 // We should only have one =r return for the made up ASM type.
929 SplitString(Constraints, Tmp, ",");
930 std::string SafeConstraints("=r,");
931 for (unsigned I = 0u; I != Tmp.size() - 1; ++I) {
932 if (Tmp[I].starts_with('=') && (Tmp[I][1] == '&' || isalnum(Tmp[I][1])))
933 continue;
934 SafeConstraints.append(Tmp[I]).append({','});
935 }
936 SafeConstraints.append(Tmp.back());
937
938 return SafeConstraints;
939}
940
941// Mutates indirect and inline ASM callsites iff aggregate argument/return types
942// are present with the types replaced by i32 types. The change in types is
943// noted in 'spv.mutated_callsites' metadata for later restoration. For ASM we
944// also have to mutate the constraint string as IRTranslator tries to handle
945// multiple outputs and expects an aggregate return type in their presence.
946bool SPIRVPrepareFunctionsImpl::removeAggregateTypesFromCalls(Function *F) {
947 if (F->isDeclaration() || F->isIntrinsic())
948 return false;
949
951 for (auto &&I : instructions(F)) {
952 if (auto *CB = dyn_cast<CallBase>(&I)) {
953 if (!CB->getCalledOperand() || CB->getCalledFunction())
954 continue;
955 if (CB->getType()->isAggregateType() ||
956 any_of(CB->args(),
957 [](auto &&Arg) { return Arg->getType()->isAggregateType(); }))
958 Calls.emplace_back(CB, nullptr);
959 }
960 }
961
962 if (Calls.empty())
963 return false;
964
965 IRBuilder<> B(*F->getParent());
966
967 unsigned MutatedCallIdx = 0;
968 for (auto &&[CB, NewFnTy] : Calls) {
970 SmallVector<Type *> NewArgTypes;
971
972 Type *RetTy = CB->getType();
973 if (RetTy->isAggregateType()) {
974 ChangedTypes.emplace_back(-1, RetTy);
975 RetTy = B.getInt32Ty();
976 }
977
978 for (auto &&Arg : CB->args()) {
979 if (Arg->getType()->isAggregateType()) {
980 NewArgTypes.push_back(B.getInt32Ty());
981 ChangedTypes.emplace_back(Arg.getOperandNo(), Arg->getType());
982 } else {
983 NewArgTypes.push_back(Arg->getType());
984 }
985 }
986 NewFnTy = FunctionType::get(RetTy, NewArgTypes,
987 CB->getFunctionType()->isVarArg());
988
989 // Keyed via instruction metadata, not a name.
990 std::string Key =
991 ("spv.mutated_callsite." + F->getName() + "." + Twine(MutatedCallIdx++))
992 .str();
993 CB->setMetadata(
994 "spv.mutated_callsite",
995 MDNode::get(F->getContext(), MDString::get(F->getContext(), Key)));
996
997 std::string Constraints;
998 if (auto *ASM = dyn_cast<InlineAsm>(CB->getCalledOperand())) {
999 Constraints = ASM->getConstraintString();
1000
1001 CB->setCalledOperand(InlineAsm::get(
1002 NewFnTy, ASM->getAsmString(),
1003 fixMultiOutputConstraintString(Constraints), ASM->hasSideEffects(),
1004 ASM->isAlignStack(), ASM->getDialect(), ASM->canThrow()));
1005 }
1006
1008 F->getParent()->getOrInsertNamedMetadata("spv.mutated_callsites"),
1009 std::move(ChangedTypes), Key, Constraints);
1010 }
1011
1012 for (auto &&[CB, NewFTy] : Calls) {
1013 if (NewFTy->getReturnType() != CB->getType())
1014 TM.getSubtarget<SPIRVSubtarget>(*F).getSPIRVGlobalRegistry()->addMutated(
1015 CB, CB->getType());
1016 CB->mutateFunctionType(NewFTy);
1018 }
1019
1020 return true;
1021}
1022
1023bool SPIRVPrepareFunctionsImpl::runOnModule(Module &M) {
1024 // Resolve the SPIR-V environment from module content before any
1025 // function-level processing. This must happen before legalization so that
1026 // isShader()/isKernel() return correct values.
1027 const_cast<SPIRVTargetMachine &>(TM)
1028 .getMutableSubtargetImpl()
1029 ->resolveEnvFromModule(M);
1030
1031 bool Changed = false;
1032 if (M.getFunctionDefs().empty()) {
1033 // If there are no function definitions, insert a service
1034 // function so that the global/constant tracking intrinsics
1035 // will be created. Without these intrinsics the generated SPIR-V
1036 // will be empty. The service function itself is not emitted.
1038 BasicBlock *BB = BasicBlock::Create(M.getContext(), "entry", SF);
1039 IRBuilder<> IRB(BB);
1040 IRB.CreateRetVoid();
1041 Changed = true;
1042 }
1043
1044 Changed |= terminateBlocksAfterTrap(M, Intrinsic::trap);
1045 Changed |= terminateBlocksAfterTrap(M, Intrinsic::ubsantrap);
1046
1047 for (GlobalVariable &GV : M.globals()) {
1048 // Strip + tag available_externally globals so AuxData can re-emit the
1049 // original linkage as NonSemantic.AuxData::Linkage.
1050 if (GV.hasAvailableExternallyLinkage() && !GV.isDeclaration()) {
1051 GV.addAttribute(SPIRV_WAS_AVAILABLE_EXTERNALLY_ATTR);
1052 GV.setLinkage(GlobalValue::ExternalLinkage);
1053 Changed = true;
1054 }
1055 }
1056
1057 std::vector<Function *> FuncsWorklist;
1058 for (Function &F : M) {
1059 // MachineFunctionPass skips available_externally; strip + tag so AuxData
1060 // can re-emit the original linkage as NonSemantic.AuxData::Linkage.
1061 if (F.hasAvailableExternallyLinkage() && !F.isDeclaration()) {
1063 F.setLinkage(GlobalValue::ExternalLinkage);
1064 Changed = true;
1065 }
1066 Changed |= substituteAbortKHRCalls(&F);
1067 Changed |= substituteIntrinsicCalls(&F);
1068 Changed |= sortBlocks(F);
1069 Changed |= removeAggregateTypesFromCalls(&F);
1070 FuncsWorklist.push_back(&F);
1071 }
1072
1073 for (auto *F : FuncsWorklist) {
1074 Function *NewF = removeAggregateTypesFromSignature(F);
1075
1076 if (NewF != F) {
1077 F->eraseFromParent();
1078 Changed = true;
1079 }
1080 }
1081 return Changed;
1082}
1083
1088 auto GetTTI = [&FAM](Function &F) -> const TargetTransformInfo & {
1089 return FAM.getResult<TargetIRAnalysis>(F);
1090 };
1091 return SPIRVPrepareFunctionsImpl(TM, GetTTI).runOnModule(M)
1094}
1095
1096ModulePass *
1098 return new SPIRVPrepareFunctionsLegacy(TM);
1099}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Expand Atomic instructions
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
return Result
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
#define T
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
const char * Msg
static Value * expandFMinimumMaximum(IRBuilderBase &Builder, bool IsMax, Value *X, Value *Y, FastMathFlags FMF)
static void lowerFunnelShifts(IntrinsicInst *FSHIntrinsic)
static std::string getAnnotation(Value *AnnoVal, Value *OptAnnoVal)
spirv prepare SPIRV prepare static false std::string lowerLLVMIntrinsicName(IntrinsicInst *II)
static bool lowerConstantMemSet(MemSetInst *MSI, const SPIRVSubtarget &STI)
static Value * fixZeroSign(IRBuilderBase &Builder, bool IsMax, Value *Res, Value *X, Value *Y)
static void lowerVectorReduceFMinimumMaximum(IntrinsicInst *II, SmallVector< Instruction * > &EraseFromParent)
static void lowerConstrainedFPCmpIntrinsic(ConstrainedFPCmpIntrinsic *ConstrainedCmpIntrinsic, SmallVector< Instruction * > &EraseFromParent)
static void lowerConstrainedFmuladd(IntrinsicInst *II, SmallVector< Instruction * > &EraseFromParent)
static void lowerPtrAnnotation(IntrinsicInst *II)
static bool lowerIntrinsicToFunction(IntrinsicInst *Intrinsic, const TargetTransformInfo &TTI)
static bool isAbortKHRBuiltin(const Function &F)
static SmallVector< Metadata * > parseAnnotation(Value *I, const std::string &Anno, LLVMContext &Ctx, Type *Int32Ty)
static void removeIncompatibleAttrs(T *V)
static std::string fixMultiOutputConstraintString(StringRef Constraints)
static void rewriteAbortKHRCall(CallInst *CI)
static void addFunctionTypeMutation(NamedMDNode *NMD, SmallVector< std::pair< int, Type * > > ChangedTys, StringRef Name, StringRef AsmConstraints="")
static bool toSpvLifetimeIntrinsic(IntrinsicInst *II, Intrinsic::ID NewID)
static void lowerExpectAssume(IntrinsicInst *II)
static void lowerFMinimumMaximumNum(IntrinsicInst *II, SmallVector< Instruction * > &EraseFromParent)
static void lowerFMinimumMaximum(IntrinsicInst *II, SmallVector< Instruction * > &EraseFromParent)
static Function * getOrCreateFunction(Module *M, Type *RetTy, ArrayRef< Type * > ArgTypes, StringRef Name)
#define SPIRV_WAS_AVAILABLE_EXTERNALLY_ATTR
Definition SPIRVUtils.h:556
This file contains some functions that are useful when dealing with strings.
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
BinaryOperator * Mul
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
Type * getParamByValType(unsigned ArgNo) const
Extract the byval type for a call or parameter.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
This class represents a function call, abstracting a target machine's calling convention.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Constrained floating point compare intrinsics.
LLVM_ABI FCmpInst::Predicate getPredicate() const
Diagnostic information for unsupported feature in backend.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noNaNs() const
Definition FMF.h:65
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
bool empty() const
Definition Function.h:853
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
arg_iterator arg_begin()
Definition Function.h:862
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:252
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
void setCallingConv(CallingConv::ID CC)
Definition Function.h:277
Argument * getArg(unsigned i) const
Definition Function.h:880
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
Module * getParent()
Get the module that this global value is contained inside of...
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1534
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
Definition IRBuilder.h:1194
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1441
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1513
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, MaybeAlign Align, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert a memset to the specified pointer and the specified value.
Definition IRBuilder.h:602
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Definition IRBuilder.h:1189
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
LLVM_ABI CallInst * CreateMemTransferInst(Intrinsic::ID IntrID, Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, Value *Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1594
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:486
Value * CreateURem(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1501
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
LLVM_ABI void LowerIntrinsicCall(CallInst *CI)
Replace a call to the specified intrinsic function.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
Value * getLength() const
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
MaybeAlign getDestAlign() const
bool isVolatile() const
Value * getValue() const
This class wraps the llvm.memset and llvm.memset.inline intrinsics.
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:105
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:332
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition Module.cpp:327
A tuple of MDNodes.
Definition Metadata.h:1806
Module * getParent()
Get the module that holds this named metadata collection.
Definition Metadata.h:1876
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
const SPIRVOptions & getCLOpts() const
bool canUseExtension(SPIRV::Extension::Extension E) const
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
Analysis pass providing the TargetTransformInfo.
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:314
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:512
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
Type * getElementType() const
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI bool isTargetIntrinsic(ID IID)
isTargetIntrinsic - Returns true if IID is an intrinsic specific to a certain target.
std::string lookupBuiltinNameHelper(StringRef DemangledCall, FPDecorationId *DecorationId)
Parses the name part of the demangled builtin call.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
bool sortBlocks(Function &F)
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI void ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V)
Replace all uses of an instruction (specified by BI) with a value, then remove and delete the origina...
LLVM_ABI void SplitString(StringRef Source, SmallVectorImpl< StringRef > &OutFragments, StringRef Delimiters=" \t\n\v\f\r")
SplitString - Split up the specified string according to the specified delimiters,...
Function * getOrCreateBackendServiceFunction(Module &M)
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2042
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
Definition Local.cpp:2593
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
TargetTransformInfo TTI
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1926
@ Add
Sum of integers.
constexpr unsigned BitWidth
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI void CloneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, CloneFunctionChangeType Changes, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc into NewFunc, transforming the old arguments into references to VMap values.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
LLVM_ABI void expandMemSetAsLoop(MemSetInst *MemSet, const TargetTransformInfo &TTI)
Expand MemSet as a loop according to the target's preferences.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool to_integer(StringRef S, N &Num, unsigned Base=0)
Convert the string S to an integer of the specified type using the radix Base. If Base is 0,...
ModulePass * createSPIRVPrepareFunctionsPass(const SPIRVTargetMachine &TM)
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111