clang 18.0.0git
SemaCUDA.cpp
Go to the documentation of this file.
1//===--- SemaCUDA.cpp - 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 implements semantic analysis for CUDA constructs.
10///
11//===----------------------------------------------------------------------===//
12
14#include "clang/AST/Decl.h"
15#include "clang/AST/ExprCXX.h"
16#include "clang/Basic/Cuda.h"
19#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Sema.h"
24#include "clang/Sema/Template.h"
25#include "llvm/ADT/SmallVector.h"
26#include <optional>
27using namespace clang;
28
29template <typename AttrT> static bool hasExplicitAttr(const VarDecl *D) {
30 if (!D)
31 return false;
32 if (auto *A = D->getAttr<AttrT>())
33 return !A->isImplicit();
34 return false;
35}
36
38 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
39 ForceCUDAHostDeviceDepth++;
40}
41
43 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
44 if (ForceCUDAHostDeviceDepth == 0)
45 return false;
46 ForceCUDAHostDeviceDepth--;
47 return true;
48}
49
51 MultiExprArg ExecConfig,
52 SourceLocation GGGLoc) {
54 if (!ConfigDecl)
55 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
57 QualType ConfigQTy = ConfigDecl->getType();
58
59 DeclRefExpr *ConfigDR = new (Context)
60 DeclRefExpr(Context, ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
61 MarkFunctionReferenced(LLLLoc, ConfigDecl);
62
63 return BuildCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
64 /*IsExecConfig=*/true);
65}
66
69 bool HasHostAttr = false;
70 bool HasDeviceAttr = false;
71 bool HasGlobalAttr = false;
72 bool HasInvalidTargetAttr = false;
73 for (const ParsedAttr &AL : Attrs) {
74 switch (AL.getKind()) {
75 case ParsedAttr::AT_CUDAGlobal:
76 HasGlobalAttr = true;
77 break;
78 case ParsedAttr::AT_CUDAHost:
79 HasHostAttr = true;
80 break;
81 case ParsedAttr::AT_CUDADevice:
82 HasDeviceAttr = true;
83 break;
84 case ParsedAttr::AT_CUDAInvalidTarget:
85 HasInvalidTargetAttr = true;
86 break;
87 default:
88 break;
89 }
90 }
91
92 if (HasInvalidTargetAttr)
93 return CFT_InvalidTarget;
94
95 if (HasGlobalAttr)
96 return CFT_Global;
97
98 if (HasHostAttr && HasDeviceAttr)
99 return CFT_HostDevice;
100
101 if (HasDeviceAttr)
102 return CFT_Device;
103
104 return CFT_Host;
105}
106
107template <typename A>
108static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr) {
109 return D->hasAttrs() && llvm::any_of(D->getAttrs(), [&](Attr *Attribute) {
110 return isa<A>(Attribute) &&
111 !(IgnoreImplicitAttr && Attribute->isImplicit());
112 });
113}
114
117 Decl *D)
118 : S(S_) {
120 assert(K == CTCK_InitGlobalVar);
121 auto *VD = dyn_cast_or_null<VarDecl>(D);
122 if (VD && VD->hasGlobalStorage() && !VD->isStaticLocal()) {
123 auto Target = CFT_Host;
124 if ((hasAttr<CUDADeviceAttr>(VD, /*IgnoreImplicit=*/true) &&
125 !hasAttr<CUDAHostAttr>(VD, /*IgnoreImplicit=*/true)) ||
126 hasAttr<CUDASharedAttr>(VD, /*IgnoreImplicit=*/true) ||
127 hasAttr<CUDAConstantAttr>(VD, /*IgnoreImplicit=*/true))
129 S.CurCUDATargetCtx = {Target, K, VD};
130 }
131}
132
133/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
135 bool IgnoreImplicitHDAttr) {
136 // Code that lives outside a function gets the target from CurCUDATargetCtx.
137 if (D == nullptr)
139
140 if (D->hasAttr<CUDAInvalidTargetAttr>())
141 return CFT_InvalidTarget;
142
143 if (D->hasAttr<CUDAGlobalAttr>())
144 return CFT_Global;
145
146 if (hasAttr<CUDADeviceAttr>(D, IgnoreImplicitHDAttr)) {
147 if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr))
148 return CFT_HostDevice;
149 return CFT_Device;
150 } else if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr)) {
151 return CFT_Host;
152 } else if ((D->isImplicit() || !D->isUserProvided()) &&
153 !IgnoreImplicitHDAttr) {
154 // Some implicit declarations (like intrinsic functions) are not marked.
155 // Set the most lenient target on them for maximal flexibility.
156 return CFT_HostDevice;
157 }
158
159 return CFT_Host;
160}
161
162/// IdentifyTarget - Determine the CUDA compilation target for this variable.
164 if (Var->hasAttr<HIPManagedAttr>())
165 return CVT_Unified;
166 // Only constexpr and const variabless with implicit constant attribute
167 // are emitted on both sides. Such variables are promoted to device side
168 // only if they have static constant intializers on device side.
169 if ((Var->isConstexpr() || Var->getType().isConstQualified()) &&
170 Var->hasAttr<CUDAConstantAttr>() &&
171 !hasExplicitAttr<CUDAConstantAttr>(Var))
172 return CVT_Both;
173 if (Var->hasAttr<CUDADeviceAttr>() || Var->hasAttr<CUDAConstantAttr>() ||
174 Var->hasAttr<CUDASharedAttr>() ||
177 return CVT_Device;
178 // Function-scope static variable without explicit device or constant
179 // attribute are emitted
180 // - on both sides in host device functions
181 // - on device side in device or global functions
182 if (auto *FD = dyn_cast<FunctionDecl>(Var->getDeclContext())) {
183 switch (IdentifyCUDATarget(FD)) {
184 case CFT_HostDevice:
185 return CVT_Both;
186 case CFT_Device:
187 case CFT_Global:
188 return CVT_Device;
189 default:
190 return CVT_Host;
191 }
192 }
193 return CVT_Host;
194}
195
196// * CUDA Call preference table
197//
198// F - from,
199// T - to
200// Ph - preference in host mode
201// Pd - preference in device mode
202// H - handled in (x)
203// Preferences: N:native, SS:same side, HD:host-device, WS:wrong side, --:never.
204//
205// | F | T | Ph | Pd | H |
206// |----+----+-----+-----+-----+
207// | d | d | N | N | (c) |
208// | d | g | -- | -- | (a) |
209// | d | h | -- | -- | (e) |
210// | d | hd | HD | HD | (b) |
211// | g | d | N | N | (c) |
212// | g | g | -- | -- | (a) |
213// | g | h | -- | -- | (e) |
214// | g | hd | HD | HD | (b) |
215// | h | d | -- | -- | (e) |
216// | h | g | N | N | (c) |
217// | h | h | N | N | (c) |
218// | h | hd | HD | HD | (b) |
219// | hd | d | WS | SS | (d) |
220// | hd | g | SS | -- |(d/a)|
221// | hd | h | SS | WS | (d) |
222// | hd | hd | HD | HD | (b) |
223
226 const FunctionDecl *Callee) {
227 assert(Callee && "Callee must be valid.");
228 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller);
229 CUDAFunctionTarget CalleeTarget = IdentifyCUDATarget(Callee);
230
231 // If one of the targets is invalid, the check always fails, no matter what
232 // the other target is.
233 if (CallerTarget == CFT_InvalidTarget || CalleeTarget == CFT_InvalidTarget)
234 return CFP_Never;
235
236 // (a) Can't call global from some contexts until we support CUDA's
237 // dynamic parallelism.
238 if (CalleeTarget == CFT_Global &&
239 (CallerTarget == CFT_Global || CallerTarget == CFT_Device))
240 return CFP_Never;
241
242 // (b) Calling HostDevice is OK for everyone.
243 if (CalleeTarget == CFT_HostDevice)
244 return CFP_HostDevice;
245
246 // (c) Best case scenarios
247 if (CalleeTarget == CallerTarget ||
248 (CallerTarget == CFT_Host && CalleeTarget == CFT_Global) ||
249 (CallerTarget == CFT_Global && CalleeTarget == CFT_Device))
250 return CFP_Native;
251
252 // (d) HostDevice behavior depends on compilation mode.
253 if (CallerTarget == CFT_HostDevice) {
254 // It's OK to call a compilation-mode matching function from an HD one.
255 if ((getLangOpts().CUDAIsDevice && CalleeTarget == CFT_Device) ||
256 (!getLangOpts().CUDAIsDevice &&
257 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)))
258 return CFP_SameSide;
259
260 // Calls from HD to non-mode-matching functions (i.e., to host functions
261 // when compiling in device mode or to device functions when compiling in
262 // host mode) are allowed at the sema level, but eventually rejected if
263 // they're ever codegened. TODO: Reject said calls earlier.
264 return CFP_WrongSide;
265 }
266
267 // (e) Calling across device/host boundary is not something you should do.
268 if ((CallerTarget == CFT_Host && CalleeTarget == CFT_Device) ||
269 (CallerTarget == CFT_Device && CalleeTarget == CFT_Host) ||
270 (CallerTarget == CFT_Global && CalleeTarget == CFT_Host))
271 return CFP_Never;
272
273 llvm_unreachable("All cases should've been handled by now.");
274}
275
276template <typename AttrT> static bool hasImplicitAttr(const FunctionDecl *D) {
277 if (!D)
278 return false;
279 if (auto *A = D->getAttr<AttrT>())
280 return A->isImplicit();
281 return D->isImplicit();
282}
283
285 bool IsImplicitDevAttr = hasImplicitAttr<CUDADeviceAttr>(D);
286 bool IsImplicitHostAttr = hasImplicitAttr<CUDAHostAttr>(D);
287 return IsImplicitDevAttr && IsImplicitHostAttr;
288}
289
291 const FunctionDecl *Caller,
292 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches) {
293 if (Matches.size() <= 1)
294 return;
295
296 using Pair = std::pair<DeclAccessPair, FunctionDecl*>;
297
298 // Gets the CUDA function preference for a call from Caller to Match.
299 auto GetCFP = [&](const Pair &Match) {
300 return IdentifyCUDAPreference(Caller, Match.second);
301 };
302
303 // Find the best call preference among the functions in Matches.
304 CUDAFunctionPreference BestCFP = GetCFP(*std::max_element(
305 Matches.begin(), Matches.end(),
306 [&](const Pair &M1, const Pair &M2) { return GetCFP(M1) < GetCFP(M2); }));
307
308 // Erase all functions with lower priority.
309 llvm::erase_if(Matches,
310 [&](const Pair &Match) { return GetCFP(Match) < BestCFP; });
311}
312
313/// When an implicitly-declared special member has to invoke more than one
314/// base/field special member, conflicts may occur in the targets of these
315/// members. For example, if one base's member __host__ and another's is
316/// __device__, it's a conflict.
317/// This function figures out if the given targets \param Target1 and
318/// \param Target2 conflict, and if they do not it fills in
319/// \param ResolvedTarget with a target that resolves for both calls.
320/// \return true if there's a conflict, false otherwise.
321static bool
324 Sema::CUDAFunctionTarget *ResolvedTarget) {
325 // Only free functions and static member functions may be global.
326 assert(Target1 != Sema::CFT_Global);
327 assert(Target2 != Sema::CFT_Global);
328
329 if (Target1 == Sema::CFT_HostDevice) {
330 *ResolvedTarget = Target2;
331 } else if (Target2 == Sema::CFT_HostDevice) {
332 *ResolvedTarget = Target1;
333 } else if (Target1 != Target2) {
334 return true;
335 } else {
336 *ResolvedTarget = Target1;
337 }
338
339 return false;
340}
341
344 CXXMethodDecl *MemberDecl,
345 bool ConstRHS,
346 bool Diagnose) {
347 // If the defaulted special member is defined lexically outside of its
348 // owning class, or the special member already has explicit device or host
349 // attributes, do not infer.
350 bool InClass = MemberDecl->getLexicalParent() == MemberDecl->getParent();
351 bool HasH = MemberDecl->hasAttr<CUDAHostAttr>();
352 bool HasD = MemberDecl->hasAttr<CUDADeviceAttr>();
353 bool HasExplicitAttr =
354 (HasD && !MemberDecl->getAttr<CUDADeviceAttr>()->isImplicit()) ||
355 (HasH && !MemberDecl->getAttr<CUDAHostAttr>()->isImplicit());
356 if (!InClass || HasExplicitAttr)
357 return false;
358
359 std::optional<CUDAFunctionTarget> InferredTarget;
360
361 // We're going to invoke special member lookup; mark that these special
362 // members are called from this one, and not from its caller.
363 ContextRAII MethodContext(*this, MemberDecl);
364
365 // Look for special members in base classes that should be invoked from here.
366 // Infer the target of this member base on the ones it should call.
367 // Skip direct and indirect virtual bases for abstract classes.
369 for (const auto &B : ClassDecl->bases()) {
370 if (!B.isVirtual()) {
371 Bases.push_back(&B);
372 }
373 }
374
375 if (!ClassDecl->isAbstract()) {
376 llvm::append_range(Bases, llvm::make_pointer_range(ClassDecl->vbases()));
377 }
378
379 for (const auto *B : Bases) {
380 const RecordType *BaseType = B->getType()->getAs<RecordType>();
381 if (!BaseType) {
382 continue;
383 }
384
385 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
387 LookupSpecialMember(BaseClassDecl, CSM,
388 /* ConstArg */ ConstRHS,
389 /* VolatileArg */ false,
390 /* RValueThis */ false,
391 /* ConstThis */ false,
392 /* VolatileThis */ false);
393
394 if (!SMOR.getMethod())
395 continue;
396
397 CUDAFunctionTarget BaseMethodTarget = IdentifyCUDATarget(SMOR.getMethod());
398 if (!InferredTarget) {
399 InferredTarget = BaseMethodTarget;
400 } else {
401 bool ResolutionError = resolveCalleeCUDATargetConflict(
402 *InferredTarget, BaseMethodTarget, &*InferredTarget);
403 if (ResolutionError) {
404 if (Diagnose) {
405 Diag(ClassDecl->getLocation(),
406 diag::note_implicit_member_target_infer_collision)
407 << (unsigned)CSM << *InferredTarget << BaseMethodTarget;
408 }
409 MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
410 return true;
411 }
412 }
413 }
414
415 // Same as for bases, but now for special members of fields.
416 for (const auto *F : ClassDecl->fields()) {
417 if (F->isInvalidDecl()) {
418 continue;
419 }
420
421 const RecordType *FieldType =
422 Context.getBaseElementType(F->getType())->getAs<RecordType>();
423 if (!FieldType) {
424 continue;
425 }
426
427 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(FieldType->getDecl());
429 LookupSpecialMember(FieldRecDecl, CSM,
430 /* ConstArg */ ConstRHS && !F->isMutable(),
431 /* VolatileArg */ false,
432 /* RValueThis */ false,
433 /* ConstThis */ false,
434 /* VolatileThis */ false);
435
436 if (!SMOR.getMethod())
437 continue;
438
439 CUDAFunctionTarget FieldMethodTarget =
441 if (!InferredTarget) {
442 InferredTarget = FieldMethodTarget;
443 } else {
444 bool ResolutionError = resolveCalleeCUDATargetConflict(
445 *InferredTarget, FieldMethodTarget, &*InferredTarget);
446 if (ResolutionError) {
447 if (Diagnose) {
448 Diag(ClassDecl->getLocation(),
449 diag::note_implicit_member_target_infer_collision)
450 << (unsigned)CSM << *InferredTarget << FieldMethodTarget;
451 }
452 MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
453 return true;
454 }
455 }
456 }
457
458
459 // If no target was inferred, mark this member as __host__ __device__;
460 // it's the least restrictive option that can be invoked from any target.
461 bool NeedsH = true, NeedsD = true;
462 if (InferredTarget) {
463 if (*InferredTarget == CFT_Device)
464 NeedsH = false;
465 else if (*InferredTarget == CFT_Host)
466 NeedsD = false;
467 }
468
469 // We either setting attributes first time, or the inferred ones must match
470 // previously set ones.
471 if (NeedsD && !HasD)
472 MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
473 if (NeedsH && !HasH)
474 MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
475
476 return false;
477}
478
480 if (!CD->isDefined() && CD->isTemplateInstantiation())
482
483 // (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
484 // empty at a point in the translation unit, if it is either a
485 // trivial constructor
486 if (CD->isTrivial())
487 return true;
488
489 // ... or it satisfies all of the following conditions:
490 // The constructor function has been defined.
491 // The constructor function has no parameters,
492 // and the function body is an empty compound statement.
493 if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
494 return false;
495
496 // Its class has no virtual functions and no virtual base classes.
497 if (CD->getParent()->isDynamicClass())
498 return false;
499
500 // Union ctor does not call ctors of its data members.
501 if (CD->getParent()->isUnion())
502 return true;
503
504 // The only form of initializer allowed is an empty constructor.
505 // This will recursively check all base classes and member initializers
506 if (!llvm::all_of(CD->inits(), [&](const CXXCtorInitializer *CI) {
507 if (const CXXConstructExpr *CE =
508 dyn_cast<CXXConstructExpr>(CI->getInit()))
509 return isEmptyCudaConstructor(Loc, CE->getConstructor());
510 return false;
511 }))
512 return false;
513
514 return true;
515}
516
518 // No destructor -> no problem.
519 if (!DD)
520 return true;
521
522 if (!DD->isDefined() && DD->isTemplateInstantiation())
524
525 // (E.2.3.1, CUDA 7.5) A destructor for a class type is considered
526 // empty at a point in the translation unit, if it is either a
527 // trivial constructor
528 if (DD->isTrivial())
529 return true;
530
531 // ... or it satisfies all of the following conditions:
532 // The destructor function has been defined.
533 // and the function body is an empty compound statement.
534 if (!DD->hasTrivialBody())
535 return false;
536
537 const CXXRecordDecl *ClassDecl = DD->getParent();
538
539 // Its class has no virtual functions and no virtual base classes.
540 if (ClassDecl->isDynamicClass())
541 return false;
542
543 // Union does not have base class and union dtor does not call dtors of its
544 // data members.
545 if (DD->getParent()->isUnion())
546 return true;
547
548 // Only empty destructors are allowed. This will recursively check
549 // destructors for all base classes...
550 if (!llvm::all_of(ClassDecl->bases(), [&](const CXXBaseSpecifier &BS) {
551 if (CXXRecordDecl *RD = BS.getType()->getAsCXXRecordDecl())
552 return isEmptyCudaDestructor(Loc, RD->getDestructor());
553 return true;
554 }))
555 return false;
556
557 // ... and member fields.
558 if (!llvm::all_of(ClassDecl->fields(), [&](const FieldDecl *Field) {
559 if (CXXRecordDecl *RD = Field->getType()
560 ->getBaseElementTypeUnsafe()
561 ->getAsCXXRecordDecl())
562 return isEmptyCudaDestructor(Loc, RD->getDestructor());
563 return true;
564 }))
565 return false;
566
567 return true;
568}
569
570namespace {
571enum CUDAInitializerCheckKind {
572 CICK_DeviceOrConstant, // Check initializer for device/constant variable
573 CICK_Shared, // Check initializer for shared variable
574};
575
576bool IsDependentVar(VarDecl *VD) {
577 if (VD->getType()->isDependentType())
578 return true;
579 if (const auto *Init = VD->getInit())
580 return Init->isValueDependent();
581 return false;
582}
583
584// Check whether a variable has an allowed initializer for a CUDA device side
585// variable with global storage. \p VD may be a host variable to be checked for
586// potential promotion to device side variable.
587//
588// CUDA/HIP allows only empty constructors as initializers for global
589// variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
590// __shared__ variables whether they are local or not (they all are implicitly
591// static in CUDA). One exception is that CUDA allows constant initializers
592// for __constant__ and __device__ variables.
593bool HasAllowedCUDADeviceStaticInitializer(Sema &S, VarDecl *VD,
594 CUDAInitializerCheckKind CheckKind) {
595 assert(!VD->isInvalidDecl() && VD->hasGlobalStorage());
596 assert(!IsDependentVar(VD) && "do not check dependent var");
597 const Expr *Init = VD->getInit();
598 auto IsEmptyInit = [&](const Expr *Init) {
599 if (!Init)
600 return true;
601 if (const auto *CE = dyn_cast<CXXConstructExpr>(Init)) {
602 return S.isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
603 }
604 return false;
605 };
606 auto IsConstantInit = [&](const Expr *Init) {
607 assert(Init);
609 /*NoWronSidedVars=*/true);
610 return Init->isConstantInitializer(S.Context,
611 VD->getType()->isReferenceType());
612 };
613 auto HasEmptyDtor = [&](VarDecl *VD) {
614 if (const auto *RD = VD->getType()->getAsCXXRecordDecl())
615 return S.isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
616 return true;
617 };
618 if (CheckKind == CICK_Shared)
619 return IsEmptyInit(Init) && HasEmptyDtor(VD);
620 return S.LangOpts.GPUAllowDeviceInit ||
621 ((IsEmptyInit(Init) || IsConstantInit(Init)) && HasEmptyDtor(VD));
622}
623} // namespace
624
626 // Do not check dependent variables since the ctor/dtor/initializer are not
627 // determined. Do it after instantiation.
628 if (VD->isInvalidDecl() || !VD->hasInit() || !VD->hasGlobalStorage() ||
629 IsDependentVar(VD))
630 return;
631 const Expr *Init = VD->getInit();
632 bool IsSharedVar = VD->hasAttr<CUDASharedAttr>();
633 bool IsDeviceOrConstantVar =
634 !IsSharedVar &&
635 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>());
636 if (IsDeviceOrConstantVar || IsSharedVar) {
637 if (HasAllowedCUDADeviceStaticInitializer(
638 *this, VD, IsSharedVar ? CICK_Shared : CICK_DeviceOrConstant))
639 return;
640 Diag(VD->getLocation(),
641 IsSharedVar ? diag::err_shared_var_init : diag::err_dynamic_var_init)
642 << Init->getSourceRange();
643 VD->setInvalidDecl();
644 } else {
645 // This is a host-side global variable. Check that the initializer is
646 // callable from the host side.
647 const FunctionDecl *InitFn = nullptr;
648 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
649 InitFn = CE->getConstructor();
650 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
651 InitFn = CE->getDirectCallee();
652 }
653 if (InitFn) {
654 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
655 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
656 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
657 << InitFnTarget << InitFn;
658 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
659 VD->setInvalidDecl();
660 }
661 }
662 }
663}
664
665// With -fcuda-host-device-constexpr, an unattributed constexpr function is
666// treated as implicitly __host__ __device__, unless:
667// * it is a variadic function (device-side variadic functions are not
668// allowed), or
669// * a __device__ function with this signature was already declared, in which
670// case in which case we output an error, unless the __device__ decl is in a
671// system header, in which case we leave the constexpr function unattributed.
672//
673// In addition, all function decls are treated as __host__ __device__ when
674// ForceCUDAHostDeviceDepth > 0 (corresponding to code within a
675// #pragma clang force_cuda_host_device_begin/end
676// pair).
678 const LookupResult &Previous) {
679 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
680
681 if (ForceCUDAHostDeviceDepth > 0) {
682 if (!NewD->hasAttr<CUDAHostAttr>())
683 NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
684 if (!NewD->hasAttr<CUDADeviceAttr>())
685 NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
686 return;
687 }
688
689 if (!getLangOpts().CUDAHostDeviceConstexpr || !NewD->isConstexpr() ||
690 NewD->isVariadic() || NewD->hasAttr<CUDAHostAttr>() ||
691 NewD->hasAttr<CUDADeviceAttr>() || NewD->hasAttr<CUDAGlobalAttr>())
692 return;
693
694 // Is D a __device__ function with the same signature as NewD, ignoring CUDA
695 // attributes?
696 auto IsMatchingDeviceFn = [&](NamedDecl *D) {
697 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(D))
698 D = Using->getTargetDecl();
699 FunctionDecl *OldD = D->getAsFunction();
700 return OldD && OldD->hasAttr<CUDADeviceAttr>() &&
701 !OldD->hasAttr<CUDAHostAttr>() &&
702 !IsOverload(NewD, OldD, /* UseMemberUsingDeclRules = */ false,
703 /* ConsiderCudaAttrs = */ false);
704 };
705 auto It = llvm::find_if(Previous, IsMatchingDeviceFn);
706 if (It != Previous.end()) {
707 // We found a __device__ function with the same name and signature as NewD
708 // (ignoring CUDA attrs). This is an error unless that function is defined
709 // in a system header, in which case we simply return without making NewD
710 // host+device.
711 NamedDecl *Match = *It;
712 if (!getSourceManager().isInSystemHeader(Match->getLocation())) {
713 Diag(NewD->getLocation(),
714 diag::err_cuda_unattributed_constexpr_cannot_overload_device)
715 << NewD;
716 Diag(Match->getLocation(),
717 diag::note_cuda_conflicting_device_function_declared_here);
718 }
719 return;
720 }
721
722 NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
723 NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
724}
725
726// TODO: `__constant__` memory may be a limited resource for certain targets.
727// A safeguard may be needed at the end of compilation pipeline if
728// `__constant__` memory usage goes beyond limit.
730 // Do not promote dependent variables since the cotr/dtor/initializer are
731 // not determined. Do it after instantiation.
732 if (getLangOpts().CUDAIsDevice && !VD->hasAttr<CUDAConstantAttr>() &&
733 !VD->hasAttr<CUDASharedAttr>() &&
734 (VD->isFileVarDecl() || VD->isStaticDataMember()) &&
735 !IsDependentVar(VD) &&
736 ((VD->isConstexpr() || VD->getType().isConstQualified()) &&
737 HasAllowedCUDADeviceStaticInitializer(*this, VD,
738 CICK_DeviceOrConstant))) {
739 VD->addAttr(CUDAConstantAttr::CreateImplicit(getASTContext()));
740 }
741}
742
744 unsigned DiagID) {
745 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
746 FunctionDecl *CurFunContext = getCurFunctionDecl(/*AllowLambda=*/true);
747 SemaDiagnosticBuilder::Kind DiagKind = [&] {
748 if (!CurFunContext)
750 switch (CurrentCUDATarget()) {
751 case CFT_Global:
752 case CFT_Device:
754 case CFT_HostDevice:
755 // An HD function counts as host code if we're compiling for host, and
756 // device code if we're compiling for device. Defer any errors in device
757 // mode until the function is known-emitted.
758 if (!getLangOpts().CUDAIsDevice)
760 if (IsLastErrorImmediate && Diags.getDiagnosticIDs()->isBuiltinNote(DiagID))
762 return (getEmissionStatus(CurFunContext) ==
766 default:
768 }
769 }();
770 return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, CurFunContext, *this);
771}
772
774 unsigned DiagID) {
775 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
776 FunctionDecl *CurFunContext = getCurFunctionDecl(/*AllowLambda=*/true);
777 SemaDiagnosticBuilder::Kind DiagKind = [&] {
778 if (!CurFunContext)
780 switch (CurrentCUDATarget()) {
781 case CFT_Host:
783 case CFT_HostDevice:
784 // An HD function counts as host code if we're compiling for host, and
785 // device code if we're compiling for device. Defer any errors in device
786 // mode until the function is known-emitted.
787 if (getLangOpts().CUDAIsDevice)
789 if (IsLastErrorImmediate && Diags.getDiagnosticIDs()->isBuiltinNote(DiagID))
791 return (getEmissionStatus(CurFunContext) ==
795 default:
797 }
798 }();
799 return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, CurFunContext, *this);
800}
801
803 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
804 assert(Callee && "Callee may not be null.");
805
806 auto &ExprEvalCtx = ExprEvalContexts.back();
807 if (ExprEvalCtx.isUnevaluated() || ExprEvalCtx.isConstantEvaluated())
808 return true;
809
810 // FIXME: Is bailing out early correct here? Should we instead assume that
811 // the caller is a global initializer?
812 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
813 if (!Caller)
814 return true;
815
816 // If the caller is known-emitted, mark the callee as known-emitted.
817 // Otherwise, mark the call in our call graph so we can traverse it later.
818 bool CallerKnownEmitted =
820 SemaDiagnosticBuilder::Kind DiagKind = [this, Caller, Callee,
821 CallerKnownEmitted] {
822 switch (IdentifyCUDAPreference(Caller, Callee)) {
823 case CFP_Never:
824 case CFP_WrongSide:
825 assert(Caller && "Never/wrongSide calls require a non-null caller");
826 // If we know the caller will be emitted, we know this wrong-side call
827 // will be emitted, so it's an immediate error. Otherwise, defer the
828 // error until we know the caller is emitted.
829 return CallerKnownEmitted
832 default:
834 }
835 }();
836
837 if (DiagKind == SemaDiagnosticBuilder::K_Nop) {
838 // For -fgpu-rdc, keep track of external kernels used by host functions.
839 if (LangOpts.CUDAIsDevice && LangOpts.GPURelocatableDeviceCode &&
840 Callee->hasAttr<CUDAGlobalAttr>() && !Callee->isDefined())
842 return true;
843 }
844
845 // Avoid emitting this error twice for the same location. Using a hashtable
846 // like this is unfortunate, but because we must continue parsing as normal
847 // after encountering a deferred error, it's otherwise very tricky for us to
848 // ensure that we only emit this deferred error once.
849 if (!LocsWithCUDACallDiags.insert({Caller, Loc}).second)
850 return true;
851
852 SemaDiagnosticBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller, *this)
853 << IdentifyCUDATarget(Callee) << /*function*/ 0 << Callee
854 << IdentifyCUDATarget(Caller);
855 if (!Callee->getBuiltinID())
856 SemaDiagnosticBuilder(DiagKind, Callee->getLocation(),
857 diag::note_previous_decl, Caller, *this)
858 << Callee;
859 return DiagKind != SemaDiagnosticBuilder::K_Immediate &&
861}
862
863// Check the wrong-sided reference capture of lambda for CUDA/HIP.
864// A lambda function may capture a stack variable by reference when it is
865// defined and uses the capture by reference when the lambda is called. When
866// the capture and use happen on different sides, the capture is invalid and
867// should be diagnosed.
869 const sema::Capture &Capture) {
870 // In host compilation we only need to check lambda functions emitted on host
871 // side. In such lambda functions, a reference capture is invalid only
872 // if the lambda structure is populated by a device function or kernel then
873 // is passed to and called by a host function. However that is impossible,
874 // since a device function or kernel can only call a device function, also a
875 // kernel cannot pass a lambda back to a host function since we cannot
876 // define a kernel argument type which can hold the lambda before the lambda
877 // itself is defined.
878 if (!LangOpts.CUDAIsDevice)
879 return;
880
881 // File-scope lambda can only do init captures for global variables, which
882 // results in passing by value for these global variables.
883 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
884 if (!Caller)
885 return;
886
887 // In device compilation, we only need to check lambda functions which are
888 // emitted on device side. For such lambdas, a reference capture is invalid
889 // only if the lambda structure is populated by a host function then passed
890 // to and called in a device function or kernel.
891 bool CalleeIsDevice = Callee->hasAttr<CUDADeviceAttr>();
892 bool CallerIsHost =
893 !Caller->hasAttr<CUDAGlobalAttr>() && !Caller->hasAttr<CUDADeviceAttr>();
894 bool ShouldCheck = CalleeIsDevice && CallerIsHost;
895 if (!ShouldCheck || !Capture.isReferenceCapture())
896 return;
897 auto DiagKind = SemaDiagnosticBuilder::K_Deferred;
900 diag::err_capture_bad_target, Callee, *this)
901 << Capture.getVariable();
902 } else if (Capture.isThisCapture()) {
903 // Capture of this pointer is allowed since this pointer may be pointing to
904 // managed memory which is accessible on both device and host sides. It only
905 // results in invalid memory access if this pointer points to memory not
906 // accessible on device side.
908 diag::warn_maybe_capture_bad_target_this_ptr, Callee,
909 *this);
910 }
911}
912
914 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
915 if (Method->hasAttr<CUDAHostAttr>() || Method->hasAttr<CUDADeviceAttr>())
916 return;
917 Method->addAttr(CUDADeviceAttr::CreateImplicit(Context));
918 Method->addAttr(CUDAHostAttr::CreateImplicit(Context));
919}
920
922 const LookupResult &Previous) {
923 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
924 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(NewFD);
925 for (NamedDecl *OldND : Previous) {
926 FunctionDecl *OldFD = OldND->getAsFunction();
927 if (!OldFD)
928 continue;
929
930 CUDAFunctionTarget OldTarget = IdentifyCUDATarget(OldFD);
931 // Don't allow HD and global functions to overload other functions with the
932 // same signature. We allow overloading based on CUDA attributes so that
933 // functions can have different implementations on the host and device, but
934 // HD/global functions "exist" in some sense on both the host and device, so
935 // should have the same implementation on both sides.
936 if (NewTarget != OldTarget &&
937 ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
938 (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) &&
939 !IsOverload(NewFD, OldFD, /* UseMemberUsingDeclRules = */ false,
940 /* ConsiderCudaAttrs = */ false)) {
941 Diag(NewFD->getLocation(), diag::err_cuda_ovl_target)
942 << NewTarget << NewFD->getDeclName() << OldTarget << OldFD;
943 Diag(OldFD->getLocation(), diag::note_previous_declaration);
944 NewFD->setInvalidDecl();
945 break;
946 }
947 }
948}
949
950template <typename AttrTy>
952 const FunctionDecl &TemplateFD) {
953 if (AttrTy *Attribute = TemplateFD.getAttr<AttrTy>()) {
954 AttrTy *Clone = Attribute->clone(S.Context);
955 Clone->setInherited(true);
956 FD->addAttr(Clone);
957 }
958}
959
961 const FunctionTemplateDecl &TD) {
962 const FunctionDecl &TemplateFD = *TD.getTemplatedDecl();
963 copyAttrIfPresent<CUDAGlobalAttr>(*this, FD, TemplateFD);
964 copyAttrIfPresent<CUDAHostAttr>(*this, FD, TemplateFD);
965 copyAttrIfPresent<CUDADeviceAttr>(*this, FD, TemplateFD);
966}
967
969 if (getLangOpts().HIP)
970 return getLangOpts().HIPUseNewLaunchAPI ? "__hipPushCallConfiguration"
971 : "hipConfigureCall";
972
973 // New CUDA kernel launch sequence.
976 return "__cudaPushCallConfiguration";
977
978 // Legacy CUDA kernel configuration call
979 return "cudaConfigureCall";
980}
Defines the clang::ASTContext interface.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::Preprocessor interface.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition: SemaCUDA.cpp:108
static void copyAttrIfPresent(Sema &S, FunctionDecl *FD, const FunctionDecl &TemplateFD)
Definition: SemaCUDA.cpp:951
static bool resolveCalleeCUDATargetConflict(Sema::CUDAFunctionTarget Target1, Sema::CUDAFunctionTarget Target2, Sema::CUDAFunctionTarget *ResolvedTarget)
When an implicitly-declared special member has to invoke more than one base/field special member,...
Definition: SemaCUDA.cpp:322
static bool hasImplicitAttr(const FunctionDecl *D)
Definition: SemaCUDA.cpp:276
static bool hasExplicitAttr(const VarDecl *D)
Definition: SemaCUDA.cpp:29
StateNode * Previous
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::DenseSet< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
Definition: ASTContext.h:1151
FunctionDecl * getcudaConfigureCallDecl()
Definition: ASTContext.h:1395
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:743
Attr - This represents one attribute.
Definition: Attr.h:40
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1523
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2491
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2259
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2755
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2035
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2150
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
base_class_range bases()
Definition: DeclCXX.h:606
base_class_range vbases()
Definition: DeclCXX.h:623
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1203
bool isDynamicClass() const
Definition: DeclCXX.h:572
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2832
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1967
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1242
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
T * getAttr() const
Definition: DeclBase.h:556
bool hasAttrs() const
Definition: DeclBase.h:502
void addAttr(Attr *A)
Definition: DeclBase.cpp:904
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:576
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:133
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:228
bool isInvalidDecl() const
Definition: DeclBase.h:571
SourceLocation getLocation() const
Definition: DeclBase.h:432
DeclContext * getDeclContext()
Definition: DeclBase.h:441
AttrVec & getAttrs()
Definition: DeclBase.h:508
bool hasAttr() const
Definition: DeclBase.h:560
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:552
This represents one expression.
Definition: Expr.h:110
Represents a member of a struct/union/class.
Definition: Decl.h:2962
Represents a function declaration or definition.
Definition: Decl.h:1919
bool hasTrivialBody() const
Returns whether the function has a trivial body that does not require any specific codegen.
Definition: Decl.cpp:3105
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2274
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3062
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4010
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2367
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2307
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3616
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3141
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Represents the results of name lookup.
Definition: Lookup.h:46
This represents a decl that may have a name.
Definition: Decl.h:247
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:313
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:124
A (possibly-)qualified type.
Definition: Type.h:736
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6819
field_range fields() const
Definition: Decl.h:4263
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4933
RecordDecl * getDecl() const
Definition: Type.h:4943
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
A RAII object to temporarily push a declaration context.
Definition: Sema.h:1024
A generic diagnostic builder for errors which may or may not be deferred.
Definition: Sema.h:1800
@ K_Nop
Emit no diagnostics.
Definition: Sema.h:1804
@ K_Deferred
Create a deferred diagnostic, which is emitted only if the function it's attached to is codegen'ed.
Definition: Sema.h:1814
@ K_ImmediateWithCallStack
Emit the diagnostic immediately, and, if it's a warning or error, also emit a call stack showing how ...
Definition: Sema.h:1810
@ K_Immediate
Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
Definition: Sema.h:1806
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition: Sema.h:1449
CXXMethodDecl * getMethod() const
Definition: Sema.h:1465
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:356
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1897
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true, bool ConsiderRequiresClauses=true)
CUDAFunctionPreference
Definition: Sema.h:13341
@ CFP_Never
Definition: Sema.h:13342
@ CFP_HostDevice
Definition: Sema.h:13346
@ CFP_SameSide
Definition: Sema.h:13347
@ CFP_Native
Definition: Sema.h:13349
@ CFP_WrongSide
Definition: Sema.h:13343
bool IsLastErrorImmediate
Is the last error level diagnostic immediate.
Definition: Sema.h:1910
void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture)
Definition: SemaCUDA.cpp:868
void EraseUnwantedCUDAMatches(const FunctionDecl *Caller, 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:290
ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc)
Definition: SemaCUDA.cpp:50
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1475
CUDATargetContextKind
Defines kinds of CUDA global host/device context where a function may be called.
Definition: Sema.h:13311
@ CTCK_InitGlobalVar
Unknown context.
Definition: Sema.h:13313
ASTContext & Context
Definition: Sema.h:407
ASTContext & getASTContext() const
Definition: Sema.h:1692
void checkAllowedCUDAInitializer(VarDecl *VD)
Definition: SemaCUDA.cpp:625
const LangOptions & getLangOpts() const
Definition: Sema.h:1685
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition: SemaCUDA.cpp:743
bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition: SemaCUDA.cpp:802
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:7127
const LangOptions & LangOpts
Definition: Sema.h:405
void MaybeAddCUDAConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition: SemaCUDA.cpp:729
CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition: SemaCUDA.cpp:225
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20221
struct clang::Sema::CUDATargetContext CurCUDATargetCtx
void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition: SemaCUDA.cpp:677
void PushForceCUDAHostDevice()
Increments our count of the number of times we've seen a pragma forcing functions to be host device.
Definition: SemaCUDA.cpp:37
SourceManager & getSourceManager() const
Definition: Sema.h:1690
llvm::DenseSet< FunctionDeclAndLoc > LocsWithCUDACallDiags
FunctionDecls and SourceLocations for which CheckCUDACall has emitted a (maybe deferred) "bad call" d...
Definition: Sema.h:13206
SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as host cod...
Definition: SemaCUDA.cpp:773
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember 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:342
void CUDASetLambdaAttrs(CXXMethodDecl *Method)
Set device or host device attributes on the given lambda operator() method.
Definition: SemaCUDA.cpp:913
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
CUDAVariableTarget
Definition: Sema.h:13300
@ CVT_Both
Emitted on host side only.
Definition: Sema.h:13303
@ CVT_Device
Definition: Sema.h:13301
@ CVT_Unified
Emitted on both sides with different addresses.
Definition: Sema.h:13304
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition: Sema.h:13302
CUDAFunctionTarget
Definition: Sema.h:1015
@ CFT_Device
Definition: Sema.h:1016
@ CFT_HostDevice
Definition: Sema.h:1019
@ CFT_Global
Definition: Sema.h:1017
@ CFT_Host
Definition: Sema.h:1018
@ CFT_InvalidTarget
Definition: Sema.h:1020
void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
Definition: SemaCUDA.cpp:960
CUDAFunctionTarget CurrentCUDATarget()
Gets the CUDA target for the current context.
Definition: Sema.h:13333
bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD)
Definition: SemaCUDA.cpp:479
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1427
DiagnosticsEngine & Diags
Definition: Sema.h:409
bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD)
Definition: SemaCUDA.cpp:517
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:18833
static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D)
Definition: SemaCUDA.cpp:284
bool PopForceCUDAHostDevice()
Decrements our count of the number of times we've seen a pragma forcing functions to be host device.
Definition: SemaCUDA.cpp:42
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:1572
std::string getCudaConfigureFuncName() const
Returns the name of the launch configuration function.
Definition: SemaCUDA.cpp:968
void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
Definition: SemaCUDA.cpp:921
Encodes a location in the source.
bool isUnion() const
Definition: Decl.h:3681
const llvm::VersionTuple & getSDKVersion() const
Definition: TargetInfo.h:1691
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1823
bool isReferenceType() const
Definition: Type.h:7011
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
Definition: Type.cpp:4660
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2365
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
Definition: Type.cpp:4667
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7523
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3274
QualType getType() const
Definition: Decl.h:714
Represents a variable declaration or definition.
Definition: Decl.h:915
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1521
bool hasInit() const
Definition: Decl.cpp:2378
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1242
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1185
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1301
const Expr * getInit() const
Definition: Decl.h:1327
ValueDecl * getVariable() const
Definition: ScopeInfo.h:650
bool isVariableCapture() const
Definition: ScopeInfo.h:625
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:661
bool isThisCapture() const
Definition: ScopeInfo.h:624
bool isReferenceCapture() const
Definition: ScopeInfo.h:630
Defines the clang::TargetInfo interface.
bool CudaFeatureEnabled(llvm::VersionTuple, CudaFeature)
Definition: Cuda.cpp:237
ExprResult ExprError()
Definition: Ownership.h:264
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:130
CUDATargetContext SavedCtx
Definition: Sema.h:13327
CUDATargetContextRAII(Sema &S_, CUDATargetContextKind K, Decl *D)
Definition: SemaCUDA.cpp:115
CUDAFunctionTarget Target
Definition: Sema.h:13320