1e5dd7070Spatrick //===------ CGGPUBuiltin.cpp - Codegen for GPU builtins -------------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // Generates code for built-in GPU calls which are not runtime-specific.
10e5dd7070Spatrick // (Runtime-specific codegen lives in programming model specific files.)
11e5dd7070Spatrick //
12e5dd7070Spatrick //===----------------------------------------------------------------------===//
13e5dd7070Spatrick
14e5dd7070Spatrick #include "CodeGenFunction.h"
15e5dd7070Spatrick #include "clang/Basic/Builtins.h"
16e5dd7070Spatrick #include "llvm/IR/DataLayout.h"
17e5dd7070Spatrick #include "llvm/IR/Instruction.h"
18e5dd7070Spatrick #include "llvm/Support/MathExtras.h"
19ec727ea7Spatrick #include "llvm/Transforms/Utils/AMDGPUEmitPrintf.h"
20e5dd7070Spatrick
21e5dd7070Spatrick using namespace clang;
22e5dd7070Spatrick using namespace CodeGen;
23e5dd7070Spatrick
24*12c85518Srobert namespace {
GetVprintfDeclaration(llvm::Module & M)25*12c85518Srobert llvm::Function *GetVprintfDeclaration(llvm::Module &M) {
26e5dd7070Spatrick llvm::Type *ArgTypes[] = {llvm::Type::getInt8PtrTy(M.getContext()),
27e5dd7070Spatrick llvm::Type::getInt8PtrTy(M.getContext())};
28e5dd7070Spatrick llvm::FunctionType *VprintfFuncType = llvm::FunctionType::get(
29e5dd7070Spatrick llvm::Type::getInt32Ty(M.getContext()), ArgTypes, false);
30e5dd7070Spatrick
31e5dd7070Spatrick if (auto *F = M.getFunction("vprintf")) {
32e5dd7070Spatrick // Our CUDA system header declares vprintf with the right signature, so
33e5dd7070Spatrick // nobody else should have been able to declare vprintf with a bogus
34e5dd7070Spatrick // signature.
35e5dd7070Spatrick assert(F->getFunctionType() == VprintfFuncType);
36e5dd7070Spatrick return F;
37e5dd7070Spatrick }
38e5dd7070Spatrick
39e5dd7070Spatrick // vprintf doesn't already exist; create a declaration and insert it into the
40e5dd7070Spatrick // module.
41e5dd7070Spatrick return llvm::Function::Create(
42e5dd7070Spatrick VprintfFuncType, llvm::GlobalVariable::ExternalLinkage, "vprintf", &M);
43e5dd7070Spatrick }
44e5dd7070Spatrick
GetOpenMPVprintfDeclaration(CodeGenModule & CGM)45*12c85518Srobert llvm::Function *GetOpenMPVprintfDeclaration(CodeGenModule &CGM) {
46*12c85518Srobert const char *Name = "__llvm_omp_vprintf";
47*12c85518Srobert llvm::Module &M = CGM.getModule();
48*12c85518Srobert llvm::Type *ArgTypes[] = {llvm::Type::getInt8PtrTy(M.getContext()),
49*12c85518Srobert llvm::Type::getInt8PtrTy(M.getContext()),
50*12c85518Srobert llvm::Type::getInt32Ty(M.getContext())};
51*12c85518Srobert llvm::FunctionType *VprintfFuncType = llvm::FunctionType::get(
52*12c85518Srobert llvm::Type::getInt32Ty(M.getContext()), ArgTypes, false);
53*12c85518Srobert
54*12c85518Srobert if (auto *F = M.getFunction(Name)) {
55*12c85518Srobert if (F->getFunctionType() != VprintfFuncType) {
56*12c85518Srobert CGM.Error(SourceLocation(),
57*12c85518Srobert "Invalid type declaration for __llvm_omp_vprintf");
58*12c85518Srobert return nullptr;
59*12c85518Srobert }
60*12c85518Srobert return F;
61*12c85518Srobert }
62*12c85518Srobert
63*12c85518Srobert return llvm::Function::Create(
64*12c85518Srobert VprintfFuncType, llvm::GlobalVariable::ExternalLinkage, Name, &M);
65*12c85518Srobert }
66*12c85518Srobert
67e5dd7070Spatrick // Transforms a call to printf into a call to the NVPTX vprintf syscall (which
68e5dd7070Spatrick // isn't particularly special; it's invoked just like a regular function).
69e5dd7070Spatrick // vprintf takes two args: A format string, and a pointer to a buffer containing
70e5dd7070Spatrick // the varargs.
71e5dd7070Spatrick //
72e5dd7070Spatrick // For example, the call
73e5dd7070Spatrick //
74e5dd7070Spatrick // printf("format string", arg1, arg2, arg3);
75e5dd7070Spatrick //
76e5dd7070Spatrick // is converted into something resembling
77e5dd7070Spatrick //
78e5dd7070Spatrick // struct Tmp {
79e5dd7070Spatrick // Arg1 a1;
80e5dd7070Spatrick // Arg2 a2;
81e5dd7070Spatrick // Arg3 a3;
82e5dd7070Spatrick // };
83e5dd7070Spatrick // char* buf = alloca(sizeof(Tmp));
84e5dd7070Spatrick // *(Tmp*)buf = {a1, a2, a3};
85e5dd7070Spatrick // vprintf("format string", buf);
86e5dd7070Spatrick //
87e5dd7070Spatrick // buf is aligned to the max of {alignof(Arg1), ...}. Furthermore, each of the
88e5dd7070Spatrick // args is itself aligned to its preferred alignment.
89e5dd7070Spatrick //
90e5dd7070Spatrick // Note that by the time this function runs, E's args have already undergone the
91e5dd7070Spatrick // standard C vararg promotion (short -> int, float -> double, etc.).
92e5dd7070Spatrick
93*12c85518Srobert std::pair<llvm::Value *, llvm::TypeSize>
packArgsIntoNVPTXFormatBuffer(CodeGenFunction * CGF,const CallArgList & Args)94*12c85518Srobert packArgsIntoNVPTXFormatBuffer(CodeGenFunction *CGF, const CallArgList &Args) {
95*12c85518Srobert const llvm::DataLayout &DL = CGF->CGM.getDataLayout();
96*12c85518Srobert llvm::LLVMContext &Ctx = CGF->CGM.getLLVMContext();
97*12c85518Srobert CGBuilderTy &Builder = CGF->Builder;
98e5dd7070Spatrick
99e5dd7070Spatrick // Construct and fill the args buffer that we'll pass to vprintf.
100e5dd7070Spatrick if (Args.size() <= 1) {
101*12c85518Srobert // If there are no args, pass a null pointer and size 0
102*12c85518Srobert llvm::Value * BufferPtr = llvm::ConstantPointerNull::get(llvm::Type::getInt8PtrTy(Ctx));
103*12c85518Srobert return {BufferPtr, llvm::TypeSize::Fixed(0)};
104e5dd7070Spatrick } else {
105e5dd7070Spatrick llvm::SmallVector<llvm::Type *, 8> ArgTypes;
106e5dd7070Spatrick for (unsigned I = 1, NumArgs = Args.size(); I < NumArgs; ++I)
107*12c85518Srobert ArgTypes.push_back(Args[I].getRValue(*CGF).getScalarVal()->getType());
108e5dd7070Spatrick
109e5dd7070Spatrick // Using llvm::StructType is correct only because printf doesn't accept
110e5dd7070Spatrick // aggregates. If we had to handle aggregates here, we'd have to manually
111e5dd7070Spatrick // compute the offsets within the alloca -- we wouldn't be able to assume
112e5dd7070Spatrick // that the alignment of the llvm type was the same as the alignment of the
113e5dd7070Spatrick // clang type.
114e5dd7070Spatrick llvm::Type *AllocaTy = llvm::StructType::create(ArgTypes, "printf_args");
115*12c85518Srobert llvm::Value *Alloca = CGF->CreateTempAlloca(AllocaTy);
116e5dd7070Spatrick
117e5dd7070Spatrick for (unsigned I = 1, NumArgs = Args.size(); I < NumArgs; ++I) {
118e5dd7070Spatrick llvm::Value *P = Builder.CreateStructGEP(AllocaTy, Alloca, I - 1);
119*12c85518Srobert llvm::Value *Arg = Args[I].getRValue(*CGF).getScalarVal();
120ec727ea7Spatrick Builder.CreateAlignedStore(Arg, P, DL.getPrefTypeAlign(Arg->getType()));
121e5dd7070Spatrick }
122*12c85518Srobert llvm::Value *BufferPtr =
123*12c85518Srobert Builder.CreatePointerCast(Alloca, llvm::Type::getInt8PtrTy(Ctx));
124*12c85518Srobert return {BufferPtr, DL.getTypeAllocSize(AllocaTy)};
125*12c85518Srobert }
126e5dd7070Spatrick }
127e5dd7070Spatrick
containsNonScalarVarargs(CodeGenFunction * CGF,CallArgList Args)128*12c85518Srobert bool containsNonScalarVarargs(CodeGenFunction *CGF, CallArgList Args) {
129*12c85518Srobert return llvm::any_of(llvm::drop_begin(Args), [&](const CallArg &A) {
130*12c85518Srobert return !A.getRValue(*CGF).isScalar();
131*12c85518Srobert });
132e5dd7070Spatrick }
133ec727ea7Spatrick
EmitDevicePrintfCallExpr(const CallExpr * E,CodeGenFunction * CGF,llvm::Function * Decl,bool WithSizeArg)134*12c85518Srobert RValue EmitDevicePrintfCallExpr(const CallExpr *E, CodeGenFunction *CGF,
135*12c85518Srobert llvm::Function *Decl, bool WithSizeArg) {
136*12c85518Srobert CodeGenModule &CGM = CGF->CGM;
137*12c85518Srobert CGBuilderTy &Builder = CGF->Builder;
138*12c85518Srobert assert(E->getBuiltinCallee() == Builtin::BIprintf);
139*12c85518Srobert assert(E->getNumArgs() >= 1); // printf always has at least one arg.
140*12c85518Srobert
141*12c85518Srobert // Uses the same format as nvptx for the argument packing, but also passes
142*12c85518Srobert // an i32 for the total size of the passed pointer
143*12c85518Srobert CallArgList Args;
144*12c85518Srobert CGF->EmitCallArgs(Args,
145*12c85518Srobert E->getDirectCallee()->getType()->getAs<FunctionProtoType>(),
146*12c85518Srobert E->arguments(), E->getDirectCallee(),
147*12c85518Srobert /* ParamsToSkip = */ 0);
148*12c85518Srobert
149*12c85518Srobert // We don't know how to emit non-scalar varargs.
150*12c85518Srobert if (containsNonScalarVarargs(CGF, Args)) {
151*12c85518Srobert CGM.ErrorUnsupported(E, "non-scalar arg to printf");
152*12c85518Srobert return RValue::get(llvm::ConstantInt::get(CGF->IntTy, 0));
153*12c85518Srobert }
154*12c85518Srobert
155*12c85518Srobert auto r = packArgsIntoNVPTXFormatBuffer(CGF, Args);
156*12c85518Srobert llvm::Value *BufferPtr = r.first;
157*12c85518Srobert
158*12c85518Srobert llvm::SmallVector<llvm::Value *, 3> Vec = {
159*12c85518Srobert Args[0].getRValue(*CGF).getScalarVal(), BufferPtr};
160*12c85518Srobert if (WithSizeArg) {
161*12c85518Srobert // Passing > 32bit of data as a local alloca doesn't work for nvptx or
162*12c85518Srobert // amdgpu
163*12c85518Srobert llvm::Constant *Size =
164*12c85518Srobert llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGM.getLLVMContext()),
165*12c85518Srobert static_cast<uint32_t>(r.second.getFixedValue()));
166*12c85518Srobert
167*12c85518Srobert Vec.push_back(Size);
168*12c85518Srobert }
169*12c85518Srobert return RValue::get(Builder.CreateCall(Decl, Vec));
170*12c85518Srobert }
171*12c85518Srobert } // namespace
172*12c85518Srobert
EmitNVPTXDevicePrintfCallExpr(const CallExpr * E)173*12c85518Srobert RValue CodeGenFunction::EmitNVPTXDevicePrintfCallExpr(const CallExpr *E) {
174*12c85518Srobert assert(getTarget().getTriple().isNVPTX());
175*12c85518Srobert return EmitDevicePrintfCallExpr(
176*12c85518Srobert E, this, GetVprintfDeclaration(CGM.getModule()), false);
177*12c85518Srobert }
178*12c85518Srobert
EmitAMDGPUDevicePrintfCallExpr(const CallExpr * E)179*12c85518Srobert RValue CodeGenFunction::EmitAMDGPUDevicePrintfCallExpr(const CallExpr *E) {
180ec727ea7Spatrick assert(getTarget().getTriple().getArch() == llvm::Triple::amdgcn);
181ec727ea7Spatrick assert(E->getBuiltinCallee() == Builtin::BIprintf ||
182ec727ea7Spatrick E->getBuiltinCallee() == Builtin::BI__builtin_printf);
183ec727ea7Spatrick assert(E->getNumArgs() >= 1); // printf always has at least one arg.
184ec727ea7Spatrick
185ec727ea7Spatrick CallArgList CallArgs;
186ec727ea7Spatrick EmitCallArgs(CallArgs,
187ec727ea7Spatrick E->getDirectCallee()->getType()->getAs<FunctionProtoType>(),
188ec727ea7Spatrick E->arguments(), E->getDirectCallee(),
189ec727ea7Spatrick /* ParamsToSkip = */ 0);
190ec727ea7Spatrick
191ec727ea7Spatrick SmallVector<llvm::Value *, 8> Args;
192ec727ea7Spatrick for (auto A : CallArgs) {
193ec727ea7Spatrick // We don't know how to emit non-scalar varargs.
194ec727ea7Spatrick if (!A.getRValue(*this).isScalar()) {
195ec727ea7Spatrick CGM.ErrorUnsupported(E, "non-scalar arg to printf");
196ec727ea7Spatrick return RValue::get(llvm::ConstantInt::get(IntTy, -1));
197ec727ea7Spatrick }
198ec727ea7Spatrick
199ec727ea7Spatrick llvm::Value *Arg = A.getRValue(*this).getScalarVal();
200ec727ea7Spatrick Args.push_back(Arg);
201ec727ea7Spatrick }
202ec727ea7Spatrick
203ec727ea7Spatrick llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
204ec727ea7Spatrick IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
205ec727ea7Spatrick auto Printf = llvm::emitAMDGPUPrintfCall(IRB, Args);
206ec727ea7Spatrick Builder.SetInsertPoint(IRB.GetInsertBlock(), IRB.GetInsertPoint());
207ec727ea7Spatrick return RValue::get(Printf);
208ec727ea7Spatrick }
209*12c85518Srobert
EmitOpenMPDevicePrintfCallExpr(const CallExpr * E)210*12c85518Srobert RValue CodeGenFunction::EmitOpenMPDevicePrintfCallExpr(const CallExpr *E) {
211*12c85518Srobert assert(getTarget().getTriple().isNVPTX() ||
212*12c85518Srobert getTarget().getTriple().isAMDGCN());
213*12c85518Srobert return EmitDevicePrintfCallExpr(E, this, GetOpenMPVprintfDeclaration(CGM),
214*12c85518Srobert true);
215*12c85518Srobert }
216