clang 24.0.0git
SemaCUDA.h
Go to the documentation of this file.
1//===----- SemaCUDA.h ----- Semantic Analysis for CUDA constructs ---------===//
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/// \file
9/// This file declares semantic analysis for CUDA constructs.
10///
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_SEMA_SEMACUDA_H
14#define LLVM_CLANG_SEMA_SEMACUDA_H
15
16#include "clang/AST/ASTFwd.h"
19#include "clang/Basic/Cuda.h"
20#include "clang/Basic/LLVM.h"
22#include "clang/Sema/Lookup.h"
24#include "clang/Sema/SemaBase.h"
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/DenseMapInfo.h"
27#include "llvm/ADT/DenseSet.h"
28#include "llvm/ADT/Hashing.h"
29#include "llvm/ADT/SmallVector.h"
30#include <string>
31#include <utility>
32
33namespace clang {
34namespace sema {
35class Capture;
36} // namespace sema
37
38class ASTReader;
39class ASTWriter;
40enum class CUDAFunctionTarget;
41enum class CXXSpecialMemberKind;
43class Scope;
44
45class SemaCUDA : public SemaBase {
46public:
47 SemaCUDA(Sema &S);
48
49 /// Increments our count of the number of times we've seen a pragma forcing
50 /// functions to be __host__ __device__. So long as this count is greater
51 /// than zero, all functions encountered will be __host__ __device__.
53
54 /// Decrements our count of the number of times we've seen a pragma forcing
55 /// functions to be __host__ __device__. Returns false if the count is 0
56 /// before incrementing, so you can emit an error.
57 bool PopForceHostDevice();
58
60 MultiExprArg ExecConfig,
61 SourceLocation GGGLoc);
62
63 /// FunctionDecls and SourceLocations for which CheckCall has emitted a
64 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
65 /// same deferred diag twice.
66 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
67
68 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
69 /// context is "used as device code".
70 ///
71 /// - If CurContext is a __host__ function, does not emit any diagnostics
72 /// unless \p EmitOnBothSides is true.
73 /// - If CurContext is a __device__ or __global__ function, emits the
74 /// diagnostics immediately.
75 /// - If CurContext is a __host__ __device__ function and we are compiling for
76 /// the device, creates a diagnostic which is emitted if and when we realize
77 /// that the function will be codegen'ed.
78 ///
79 /// Example usage:
80 ///
81 /// // Variable-length arrays are not allowed in CUDA device code.
82 /// if (DiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentTarget())
83 /// return ExprError();
84 /// // Otherwise, continue parsing as normal.
86
87 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
88 /// context is "used as host code".
89 ///
90 /// Same as DiagIfDeviceCode, with "host" and "device" switched.
92
93 /// Diagnoses a use of RTTI at \p Loc if it is in device function or the
94 /// initializer of a device variable, where RTTI is not available.
95 void checkRTTIUse(SourceLocation Loc, StringRef Op);
96
97 /// Diagnoses a use of RTTI in \p Init, the default argument or default
98 /// member initializer of \p D if it is used at \p UseLoc in device code.
99 void checkRTTIInDefaultInit(const ValueDecl *D, const Expr *Init,
100 SourceLocation UseLoc);
101
102 /// Determines whether the given function is a CUDA device/host/kernel/etc.
103 /// function.
104 ///
105 /// Use this rather than examining the function's attributes yourself -- you
106 /// will get it wrong. Returns CUDAFunctionTarget::Host if D is null.
108 bool IgnoreImplicitHDAttr = false);
110
112 CVT_Device, /// Emitted on device side with a shadow variable on host side
113 CVT_Host, /// Emitted on host side only
114 CVT_Both, /// Emitted on both sides with different addresses
115 CVT_Unified, /// Emitted as a unified address, e.g. managed variables
116 };
117 /// Determines whether the given variable is emitted on host or device side.
119
120 /// Defines kinds of CUDA global host/device context where a function may be
121 /// called.
123 CTCK_Unknown, /// Unknown context
124 CTCK_InitGlobalVar, /// Function called during global variable
125 /// initialization
126 };
127
128 /// Define the current global CUDA host/device context where a function may be
129 /// called. Only used when a function is called outside of any functions.
135
143
144 /// Gets the CUDA target for the current context.
146 return IdentifyTarget(dyn_cast<FunctionDecl>(SemaRef.CurContext));
147 }
148
149 static bool isImplicitHostDeviceFunction(const FunctionDecl *D);
150
151 // CUDA function call preference. Must be ordered numerically from
152 // worst to best.
154 CFP_Never, // Invalid caller/callee combination.
155 CFP_WrongSide, // Calls from host-device to host or device
156 // function that do not match current compilation
157 // mode.
158 CFP_HostDevice, // Any calls to host/device functions.
159 CFP_SameSide, // Calls from host-device to host or device
160 // function matching current compilation mode.
161 CFP_Native, // host-to-host or device-to-device calls.
162 };
163
164 /// Identifies relative preference of a given Caller/Callee
165 /// combination, based on their host/device attributes.
166 /// \param Caller function which needs address of \p Callee.
167 /// nullptr in case of global context.
168 /// \param Callee target function
169 ///
170 /// \returns preference value for particular Caller/Callee combination.
172 const FunctionDecl *Callee);
173
174 /// Determines whether Caller may invoke Callee, based on their CUDA
175 /// host/device attributes. Returns false if the call is not allowed.
176 ///
177 /// Note: Will return true for CFP_WrongSide calls. These may appear in
178 /// semantically correct CUDA programs, but only if they're never codegen'ed.
179 bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee) {
180 return IdentifyPreference(Caller, Callee) != CFP_Never;
181 }
182
183 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
184 /// depending on FD and the current compilation settings.
186
187 /// May add implicit CUDAConstantAttr attribute to VD, depending on VD
188 /// and current compilation settings.
190
191 /// Check whether we're allowed to call Callee from the current context.
192 ///
193 /// - If the call is never allowed in a semantically-correct program
194 /// (CFP_Never), emits an error and returns false.
195 ///
196 /// - If the call is allowed in semantically-correct programs, but only if
197 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
198 /// be emitted if and when the caller is codegen'ed, and returns true.
199 ///
200 /// Will only create deferred diagnostics for a given SourceLocation once,
201 /// so you can safely call this multiple times without generating duplicate
202 /// deferred errors.
203 ///
204 /// - Otherwise, returns true without emitting any diagnostics.
205 bool CheckCall(SourceLocation Loc, FunctionDecl *Callee);
206
208
209 /// Set __device__ or __host__ __device__ attributes on the given lambda
210 /// operator() method.
211 ///
212 /// CUDA lambdas by default is host device function unless it has explicit
213 /// host or device attribute.
215
216 /// Record \p FD if it is a CUDA/HIP implicit host device function used on
217 /// device side in device compilation.
219
220 /// Finds a function in \p Matches with highest calling priority
221 /// from \p Caller context and erases all functions with lower
222 /// calling priority.
224 const FunctionDecl *Caller,
225 llvm::SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>>
226 &Matches);
227
228 /// Given a implicit special member, infer its CUDA target from the
229 /// calls it needs to make to underlying base/field special members.
230 /// \param ClassDecl the class for which the member is being created.
231 /// \param CSM the kind of special member.
232 /// \param MemberDecl the special member itself.
233 /// \param ConstRHS true if this is a copy operation with a const object on
234 /// its RHS.
235 /// \param Diagnose true if this call should emit diagnostics.
236 /// \return true if there was an error inferring.
237 /// The result of this call is implicit CUDA target attribute(s) attached to
238 /// the member declaration.
241 CXXMethodDecl *MemberDecl,
242 bool ConstRHS, bool Diagnose);
243
244 /// \return true if \p CD can be considered empty according to CUDA
245 /// (E.2.3.1 in CUDA 7.5 Programming guide).
248
249 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
250 // case of error emits appropriate diagnostic and invalidates \p Var.
251 //
252 // \details CUDA allows only empty constructors as initializers for global
253 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
254 // __shared__ variables whether they are local or not (they all are implicitly
255 // static in CUDA). One exception is that CUDA allows constant initializers
256 // for __constant__ and __device__ variables.
258
259 /// Check whether NewFD is a valid overload for CUDA. Emits
260 /// diagnostics and invalidates NewFD if not.
262 /// Copies target attributes from the template TD to the function FD.
264
265 /// Returns the name of the launch configuration function. This is the name
266 /// of the function that will be called to configure kernel call, with the
267 /// parameters specified via <<<>>>.
268 std::string getConfigureFuncName() const;
269 /// Return the name of the parameter buffer allocation function for the
270 /// device kernel launch.
271 std::string getGetParameterBufferFuncName() const;
272 /// Return the name of the device kernel launch function.
273 std::string getLaunchDeviceFuncName() const;
274
275 /// Record variables that are potentially ODR-used in CUDA/HIP.
277 OverloadCandidateSet &CandidateSet);
278
279 /// Null-tolerant wrapper for FunctionDecl::isImplicitHDExplicitInstantiation.
280 static bool isImplicitHDExplicitInstantiation(const FunctionDecl *FD);
281
282private:
283 unsigned ForceHostDeviceDepth = 0;
284
285 /// Whether the current context is the initializer of a device variable.
286 bool isDeviceVarInit() const;
287
288 /// The default arguments and default member initializers, paired with the
289 /// function using them.
290 llvm::DenseSet<std::pair<const ValueDecl *, const FunctionDecl *>>
291 RTTICheckedDefaultInits;
292
293 friend class ASTReader;
294 friend class ASTWriter;
295};
296
297} // namespace clang
298
299#endif // LLVM_CLANG_SEMA_SEMACUDA_H
Forward declaration of all AST node types.
FormatToken * Previous
The previous token in the unwrapped line.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::SourceLocation class and associated facilities.
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:427
Writes an AST file containing the contents of a translation unit.
Definition ASTWriter.h:98
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:114
Represents a function declaration or definition.
Definition Decl.h:2082
Declaration of a template function.
Represents the results of name lookup.
Definition Lookup.h:147
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1162
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:120
SemaBase(Sema &S)
Definition SemaBase.cpp:7
Sema & SemaRef
Definition SemaBase.h:49
friend class ASTWriter
Definition SemaCUDA.h:294
std::string getLaunchDeviceFuncName() const
Return the name of the device kernel launch function.
void PushForceHostDevice()
Increments our count of the number of times we've seen a pragma forcing functions to be host device.
Definition SemaCUDA.cpp:41
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:745
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition SemaCUDA.h:179
void RecordImplicitHostDeviceFuncUsedByDevice(const FunctionDecl *FD)
Record FD if it is a CUDA/HIP implicit host device function used on device side in device compilation...
Definition SemaCUDA.cpp:840
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
bool PopForceHostDevice()
Decrements our count of the number of times we've seen a pragma forcing functions to be host device.
Definition SemaCUDA.cpp:46
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:212
static bool isImplicitHDExplicitInstantiation(const FunctionDecl *FD)
Null-tolerant wrapper for FunctionDecl::isImplicitHDExplicitInstantiation.
Definition SemaCUDA.cpp:406
void maybeAddHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition SemaCUDA.cpp:874
ExprResult ActOnExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc)
Definition SemaCUDA.cpp:54
friend class ASTReader
Definition SemaCUDA.h:293
bool isEmptyConstructor(SourceLocation Loc, CXXConstructorDecl *CD)
Definition SemaCUDA.cpp:599
std::string getGetParameterBufferFuncName() const
Return the name of the parameter buffer allocation function for the device kernel launch.
bool isEmptyDestructor(SourceLocation Loc, CXXDestructorDecl *CD)
Definition SemaCUDA.cpp:637
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
CUDAFunctionTarget CurrentTarget()
Gets the CUDA target for the current context.
Definition SemaCUDA.h:145
SemaDiagnosticBuilder DiagIfHostCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as host cod...
Definition SemaCUDA.cpp:987
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition SemaCUDA.cpp:463
struct clang::SemaCUDA::CUDATargetContext CurCUDATargetCtx
CUDATargetContextKind
Defines kinds of CUDA global host/device context where a function may be called.
Definition SemaCUDA.h:122
@ CTCK_InitGlobalVar
Unknown context.
Definition SemaCUDA.h:124
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition SemaCUDA.cpp:953
llvm::DenseSet< FunctionDeclAndLoc > LocsWithCUDACallDiags
FunctionDecls and SourceLocations for which CheckCall has emitted a (maybe deferred) "bad call" diagn...
Definition SemaCUDA.h:66
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:400
void CheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture)
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition SemaCUDA.cpp:939
void EraseUnwantedMatches(const FunctionDecl *Caller, llvm::SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * > > &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition SemaCUDA.cpp:410
SemaCUDA(Sema &S)
Definition SemaCUDA.cpp:31
void checkRTTIInDefaultInit(const ValueDecl *D, const Expr *Init, SourceLocation UseLoc)
Diagnoses a use of RTTI in Init, the default argument or default member initializer of D if it is use...
void SetLambdaAttrs(CXXMethodDecl *Method)
Set device or host device attributes on the given lambda operator() method.
void checkRTTIUse(SourceLocation Loc, StringRef Op)
Diagnoses a use of RTTI at Loc if it is in device function or the initializer of a device variable,...
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition SemaCUDA.cpp:312
void recordPotentialODRUsedVariable(MultiExprArg Args, OverloadCandidateSet &CandidateSet)
Record variables that are potentially ODR-used in CUDA/HIP.
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition SemaCUDA.h:113
@ CVT_Both
Emitted on host side only.
Definition SemaCUDA.h:114
@ CVT_Unified
Emitted on both sides with different addresses.
Definition SemaCUDA.h:115
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
Encodes a location in the source.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
Represents a variable declaration or definition.
Definition Decl.h:934
Top level wrappers for InstallAPI frontend operations.
CUDAFunctionTarget
Definition Cuda.h:65
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2031
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
SemaCUDA::CUDATargetContext SavedCtx
Definition SemaCUDA.h:138
CUDATargetContextRAII(SemaCUDA &S_, SemaCUDA::CUDATargetContextKind K, Decl *D)
Definition SemaCUDA.cpp:194
Define the current global CUDA host/device context where a function may be called.
Definition SemaCUDA.h:130
CUDATargetContextKind Kind
Definition SemaCUDA.h:132