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