LLVM 22.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 "SPIRVSubtarget.h"
23#include "SPIRVTargetMachine.h"
24#include "SPIRVUtils.h"
28#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/IntrinsicsSPIRV.h"
36#include <regex>
37
38using namespace llvm;
39
40namespace {
41
42class SPIRVPrepareFunctions : public ModulePass {
43 const SPIRVTargetMachine &TM;
44 bool substituteIntrinsicCalls(Function *F);
45 Function *removeAggregateTypesFromSignature(Function *F);
46 bool removeAggregateTypesFromCalls(Function *F);
47
48public:
49 static char ID;
50 SPIRVPrepareFunctions(const SPIRVTargetMachine &TM)
51 : ModulePass(ID), TM(TM) {}
52
53 bool runOnModule(Module &M) override;
54
55 StringRef getPassName() const override { return "SPIRV prepare functions"; }
56
57 void getAnalysisUsage(AnalysisUsage &AU) const override {
58 ModulePass::getAnalysisUsage(AU);
59 }
60};
61
62static cl::list<std::string> SPVAllowUnknownIntrinsics(
63 "spv-allow-unknown-intrinsics", cl::CommaSeparated,
64 cl::desc("Emit unknown intrinsics as calls to external functions. A "
65 "comma-separated input list of intrinsic prefixes must be "
66 "provided, and only intrinsics carrying a listed prefix get "
67 "emitted as described."),
68 cl::value_desc("intrinsic_prefix_0,intrinsic_prefix_1"), cl::ValueOptional);
69} // namespace
70
71char SPIRVPrepareFunctions::ID = 0;
72
73INITIALIZE_PASS(SPIRVPrepareFunctions, "prepare-functions",
74 "SPIRV prepare functions", false, false)
75
76static std::string lowerLLVMIntrinsicName(IntrinsicInst *II) {
77 Function *IntrinsicFunc = II->getCalledFunction();
78 assert(IntrinsicFunc && "Missing function");
79 std::string FuncName = IntrinsicFunc->getName().str();
80 llvm::replace(FuncName, '.', '_');
81 FuncName = "spirv." + FuncName;
82 return FuncName;
83}
84
86 ArrayRef<Type *> ArgTypes,
87 StringRef Name) {
88 FunctionType *FT = FunctionType::get(RetTy, ArgTypes, false);
89 Function *F = M->getFunction(Name);
90 if (F && F->getFunctionType() == FT)
91 return F;
93 if (F)
94 NewF->setDSOLocal(F->isDSOLocal());
96 return NewF;
97}
98
100 // For @llvm.memset.* intrinsic cases with constant value and length arguments
101 // are emulated via "storing" a constant array to the destination. For other
102 // cases we wrap the intrinsic in @spirv.llvm_memset_* function and expand the
103 // intrinsic to a loop via expandMemSetAsLoop().
104 if (auto *MSI = dyn_cast<MemSetInst>(Intrinsic))
105 if (isa<Constant>(MSI->getValue()) && isa<ConstantInt>(MSI->getLength()))
106 return false; // It is handled later using OpCopyMemorySized.
107
108 Module *M = Intrinsic->getModule();
109 std::string FuncName = lowerLLVMIntrinsicName(Intrinsic);
110 if (Intrinsic->isVolatile())
111 FuncName += ".volatile";
112 // Redirect @llvm.intrinsic.* call to @spirv.llvm_intrinsic_*
113 Function *F = M->getFunction(FuncName);
114 if (F) {
115 Intrinsic->setCalledFunction(F);
116 return true;
117 }
118 // TODO copy arguments attributes: nocapture writeonly.
119 FunctionCallee FC =
120 M->getOrInsertFunction(FuncName, Intrinsic->getFunctionType());
121 auto IntrinsicID = Intrinsic->getIntrinsicID();
122 Intrinsic->setCalledFunction(FC);
123
124 F = dyn_cast<Function>(FC.getCallee());
125 assert(F && "Callee must be a function");
126
127 switch (IntrinsicID) {
128 case Intrinsic::memset: {
129 auto *MSI = static_cast<MemSetInst *>(Intrinsic);
130 Argument *Dest = F->getArg(0);
131 Argument *Val = F->getArg(1);
132 Argument *Len = F->getArg(2);
133 Argument *IsVolatile = F->getArg(3);
134 Dest->setName("dest");
135 Val->setName("val");
136 Len->setName("len");
137 IsVolatile->setName("isvolatile");
138 BasicBlock *EntryBB = BasicBlock::Create(M->getContext(), "entry", F);
139 IRBuilder<> IRB(EntryBB);
140 auto *MemSet = IRB.CreateMemSet(Dest, Val, Len, MSI->getDestAlign(),
141 MSI->isVolatile());
142 IRB.CreateRetVoid();
144 MemSet->eraseFromParent();
145 break;
146 }
147 case Intrinsic::bswap: {
148 BasicBlock *EntryBB = BasicBlock::Create(M->getContext(), "entry", F);
149 IRBuilder<> IRB(EntryBB);
150 auto *BSwap = IRB.CreateIntrinsic(Intrinsic::bswap, Intrinsic->getType(),
151 F->getArg(0));
152 IRB.CreateRet(BSwap);
153 IntrinsicLowering IL(M->getDataLayout());
154 IL.LowerIntrinsicCall(BSwap);
155 break;
156 }
157 default:
158 break;
159 }
160 return true;
161}
162
163static std::string getAnnotation(Value *AnnoVal, Value *OptAnnoVal) {
164 if (auto *Ref = dyn_cast_or_null<GetElementPtrInst>(AnnoVal))
165 AnnoVal = Ref->getOperand(0);
166 if (auto *Ref = dyn_cast_or_null<BitCastInst>(OptAnnoVal))
167 OptAnnoVal = Ref->getOperand(0);
168
169 std::string Anno;
170 if (auto *C = dyn_cast_or_null<Constant>(AnnoVal)) {
171 StringRef Str;
172 if (getConstantStringInfo(C, Str))
173 Anno = Str;
174 }
175 // handle optional annotation parameter in a way that Khronos Translator do
176 // (collect integers wrapped in a struct)
177 if (auto *C = dyn_cast_or_null<Constant>(OptAnnoVal);
178 C && C->getNumOperands()) {
179 Value *MaybeStruct = C->getOperand(0);
180 if (auto *Struct = dyn_cast<ConstantStruct>(MaybeStruct)) {
181 for (unsigned I = 0, E = Struct->getNumOperands(); I != E; ++I) {
182 if (auto *CInt = dyn_cast<ConstantInt>(Struct->getOperand(I)))
183 Anno += (I == 0 ? ": " : ", ") +
184 std::to_string(CInt->getType()->getIntegerBitWidth() == 1
185 ? CInt->getZExtValue()
186 : CInt->getSExtValue());
187 }
188 } else if (auto *Struct = dyn_cast<ConstantAggregateZero>(MaybeStruct)) {
189 // { i32 i32 ... } zeroinitializer
190 for (unsigned I = 0, E = Struct->getType()->getStructNumElements();
191 I != E; ++I)
192 Anno += I == 0 ? ": 0" : ", 0";
193 }
194 }
195 return Anno;
196}
197
199 const std::string &Anno,
200 LLVMContext &Ctx,
201 Type *Int32Ty) {
202 // Try to parse the annotation string according to the following rules:
203 // annotation := ({kind} | {kind:value,value,...})+
204 // kind := number
205 // value := number | string
206 static const std::regex R(
207 "\\{(\\d+)(?:[:,](\\d+|\"[^\"]*\")(?:,(\\d+|\"[^\"]*\"))*)?\\}");
209 int Pos = 0;
210 for (std::sregex_iterator
211 It = std::sregex_iterator(Anno.begin(), Anno.end(), R),
212 ItEnd = std::sregex_iterator();
213 It != ItEnd; ++It) {
214 if (It->position() != Pos)
216 Pos = It->position() + It->length();
217 std::smatch Match = *It;
219 for (std::size_t i = 1; i < Match.size(); ++i) {
220 std::ssub_match SMatch = Match[i];
221 std::string Item = SMatch.str();
222 if (Item.length() == 0)
223 break;
224 if (Item[0] == '"') {
225 Item = Item.substr(1, Item.length() - 2);
226 // Acceptable format of the string snippet is:
227 static const std::regex RStr("^(\\d+)(?:,(\\d+))*$");
228 if (std::smatch MatchStr; std::regex_match(Item, MatchStr, RStr)) {
229 for (std::size_t SubIdx = 1; SubIdx < MatchStr.size(); ++SubIdx)
230 if (std::string SubStr = MatchStr[SubIdx].str(); SubStr.length())
232 ConstantInt::get(Int32Ty, std::stoi(SubStr))));
233 } else {
234 MDsItem.push_back(MDString::get(Ctx, Item));
235 }
236 } else if (int32_t Num; llvm::to_integer(StringRef(Item), Num, 10)) {
237 MDsItem.push_back(
238 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Num)));
239 } else {
240 MDsItem.push_back(MDString::get(Ctx, Item));
241 }
242 }
243 if (MDsItem.size() == 0)
245 MDs.push_back(MDNode::get(Ctx, MDsItem));
246 }
247 return Pos == static_cast<int>(Anno.length()) ? std::move(MDs)
249}
250
252 LLVMContext &Ctx = II->getContext();
254
255 // Retrieve an annotation string from arguments.
256 Value *PtrArg = nullptr;
257 if (auto *BI = dyn_cast<BitCastInst>(II->getArgOperand(0)))
258 PtrArg = BI->getOperand(0);
259 else
260 PtrArg = II->getOperand(0);
261 std::string Anno =
262 getAnnotation(II->getArgOperand(1),
263 4 < II->arg_size() ? II->getArgOperand(4) : nullptr);
264
265 // Parse the annotation.
267
268 // If the annotation string is not parsed successfully we don't know the
269 // format used and output it as a general UserSemantic decoration.
270 // Otherwise MDs is a Metadata tuple (a decoration list) in the format
271 // expected by `spirv.Decorations`.
272 if (MDs.size() == 0) {
273 auto UserSemantic = ConstantAsMetadata::get(ConstantInt::get(
274 Int32Ty, static_cast<uint32_t>(SPIRV::Decoration::UserSemantic)));
275 MDs.push_back(MDNode::get(Ctx, {UserSemantic, MDString::get(Ctx, Anno)}));
276 }
277
278 // Build the internal intrinsic function.
279 IRBuilder<> IRB(II->getParent());
280 IRB.SetInsertPoint(II);
281 IRB.CreateIntrinsic(
282 Intrinsic::spv_assign_decoration, {PtrArg->getType()},
283 {PtrArg, MetadataAsValue::get(Ctx, MDNode::get(Ctx, MDs))});
284 II->replaceAllUsesWith(II->getOperand(0));
285}
286
287static void lowerFunnelShifts(IntrinsicInst *FSHIntrinsic) {
288 // Get a separate function - otherwise, we'd have to rework the CFG of the
289 // current one. Then simply replace the intrinsic uses with a call to the new
290 // function.
291 // Generate LLVM IR for i* @spirv.llvm_fsh?_i* (i* %a, i* %b, i* %c)
292 Module *M = FSHIntrinsic->getModule();
293 FunctionType *FSHFuncTy = FSHIntrinsic->getFunctionType();
294 Type *FSHRetTy = FSHFuncTy->getReturnType();
295 const std::string FuncName = lowerLLVMIntrinsicName(FSHIntrinsic);
296 Function *FSHFunc =
297 getOrCreateFunction(M, FSHRetTy, FSHFuncTy->params(), FuncName);
298
299 if (!FSHFunc->empty()) {
300 FSHIntrinsic->setCalledFunction(FSHFunc);
301 return;
302 }
303 BasicBlock *RotateBB = BasicBlock::Create(M->getContext(), "rotate", FSHFunc);
304 IRBuilder<> IRB(RotateBB);
305 Type *Ty = FSHFunc->getReturnType();
306 // Build the actual funnel shift rotate logic.
307 // In the comments, "int" is used interchangeably with "vector of int
308 // elements".
310 Type *IntTy = VectorTy ? VectorTy->getElementType() : Ty;
311 unsigned BitWidth = IntTy->getIntegerBitWidth();
312 ConstantInt *BitWidthConstant = IRB.getInt({BitWidth, BitWidth});
313 Value *BitWidthForInsts =
314 VectorTy
315 ? IRB.CreateVectorSplat(VectorTy->getNumElements(), BitWidthConstant)
316 : BitWidthConstant;
317 Value *RotateModVal =
318 IRB.CreateURem(/*Rotate*/ FSHFunc->getArg(2), BitWidthForInsts);
319 Value *FirstShift = nullptr, *SecShift = nullptr;
320 if (FSHIntrinsic->getIntrinsicID() == Intrinsic::fshr) {
321 // Shift the less significant number right, the "rotate" number of bits
322 // will be 0-filled on the left as a result of this regular shift.
323 FirstShift = IRB.CreateLShr(FSHFunc->getArg(1), RotateModVal);
324 } else {
325 // Shift the more significant number left, the "rotate" number of bits
326 // will be 0-filled on the right as a result of this regular shift.
327 FirstShift = IRB.CreateShl(FSHFunc->getArg(0), RotateModVal);
328 }
329 // We want the "rotate" number of the more significant int's LSBs (MSBs) to
330 // occupy the leftmost (rightmost) "0 space" left by the previous operation.
331 // Therefore, subtract the "rotate" number from the integer bitsize...
332 Value *SubRotateVal = IRB.CreateSub(BitWidthForInsts, RotateModVal);
333 if (FSHIntrinsic->getIntrinsicID() == Intrinsic::fshr) {
334 // ...and left-shift the more significant int by this number, zero-filling
335 // the LSBs.
336 SecShift = IRB.CreateShl(FSHFunc->getArg(0), SubRotateVal);
337 } else {
338 // ...and right-shift the less significant int by this number, zero-filling
339 // the MSBs.
340 SecShift = IRB.CreateLShr(FSHFunc->getArg(1), SubRotateVal);
341 }
342 // A simple binary addition of the shifted ints yields the final result.
343 IRB.CreateRet(IRB.CreateOr(FirstShift, SecShift));
344
345 FSHIntrinsic->setCalledFunction(FSHFunc);
346}
347
349 ConstrainedFPCmpIntrinsic *ConstrainedCmpIntrinsic,
350 SmallVector<Instruction *> &EraseFromParent) {
351 if (!ConstrainedCmpIntrinsic)
352 return;
353 // Extract the floating-point values being compared
354 Value *LHS = ConstrainedCmpIntrinsic->getArgOperand(0);
355 Value *RHS = ConstrainedCmpIntrinsic->getArgOperand(1);
356 FCmpInst::Predicate Pred = ConstrainedCmpIntrinsic->getPredicate();
357 IRBuilder<> Builder(ConstrainedCmpIntrinsic);
358 Value *FCmp = Builder.CreateFCmp(Pred, LHS, RHS);
359 ConstrainedCmpIntrinsic->replaceAllUsesWith(FCmp);
360 EraseFromParent.push_back(dyn_cast<Instruction>(ConstrainedCmpIntrinsic));
361}
362
364 // If we cannot use the SPV_KHR_expect_assume extension, then we need to
365 // ignore the intrinsic and move on. It should be removed later on by LLVM.
366 // Otherwise we should lower the intrinsic to the corresponding SPIR-V
367 // instruction.
368 // For @llvm.assume we have OpAssumeTrueKHR.
369 // For @llvm.expect we have OpExpectKHR.
370 //
371 // We need to lower this into a builtin and then the builtin into a SPIR-V
372 // instruction.
373 if (II->getIntrinsicID() == Intrinsic::assume) {
375 II->getModule(), Intrinsic::SPVIntrinsics::spv_assume);
376 II->setCalledFunction(F);
377 } else if (II->getIntrinsicID() == Intrinsic::expect) {
379 II->getModule(), Intrinsic::SPVIntrinsics::spv_expect,
380 {II->getOperand(0)->getType()});
381 II->setCalledFunction(F);
382 } else {
383 llvm_unreachable("Unknown intrinsic");
384 }
385}
386
388 IRBuilder<> Builder(II);
389 auto *Alloca = cast<AllocaInst>(II->getArgOperand(0));
390 std::optional<TypeSize> Size =
391 Alloca->getAllocationSize(Alloca->getDataLayout());
392 Value *SizeVal = Builder.getInt64(Size ? *Size : -1);
393 Builder.CreateIntrinsic(NewID, Alloca->getType(),
394 {SizeVal, II->getArgOperand(0)});
395 II->eraseFromParent();
396 return true;
397}
398
399// Substitutes calls to LLVM intrinsics with either calls to SPIR-V intrinsics
400// or calls to proper generated functions. Returns True if F was modified.
401bool SPIRVPrepareFunctions::substituteIntrinsicCalls(Function *F) {
402 bool Changed = false;
403 const SPIRVSubtarget &STI = TM.getSubtarget<SPIRVSubtarget>(*F);
404 SmallVector<Instruction *> EraseFromParent;
405 for (BasicBlock &BB : *F) {
406 for (Instruction &I : make_early_inc_range(BB)) {
407 auto Call = dyn_cast<CallInst>(&I);
408 if (!Call)
409 continue;
411 if (!CF || !CF->isIntrinsic())
412 continue;
413 auto *II = cast<IntrinsicInst>(Call);
414 switch (II->getIntrinsicID()) {
415 case Intrinsic::memset:
416 case Intrinsic::bswap:
418 break;
419 case Intrinsic::fshl:
420 case Intrinsic::fshr:
422 Changed = true;
423 break;
424 case Intrinsic::assume:
425 case Intrinsic::expect:
426 if (STI.canUseExtension(SPIRV::Extension::SPV_KHR_expect_assume))
428 Changed = true;
429 break;
430 case Intrinsic::lifetime_start:
431 if (!STI.isShader()) {
433 II, Intrinsic::SPVIntrinsics::spv_lifetime_start);
434 } else {
435 II->eraseFromParent();
436 Changed = true;
437 }
438 break;
439 case Intrinsic::lifetime_end:
440 if (!STI.isShader()) {
442 II, Intrinsic::SPVIntrinsics::spv_lifetime_end);
443 } else {
444 II->eraseFromParent();
445 Changed = true;
446 }
447 break;
448 case Intrinsic::ptr_annotation:
450 Changed = true;
451 break;
452 case Intrinsic::experimental_constrained_fcmp:
453 case Intrinsic::experimental_constrained_fcmps:
455 EraseFromParent);
456 Changed = true;
457 break;
458 default:
459 if (TM.getTargetTriple().getVendor() == Triple::AMD ||
460 any_of(SPVAllowUnknownIntrinsics, [II](auto &&Prefix) {
461 if (Prefix.empty())
462 return false;
463 return II->getCalledFunction()->getName().starts_with(Prefix);
464 }))
466 break;
467 }
468 }
469 }
470 for (auto *I : EraseFromParent)
471 I->eraseFromParent();
472 return Changed;
473}
474
475static void
477 SmallVector<std::pair<int, Type *>> ChangedTys,
478 StringRef Name) {
479
480 LLVMContext &Ctx = NMD->getParent()->getContext();
481 Type *I32Ty = IntegerType::getInt32Ty(Ctx);
482
484 MDArgs.push_back(MDString::get(Ctx, Name));
485 transform(ChangedTys, std::back_inserter(MDArgs), [=, &Ctx](auto &&CTy) {
486 return MDNode::get(
487 Ctx, {ConstantAsMetadata::get(ConstantInt::get(I32Ty, CTy.first, true)),
489 });
490 NMD->addOperand(MDNode::get(Ctx, MDArgs));
491}
492// Returns F if aggregate argument/return types are not present or cloned F
493// function with the types replaced by i32 types. The change in types is
494// noted in 'spv.cloned_funcs' metadata for later restoration.
495Function *
496SPIRVPrepareFunctions::removeAggregateTypesFromSignature(Function *F) {
497 bool IsRetAggr = F->getReturnType()->isAggregateType();
498 // Allow intrinsics with aggregate return type to reach GlobalISel
499 if (F->isIntrinsic() && IsRetAggr)
500 return F;
501
502 IRBuilder<> B(F->getContext());
503
504 bool HasAggrArg = llvm::any_of(F->args(), [](Argument &Arg) {
505 return Arg.getType()->isAggregateType();
506 });
507 bool DoClone = IsRetAggr || HasAggrArg;
508 if (!DoClone)
509 return F;
510 SmallVector<std::pair<int, Type *>, 4> ChangedTypes;
511 Type *RetType = IsRetAggr ? B.getInt32Ty() : F->getReturnType();
512 if (IsRetAggr)
513 ChangedTypes.push_back(std::pair<int, Type *>(-1, F->getReturnType()));
514 SmallVector<Type *, 4> ArgTypes;
515 for (const auto &Arg : F->args()) {
516 if (Arg.getType()->isAggregateType()) {
517 ArgTypes.push_back(B.getInt32Ty());
518 ChangedTypes.push_back(
519 std::pair<int, Type *>(Arg.getArgNo(), Arg.getType()));
520 } else
521 ArgTypes.push_back(Arg.getType());
522 }
523 FunctionType *NewFTy =
524 FunctionType::get(RetType, ArgTypes, F->getFunctionType()->isVarArg());
525 Function *NewF =
526 Function::Create(NewFTy, F->getLinkage(), F->getAddressSpace(),
527 F->getName(), F->getParent());
528
530 auto NewFArgIt = NewF->arg_begin();
531 for (auto &Arg : F->args()) {
532 StringRef ArgName = Arg.getName();
533 NewFArgIt->setName(ArgName);
534 VMap[&Arg] = &(*NewFArgIt++);
535 }
537
538 CloneFunctionInto(NewF, F, VMap, CloneFunctionChangeType::LocalChangesOnly,
539 Returns);
540 NewF->takeName(F);
541
543 NewF->getParent()->getOrInsertNamedMetadata("spv.cloned_funcs"),
544 std::move(ChangedTypes), NewF->getName());
545
546 for (auto *U : make_early_inc_range(F->users())) {
547 if (CallInst *CI;
548 (CI = dyn_cast<CallInst>(U)) && CI->getCalledFunction() == F)
549 CI->mutateFunctionType(NewF->getFunctionType());
550 if (auto *C = dyn_cast<Constant>(U))
551 C->handleOperandChange(F, NewF);
552 else
553 U->replaceUsesOfWith(F, NewF);
554 }
555
556 // register the mutation
557 if (RetType != F->getReturnType())
558 TM.getSubtarget<SPIRVSubtarget>(*F).getSPIRVGlobalRegistry()->addMutated(
559 NewF, F->getReturnType());
560 return NewF;
561}
562
563// Mutates indirect callsites iff if aggregate argument/return types are present
564// with the types replaced by i32 types. The change in types is noted in
565// 'spv.mutated_callsites' metadata for later restoration.
566bool SPIRVPrepareFunctions::removeAggregateTypesFromCalls(Function *F) {
567 if (F->isDeclaration() || F->isIntrinsic())
568 return false;
569
571 for (auto &&I : instructions(F)) {
572 if (auto *CB = dyn_cast<CallBase>(&I)) {
573 if (!CB->getCalledOperand() || CB->getCalledFunction())
574 continue;
575 if (CB->getType()->isAggregateType() ||
576 any_of(CB->args(),
577 [](auto &&Arg) { return Arg->getType()->isAggregateType(); }))
578 Calls.emplace_back(CB, nullptr);
579 }
580 }
581
582 if (Calls.empty())
583 return false;
584
585 IRBuilder<> B(F->getContext());
586
587 for (auto &&[CB, NewFnTy] : Calls) {
589 SmallVector<Type *> NewArgTypes;
590
591 Type *RetTy = CB->getType();
592 if (RetTy->isAggregateType()) {
593 ChangedTypes.emplace_back(-1, RetTy);
594 RetTy = B.getInt32Ty();
595 }
596
597 for (auto &&Arg : CB->args()) {
598 if (Arg->getType()->isAggregateType()) {
599 NewArgTypes.push_back(B.getInt32Ty());
600 ChangedTypes.emplace_back(Arg.getOperandNo(), Arg->getType());
601 } else {
602 NewArgTypes.push_back(Arg->getType());
603 }
604 }
605 NewFnTy = FunctionType::get(RetTy, NewArgTypes,
606 CB->getFunctionType()->isVarArg());
607
608 if (!CB->hasName())
609 CB->setName("spv.mutated_callsite." + F->getName());
610 else
611 CB->setName("spv.named_mutated_callsite." + F->getName() + "." +
612 CB->getName());
613
615 F->getParent()->getOrInsertNamedMetadata("spv.mutated_callsites"),
616 std::move(ChangedTypes), CB->getName());
617 }
618
619 for (auto &&[CB, NewFTy] : Calls) {
620 if (NewFTy->getReturnType() != CB->getType())
621 TM.getSubtarget<SPIRVSubtarget>(*F).getSPIRVGlobalRegistry()->addMutated(
622 CB, CB->getType());
623 CB->mutateFunctionType(NewFTy);
624 }
625
626 return true;
627}
628
629bool SPIRVPrepareFunctions::runOnModule(Module &M) {
630 bool Changed = false;
631 for (Function &F : M) {
632 Changed |= substituteIntrinsicCalls(&F);
633 Changed |= sortBlocks(F);
634 Changed |= removeAggregateTypesFromCalls(&F);
635 }
636
637 std::vector<Function *> FuncsWorklist;
638 for (auto &F : M)
639 FuncsWorklist.push_back(&F);
640
641 for (auto *F : FuncsWorklist) {
642 Function *NewF = removeAggregateTypesFromSignature(F);
643
644 if (NewF != F) {
645 F->eraseFromParent();
646 Changed = true;
647 }
648 }
649 return Changed;
650}
651
652ModulePass *
654 return new SPIRVPrepareFunctions(TM);
655}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Expand Atomic instructions
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static void lowerFunnelShifts(IntrinsicInst *FSHIntrinsic)
static std::string getAnnotation(Value *AnnoVal, Value *OptAnnoVal)
static bool lowerIntrinsicToFunction(IntrinsicInst *Intrinsic)
static void lowerConstrainedFPCmpIntrinsic(ConstrainedFPCmpIntrinsic *ConstrainedCmpIntrinsic, SmallVector< Instruction * > &EraseFromParent)
static void lowerPtrAnnotation(IntrinsicInst *II)
static SmallVector< Metadata * > parseAnnotation(Value *I, const std::string &Anno, LLVMContext &Ctx, Type *Int32Ty)
static bool toSpvLifetimeIntrinsic(IntrinsicInst *II, Intrinsic::ID NewID)
static void lowerExpectAssume(IntrinsicInst *II)
static void addFunctionTypeMutation(NamedMDNode *NMD, SmallVector< std::pair< int, Type * > > ChangedTys, StringRef Name)
static Function * getOrCreateFunction(Module *M, Type *RetTy, ArrayRef< Type * > ArgTypes, StringRef Name)
This file contains some functions that are useful when dealing with strings.
Value * RHS
Value * LHS
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:536
This is the shared class of boolean and integer constants.
Definition Constants.h:87
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
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:166
bool empty() const
Definition Function.h:857
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:209
arg_iterator arg_begin()
Definition Function.h:866
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:249
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:214
void setCallingConv(CallingConv::ID CC)
Definition Function.h:274
Argument * getArg(unsigned i) const
Definition Function.h:884
Module * getParent()
Get the module that this global value is contained inside of...
void setDSOLocal(bool Local)
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
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:1513
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
Definition IRBuilder.h:1172
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1420
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1492
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:630
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Definition IRBuilder.h:1167
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:207
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1573
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:538
Value * CreateURem(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1480
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
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:68
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1569
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:608
This class wraps the llvm.memset and llvm.memset.inline intrinsics.
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:104
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:285
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition Module.cpp:303
A tuple of MDNodes.
Definition Metadata.h:1757
Module * getParent()
Get the module that holds this named metadata collection.
Definition Metadata.h:1827
LLVM_ABI void addOperand(MDNode *M)
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:225
const Triple & getTargetTriple() const
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
VendorType getVendor() const
Get the parsed vendor type of this triple.
Definition Triple.h:419
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:296
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:304
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:503
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:546
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
Type * getElementType() const
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
FunctionAddr VTableAddr uintptr_t uintptr_t Int32Ty
Definition InstrProf.h:296
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:632
bool sortBlocks(Function &F)
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:1980
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:1744
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
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
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:1872
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
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)
LLVM_ABI void expandMemSetAsLoop(MemSetInst *MemSet)
Expand MemSet as a loop. MemSet is not deleted.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:867