clang 23.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
13#include "clang/Sema/SemaCUDA.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/Basic/Cuda.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Overload.h"
23#include "clang/Sema/Sema.h"
24#include "clang/Sema/Template.h"
25#include "llvm/ADT/SmallVector.h"
26#include <optional>
27using namespace clang;
28
30
31template <typename AttrT> static bool hasExplicitAttr(const VarDecl *D) {
32 if (!D)
33 return false;
34 if (auto *A = D->getAttr<AttrT>())
35 return !A->isImplicit();
36 return false;
37}
38
40 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
41 ForceHostDeviceDepth++;
42}
43
45 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
46 if (ForceHostDeviceDepth == 0)
47 return false;
48 ForceHostDeviceDepth--;
49 return true;
50}
51
53 MultiExprArg ExecConfig,
54 SourceLocation GGGLoc) {
55 bool IsDeviceKernelCall = false;
56 switch (CurrentTarget()) {
59 IsDeviceKernelCall = true;
60 break;
62 if (getLangOpts().CUDAIsDevice) {
63 IsDeviceKernelCall = true;
64 if (FunctionDecl *Caller =
65 SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
66 Caller && isImplicitHostDeviceFunction(Caller)) {
67 // Under the device compilation, config call under an HD function should
68 // be treated as a device kernel call. But, for implicit HD ones (such
69 // as lambdas), need to check whether RDC is enabled or not.
70 if (!getLangOpts().GPURelocatableDeviceCode)
71 IsDeviceKernelCall = false;
72 // HIP doesn't support device-side kernel call yet. Still treat it as
73 // the host-side kernel call.
74 if (getLangOpts().HIP)
75 IsDeviceKernelCall = false;
76 }
77 }
78 break;
79 default:
80 break;
81 }
82
83 if (IsDeviceKernelCall && getLangOpts().HIP)
84 return ExprError(
85 Diag(LLLLoc, diag::err_cuda_device_kernel_launch_not_supported));
86
87 FunctionDecl *ConfigDecl = IsDeviceKernelCall
90 if (!ConfigDecl)
91 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
92 << (IsDeviceKernelCall ? getLaunchDeviceFuncName()
94 // Additional check on the launch function if it's a device kernel call.
95 if (IsDeviceKernelCall) {
96 auto *GetParamBuf = getASTContext().getcudaGetParameterBufferDecl();
97 if (!GetParamBuf)
98 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
100 }
101
102 QualType ConfigQTy = ConfigDecl->getType();
103
104 DeclRefExpr *ConfigDR = new (getASTContext()) DeclRefExpr(
105 getASTContext(), ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
106 SemaRef.MarkFunctionReferenced(LLLLoc, ConfigDecl);
107
108 if (IsDeviceKernelCall) {
110 // Use a null pointer as the kernel function, which may not be resolvable
111 // here. For example, resolving that kernel function may need additional
112 // kernel arguments.
113 llvm::APInt Zero(SemaRef.Context.getTypeSize(SemaRef.Context.IntTy), 0);
114 Args.push_back(IntegerLiteral::Create(SemaRef.Context, Zero,
115 SemaRef.Context.IntTy, LLLLoc));
116 // Use a null pointer as the placeholder of the parameter buffer, which
117 // should be replaced with the actual allocation later, in the codegen.
118 Args.push_back(IntegerLiteral::Create(SemaRef.Context, Zero,
119 SemaRef.Context.IntTy, LLLLoc));
120 // Add the original config arguments.
121 llvm::append_range(Args, ExecConfig);
122 // Add the default blockDim if it's missing.
123 if (Args.size() < 4) {
124 llvm::APInt One(SemaRef.Context.getTypeSize(SemaRef.Context.IntTy), 1);
125 Args.push_back(IntegerLiteral::Create(SemaRef.Context, One,
126 SemaRef.Context.IntTy, LLLLoc));
127 }
128 // Add the default sharedMemSize if it's missing.
129 if (Args.size() < 5)
130 Args.push_back(IntegerLiteral::Create(SemaRef.Context, Zero,
131 SemaRef.Context.IntTy, LLLLoc));
132 // Add the default stream if it's missing.
133 if (Args.size() < 6)
134 Args.push_back(new (SemaRef.Context) CXXNullPtrLiteralExpr(
135 SemaRef.Context.NullPtrTy, LLLLoc));
136 return SemaRef.BuildCallExpr(S, ConfigDR, LLLLoc, Args, GGGLoc, nullptr,
137 /*IsExecConfig=*/true);
138 }
139 return SemaRef.BuildCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
140 /*IsExecConfig=*/true);
141}
142
144 bool HasHostAttr = false;
145 bool HasDeviceAttr = false;
146 bool HasGlobalAttr = false;
147 bool HasInvalidTargetAttr = false;
148 for (const ParsedAttr &AL : Attrs) {
149 switch (AL.getKind()) {
150 case ParsedAttr::AT_CUDAGlobal:
151 HasGlobalAttr = true;
152 break;
153 case ParsedAttr::AT_CUDAHost:
154 HasHostAttr = true;
155 break;
156 case ParsedAttr::AT_CUDADevice:
157 HasDeviceAttr = true;
158 break;
159 case ParsedAttr::AT_CUDAInvalidTarget:
160 HasInvalidTargetAttr = true;
161 break;
162 default:
163 break;
164 }
165 }
166
167 if (HasInvalidTargetAttr)
169
170 if (HasGlobalAttr)
172
173 if (HasHostAttr && HasDeviceAttr)
175
176 if (HasDeviceAttr)
178
180}
181
182template <typename A>
183static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr) {
184 return D->hasAttrs() && llvm::any_of(D->getAttrs(), [&](Attr *Attribute) {
185 return isa<A>(Attribute) &&
186 !(IgnoreImplicitAttr && Attribute->isImplicit());
187 });
188}
189
192 : S(S_) {
193 SavedCtx = S.CurCUDATargetCtx;
194 assert(K == SemaCUDA::CTCK_InitGlobalVar);
195 auto *VD = dyn_cast_or_null<VarDecl>(D);
196 if (VD && VD->hasGlobalStorage() && !VD->isStaticLocal()) {
198 if ((hasAttr<CUDADeviceAttr>(VD, /*IgnoreImplicit=*/true) &&
199 !hasAttr<CUDAHostAttr>(VD, /*IgnoreImplicit=*/true)) ||
200 hasAttr<CUDASharedAttr>(VD, /*IgnoreImplicit=*/true) ||
201 hasAttr<CUDAConstantAttr>(VD, /*IgnoreImplicit=*/true))
203 S.CurCUDATargetCtx = {Target, K, VD};
204 }
205}
206
207/// IdentifyTarget - Determine the CUDA compilation target for this function
209 bool IgnoreImplicitHDAttr) {
210 // Code that lives outside a function gets the target from CurCUDATargetCtx.
211 if (D == nullptr)
212 return CurCUDATargetCtx.Target;
213
214 // C++ deduction guides are never codegen'ed and only participate in template
215 // argument deduction. Treat them as if they were always host+device so that
216 // CUDA/HIP target checking never rejects their use based solely on target.
219
220 if (D->hasAttr<CUDAInvalidTargetAttr>())
222
223 if (D->hasAttr<CUDAGlobalAttr>())
225
226 if (D->isConsteval())
228
229 if (hasAttr<CUDADeviceAttr>(D, IgnoreImplicitHDAttr)) {
230 if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr))
233 } else if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr)) {
235 } else if ((D->isImplicit() || !D->isUserProvided()) &&
236 !IgnoreImplicitHDAttr) {
237 // Some implicit declarations (like intrinsic functions) are not marked.
238 // Set the most lenient target on them for maximal flexibility.
240 }
241
243}
244
245/// IdentifyTarget - Determine the CUDA compilation target for this variable.
247 if (Var->hasAttr<HIPManagedAttr>())
248 return CVT_Unified;
249 // Only constexpr and const variabless with implicit constant attribute
250 // are emitted on both sides. Such variables are promoted to device side
251 // only if they have static constant initializers on device side.
252 if ((Var->isConstexpr() || Var->getType().isConstQualified()) &&
253 Var->hasAttr<CUDAConstantAttr>() &&
255 return CVT_Both;
256 if (Var->hasAttr<CUDADeviceAttr>() || Var->hasAttr<CUDAConstantAttr>() ||
257 Var->hasAttr<CUDASharedAttr>() ||
260 return CVT_Device;
261 // Function-scope static variable without explicit device or constant
262 // attribute are emitted
263 // - on both sides in host device functions
264 // - on device side in device or global functions
265 if (auto *FD = dyn_cast<FunctionDecl>(Var->getDeclContext())) {
266 switch (IdentifyTarget(FD)) {
268 return CVT_Both;
271 return CVT_Device;
272 default:
273 return CVT_Host;
274 }
275 }
276 return CVT_Host;
277}
278
279// * CUDA Call preference table
280//
281// F - from,
282// T - to
283// Ph - preference in host mode
284// Pd - preference in device mode
285// H - handled in (x)
286// Preferences: N:native, SS:same side, HD:host-device, WS:wrong side, --:never.
287//
288// | F | T | Ph | Pd | H |
289// |----+----+-----+-----+-----+
290// | d | d | N | N | (c) |
291// | d | g | -- | -- | (a) |
292// | d | h | -- | -- | (e) |
293// | d | hd | HD | HD | (b) |
294// | g | d | N | N | (c) |
295// | g | g | -- | -- | (a) |
296// | g | h | -- | -- | (e) |
297// | g | hd | HD | HD | (b) |
298// | h | d | -- | -- | (e) |
299// | h | g | N | N | (c) |
300// | h | h | N | N | (c) |
301// | h | hd | HD | HD | (b) |
302// | hd | d | WS | SS | (d) |
303// | hd | g | SS | -- |(d/a)|
304// | hd | h | SS | WS | (d) |
305// | hd | hd | HD | HD | (b) |
306
309 const FunctionDecl *Callee) {
310 assert(Callee && "Callee must be valid.");
311
312 // Treat ctor/dtor as host device function in device var initializer to allow
313 // trivial ctor/dtor without device attr to be used. Non-trivial ctor/dtor
314 // will be diagnosed by checkAllowedInitializer.
315 if (Caller == nullptr && CurCUDATargetCtx.Kind == CTCK_InitGlobalVar &&
318 return CFP_HostDevice;
319
320 CUDAFunctionTarget CallerTarget = IdentifyTarget(Caller);
321 CUDAFunctionTarget CalleeTarget = IdentifyTarget(Callee);
322
323 // If one of the targets is invalid, the check always fails, no matter what
324 // the other target is.
325 if (CallerTarget == CUDAFunctionTarget::InvalidTarget ||
326 CalleeTarget == CUDAFunctionTarget::InvalidTarget)
327 return CFP_Never;
328
329 // (a) Call global from either global or device contexts is allowed as part
330 // of CUDA's dynamic parallelism support.
331 if (CalleeTarget == CUDAFunctionTarget::Global &&
332 (CallerTarget == CUDAFunctionTarget::Global ||
333 CallerTarget == CUDAFunctionTarget::Device))
334 return CFP_Native;
335
336 // (b) Calling HostDevice is OK for everyone.
337 if (CalleeTarget == CUDAFunctionTarget::HostDevice)
338 return CFP_HostDevice;
339
340 // (c) Best case scenarios
341 if (CalleeTarget == CallerTarget ||
342 (CallerTarget == CUDAFunctionTarget::Host &&
343 CalleeTarget == CUDAFunctionTarget::Global) ||
344 (CallerTarget == CUDAFunctionTarget::Global &&
345 CalleeTarget == CUDAFunctionTarget::Device))
346 return CFP_Native;
347
348 // HipStdPar mode is special, in that assessing whether a device side call to
349 // a host target is deferred to a subsequent pass, and cannot unambiguously be
350 // adjudicated in the AST, hence we optimistically allow them to pass here.
351 if (getLangOpts().HIPStdPar &&
352 (CallerTarget == CUDAFunctionTarget::Global ||
353 CallerTarget == CUDAFunctionTarget::Device ||
354 CallerTarget == CUDAFunctionTarget::HostDevice) &&
355 CalleeTarget == CUDAFunctionTarget::Host)
356 return CFP_HostDevice;
357
358 // (d) HostDevice behavior depends on compilation mode.
359 if (CallerTarget == CUDAFunctionTarget::HostDevice) {
360 // It's OK to call a compilation-mode matching function from an HD one.
361 if ((getLangOpts().CUDAIsDevice &&
362 (CalleeTarget == CUDAFunctionTarget::Device ||
363 CalleeTarget == CUDAFunctionTarget::Global)) ||
364 (!getLangOpts().CUDAIsDevice &&
365 (CalleeTarget == CUDAFunctionTarget::Host ||
366 CalleeTarget == CUDAFunctionTarget::Global)))
367 return CFP_SameSide;
368
369 // Calls from HD to non-mode-matching functions (i.e., to host functions
370 // when compiling in device mode or to device functions when compiling in
371 // host mode) are allowed at the sema level, but eventually rejected if
372 // they're ever codegened. TODO: Reject said calls earlier.
373 return CFP_WrongSide;
374 }
375
376 // (e) Calling across device/host boundary is not something you should do.
377 if ((CallerTarget == CUDAFunctionTarget::Host &&
378 CalleeTarget == CUDAFunctionTarget::Device) ||
379 (CallerTarget == CUDAFunctionTarget::Device &&
380 CalleeTarget == CUDAFunctionTarget::Host) ||
381 (CallerTarget == CUDAFunctionTarget::Global &&
382 CalleeTarget == CUDAFunctionTarget::Host))
383 return CFP_Never;
384
385 llvm_unreachable("All cases should've been handled by now.");
386}
387
388template <typename AttrT> static bool hasImplicitAttr(const FunctionDecl *D) {
389 if (!D)
390 return false;
391 if (auto *A = D->getAttr<AttrT>())
392 return A->isImplicit();
393 return D->isImplicit();
394}
395
397 bool IsImplicitDevAttr = hasImplicitAttr<CUDADeviceAttr>(D);
398 bool IsImplicitHostAttr = hasImplicitAttr<CUDAHostAttr>(D);
399 return IsImplicitDevAttr && IsImplicitHostAttr;
400}
401
403 const FunctionDecl *Caller,
404 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches) {
405 if (Matches.size() <= 1)
406 return;
407
408 using Pair = std::pair<DeclAccessPair, FunctionDecl *>;
409
410 // Gets the CUDA function preference for a call from Caller to Match.
411 auto GetCFP = [&](const Pair &Match) {
412 return IdentifyPreference(Caller, Match.second);
413 };
414
415 // Find the best call preference among the functions in Matches.
416 CUDAFunctionPreference BestCFP =
417 GetCFP(*llvm::max_element(Matches, [&](const Pair &M1, const Pair &M2) {
418 return GetCFP(M1) < GetCFP(M2);
419 }));
420
421 // Erase all functions with lower priority.
422 llvm::erase_if(Matches,
423 [&](const Pair &Match) { return GetCFP(Match) < BestCFP; });
424}
425
426/// When an implicitly-declared special member has to invoke more than one
427/// base/field special member, conflicts may occur in the targets of these
428/// members. For example, if one base's member __host__ and another's is
429/// __device__, it's a conflict.
430/// This function figures out if the given targets \param Target1 and
431/// \param Target2 conflict, and if they do not it fills in
432/// \param ResolvedTarget with a target that resolves for both calls.
433/// \return true if there's a conflict, false otherwise.
434static bool
436 CUDAFunctionTarget Target2,
437 CUDAFunctionTarget *ResolvedTarget) {
438 // Only free functions and static member functions may be global.
439 assert(Target1 != CUDAFunctionTarget::Global);
440 assert(Target2 != CUDAFunctionTarget::Global);
441
442 if (Target1 == CUDAFunctionTarget::HostDevice) {
443 *ResolvedTarget = Target2;
444 } else if (Target2 == CUDAFunctionTarget::HostDevice) {
445 *ResolvedTarget = Target1;
446 } else if (Target1 != Target2) {
447 return true;
448 } else {
449 *ResolvedTarget = Target1;
450 }
451
452 return false;
453}
454
457 CXXMethodDecl *MemberDecl,
458 bool ConstRHS,
459 bool Diagnose) {
460 // If MemberDecl is virtual destructor of an explicit template class
461 // instantiation, it must be emitted, therefore it needs to be inferred
462 // conservatively by ignoring implicit host/device attrs of member and parent
463 // dtors called by it. Also, it needs to be checed by deferred diag visitor.
464 bool IsExpVDtor = false;
465 if (isa<CXXDestructorDecl>(MemberDecl) && MemberDecl->isVirtual()) {
466 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(ClassDecl)) {
467 TemplateSpecializationKind TSK = Spec->getTemplateSpecializationKind();
468 IsExpVDtor = TSK == TSK_ExplicitInstantiationDeclaration ||
470 }
471 }
472 if (IsExpVDtor)
473 SemaRef.DeclsToCheckForDeferredDiags.insert(MemberDecl);
474
475 // If the defaulted special member is defined lexically outside of its
476 // owning class, or the special member already has explicit device or host
477 // attributes, do not infer.
478 bool InClass = MemberDecl->getLexicalParent() == MemberDecl->getParent();
479 bool HasH = MemberDecl->hasAttr<CUDAHostAttr>();
480 bool HasD = MemberDecl->hasAttr<CUDADeviceAttr>();
481 bool HasExplicitAttr =
482 (HasD && !MemberDecl->getAttr<CUDADeviceAttr>()->isImplicit()) ||
483 (HasH && !MemberDecl->getAttr<CUDAHostAttr>()->isImplicit());
484 if (!InClass || HasExplicitAttr)
485 return false;
486
487 std::optional<CUDAFunctionTarget> InferredTarget;
488
489 // We're going to invoke special member lookup; mark that these special
490 // members are called from this one, and not from its caller.
491 Sema::ContextRAII MethodContext(SemaRef, MemberDecl);
492
493 // Look for special members in base classes that should be invoked from here.
494 // Infer the target of this member base on the ones it should call.
495 // Skip direct and indirect virtual bases for abstract classes, except for
496 // destructors — the complete destructor variant destroys virtual bases
497 // regardless of whether the class is abstract.
499 for (const auto &B : ClassDecl->bases()) {
500 if (!B.isVirtual()) {
501 Bases.push_back(&B);
502 }
503 }
504
505 if (!ClassDecl->isAbstract() || CSM == CXXSpecialMemberKind::Destructor)
506 llvm::append_range(Bases, llvm::make_pointer_range(ClassDecl->vbases()));
507
508 for (const auto *B : Bases) {
509 auto *BaseClassDecl = B->getType()->getAsCXXRecordDecl();
510 if (!BaseClassDecl)
511 continue;
512
514 SemaRef.LookupSpecialMember(BaseClassDecl, CSM,
515 /* ConstArg */ ConstRHS,
516 /* VolatileArg */ false,
517 /* RValueThis */ false,
518 /* ConstThis */ false,
519 /* VolatileThis */ false);
520
521 if (!SMOR.getMethod())
522 continue;
523
524 CUDAFunctionTarget BaseMethodTarget =
525 IdentifyTarget(SMOR.getMethod(), IsExpVDtor);
526
527 if (!InferredTarget) {
528 InferredTarget = BaseMethodTarget;
529 } else {
530 bool ResolutionError = resolveCalleeCUDATargetConflict(
531 *InferredTarget, BaseMethodTarget, &*InferredTarget);
532 if (ResolutionError) {
533 if (Diagnose) {
534 Diag(ClassDecl->getLocation(),
535 diag::note_implicit_member_target_infer_collision)
536 << (unsigned)CSM << *InferredTarget << BaseMethodTarget;
537 }
538 MemberDecl->addAttr(
539 CUDAInvalidTargetAttr::CreateImplicit(getASTContext()));
540 return true;
541 }
542 }
543 }
544
545 // Same as for bases, but now for special members of fields.
546 for (const auto *F : ClassDecl->fields()) {
547 if (F->isInvalidDecl()) {
548 continue;
549 }
550
551 auto *FieldRecDecl =
553 if (!FieldRecDecl)
554 continue;
555
557 SemaRef.LookupSpecialMember(FieldRecDecl, CSM,
558 /* ConstArg */ ConstRHS && !F->isMutable(),
559 /* VolatileArg */ false,
560 /* RValueThis */ false,
561 /* ConstThis */ false,
562 /* VolatileThis */ false);
563
564 if (!SMOR.getMethod())
565 continue;
566
567 CUDAFunctionTarget FieldMethodTarget =
568 IdentifyTarget(SMOR.getMethod(), IsExpVDtor);
569
570 if (!InferredTarget) {
571 InferredTarget = FieldMethodTarget;
572 } else {
573 bool ResolutionError = resolveCalleeCUDATargetConflict(
574 *InferredTarget, FieldMethodTarget, &*InferredTarget);
575 if (ResolutionError) {
576 if (Diagnose) {
577 Diag(ClassDecl->getLocation(),
578 diag::note_implicit_member_target_infer_collision)
579 << (unsigned)CSM << *InferredTarget << FieldMethodTarget;
580 }
581 MemberDecl->addAttr(
582 CUDAInvalidTargetAttr::CreateImplicit(getASTContext()));
583 return true;
584 }
585 }
586 }
587
588 // If no target was inferred, mark this member as __host__ __device__;
589 // it's the least restrictive option that can be invoked from any target.
590 bool NeedsH = true, NeedsD = true;
591 if (InferredTarget) {
592 if (*InferredTarget == CUDAFunctionTarget::Device)
593 NeedsH = false;
594 else if (*InferredTarget == CUDAFunctionTarget::Host)
595 NeedsD = false;
596 }
597
598 // We either setting attributes first time, or the inferred ones must match
599 // previously set ones.
600 if (NeedsD && !HasD)
601 MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
602 if (NeedsH && !HasH)
603 MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
604
605 return false;
606}
607
609 if (!CD->isDefined() && CD->isTemplateInstantiation())
610 SemaRef.InstantiateFunctionDefinition(Loc, CD->getFirstDecl());
611
612 // (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
613 // empty at a point in the translation unit, if it is either a
614 // trivial constructor
615 if (CD->isTrivial())
616 return true;
617
618 // ... or it satisfies all of the following conditions:
619 // The constructor function has been defined.
620 // The constructor function has no parameters,
621 // and the function body is an empty compound statement.
622 if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
623 return false;
624
625 // Its class has no virtual functions and no virtual base classes.
626 if (CD->getParent()->isDynamicClass())
627 return false;
628
629 // Union ctor does not call ctors of its data members.
630 if (CD->getParent()->isUnion())
631 return true;
632
633 // The only form of initializer allowed is an empty constructor.
634 // This will recursively check all base classes and member initializers
635 if (!llvm::all_of(CD->inits(), [&](const CXXCtorInitializer *CI) {
636 if (const CXXConstructExpr *CE =
637 dyn_cast<CXXConstructExpr>(CI->getInit()))
638 return isEmptyConstructor(Loc, CE->getConstructor());
639 return false;
640 }))
641 return false;
642
643 return true;
644}
645
647 // No destructor -> no problem.
648 if (!DD)
649 return true;
650
651 if (!DD->isDefined() && DD->isTemplateInstantiation())
652 SemaRef.InstantiateFunctionDefinition(Loc, DD->getFirstDecl());
653
654 // (E.2.3.1, CUDA 7.5) A destructor for a class type is considered
655 // empty at a point in the translation unit, if it is either a
656 // trivial constructor
657 if (DD->isTrivial())
658 return true;
659
660 // ... or it satisfies all of the following conditions:
661 // The destructor function has been defined.
662 // and the function body is an empty compound statement.
663 if (!DD->hasTrivialBody())
664 return false;
665
666 const CXXRecordDecl *ClassDecl = DD->getParent();
667
668 // Its class has no virtual functions and no virtual base classes.
669 if (ClassDecl->isDynamicClass())
670 return false;
671
672 // Union does not have base class and union dtor does not call dtors of its
673 // data members.
674 if (DD->getParent()->isUnion())
675 return true;
676
677 // Only empty destructors are allowed. This will recursively check
678 // destructors for all base classes...
679 if (!llvm::all_of(ClassDecl->bases(), [&](const CXXBaseSpecifier &BS) {
680 if (CXXRecordDecl *RD = BS.getType()->getAsCXXRecordDecl())
681 return isEmptyDestructor(Loc, RD->getDestructor());
682 return true;
683 }))
684 return false;
685
686 // ... and member fields.
687 if (!llvm::all_of(ClassDecl->fields(), [&](const FieldDecl *Field) {
688 if (CXXRecordDecl *RD = Field->getType()
689 ->getBaseElementTypeUnsafe()
690 ->getAsCXXRecordDecl())
691 return isEmptyDestructor(Loc, RD->getDestructor());
692 return true;
693 }))
694 return false;
695
696 return true;
697}
698
699namespace {
700enum CUDAInitializerCheckKind {
701 CICK_DeviceOrConstant, // Check initializer for device/constant variable
702 CICK_Shared, // Check initializer for shared variable
703};
704
705bool IsDependentVar(VarDecl *VD) {
706 if (VD->getType()->isDependentType())
707 return true;
708 if (const auto *Init = VD->getInit())
709 return Init->isValueDependent();
710 return false;
711}
712
713// Check whether a variable has an allowed initializer for a CUDA device side
714// variable with global storage. \p VD may be a host variable to be checked for
715// potential promotion to device side variable.
716//
717// CUDA/HIP allows only empty constructors as initializers for global
718// variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
719// __shared__ variables whether they are local or not (they all are implicitly
720// static in CUDA). One exception is that CUDA allows constant initializers
721// for __constant__ and __device__ variables.
722bool HasAllowedCUDADeviceStaticInitializer(SemaCUDA &S, VarDecl *VD,
723 CUDAInitializerCheckKind CheckKind) {
724 assert(!VD->isInvalidDecl() && VD->hasGlobalStorage());
725 assert(!IsDependentVar(VD) && "do not check dependent var");
726 const Expr *Init = VD->getInit();
727 auto IsEmptyInit = [&](const Expr *Init) {
728 if (!Init)
729 return true;
730 if (const auto *CE = dyn_cast<CXXConstructExpr>(Init)) {
731 return S.isEmptyConstructor(VD->getLocation(), CE->getConstructor());
732 }
733 return false;
734 };
735 auto IsConstantInit = [&](const Expr *Init) {
736 assert(Init);
737 ASTContext::CUDAConstantEvalContextRAII EvalCtx(S.getASTContext(),
738 /*NoWronSidedVars=*/true);
739 return Init->isConstantInitializer(S.getASTContext(),
740 VD->getType()->isReferenceType());
741 };
742 auto HasEmptyDtor = [&](VarDecl *VD) {
743 if (const auto *RD = VD->getType()->getAsCXXRecordDecl())
744 return S.isEmptyDestructor(VD->getLocation(), RD->getDestructor());
745 return true;
746 };
747 if (CheckKind == CICK_Shared)
748 return IsEmptyInit(Init) && HasEmptyDtor(VD);
749 return S.getLangOpts().GPUAllowDeviceInit ||
750 ((IsEmptyInit(Init) || IsConstantInit(Init)) && HasEmptyDtor(VD));
751}
752} // namespace
753
755 // Return early if VD is inside a non-instantiated template function since
756 // the implicit constructor is not defined yet.
757 if (const FunctionDecl *FD =
758 dyn_cast_or_null<FunctionDecl>(VD->getDeclContext());
759 FD && FD->isDependentContext())
760 return;
761
762 bool IsSharedVar = VD->hasAttr<CUDASharedAttr>();
763 bool IsDeviceOrConstantVar =
764 !IsSharedVar &&
765 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>());
766 if ((IsSharedVar || IsDeviceOrConstantVar) &&
768 Diag(VD->getLocation(), diag::err_cuda_address_space_gpuvar);
769 VD->setInvalidDecl();
770 return;
771 }
772 // Do not check dependent variables since the ctor/dtor/initializer are not
773 // determined. Do it after instantiation.
774 if (VD->isInvalidDecl() || !VD->hasInit() || !VD->hasGlobalStorage() ||
775 IsDependentVar(VD))
776 return;
777 const Expr *Init = VD->getInit();
778 if (IsDeviceOrConstantVar || IsSharedVar) {
779 if (HasAllowedCUDADeviceStaticInitializer(
780 *this, VD, IsSharedVar ? CICK_Shared : CICK_DeviceOrConstant))
781 return;
782 Diag(VD->getLocation(),
783 IsSharedVar ? diag::err_shared_var_init : diag::err_dynamic_var_init)
784 << Init->getSourceRange();
785 VD->setInvalidDecl();
786 } else {
787 // This is a host-side global variable. Check that the initializer is
788 // callable from the host side.
789 const FunctionDecl *InitFn = nullptr;
790 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
791 InitFn = CE->getConstructor();
792 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
793 InitFn = CE->getDirectCallee();
794 }
795 if (InitFn) {
796 CUDAFunctionTarget InitFnTarget = IdentifyTarget(InitFn);
797 if (InitFnTarget != CUDAFunctionTarget::Host &&
798 InitFnTarget != CUDAFunctionTarget::HostDevice) {
799 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
800 << InitFnTarget << InitFn;
801 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
802 VD->setInvalidDecl();
803 }
804 }
805 }
806}
807
809 const FunctionDecl *Callee) {
810 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
811 if (!Caller)
812 return;
813
814 if (!isImplicitHostDeviceFunction(Callee))
815 return;
816
817 CUDAFunctionTarget CallerTarget = IdentifyTarget(Caller);
818
819 // Record whether an implicit host device function is used on device side.
820 if (CallerTarget != CUDAFunctionTarget::Device &&
821 CallerTarget != CUDAFunctionTarget::Global &&
822 (CallerTarget != CUDAFunctionTarget::HostDevice ||
824 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Caller))))
825 return;
826
828}
829
830// With -fcuda-host-device-constexpr, an unattributed constexpr function is
831// treated as implicitly __host__ __device__, unless:
832// * it is a variadic function (device-side variadic functions are not
833// allowed), or
834// * a __device__ function with this signature was already declared, in which
835// case in which case we output an error, unless the __device__ decl is in a
836// system header, in which case we leave the constexpr function unattributed.
837//
838// In addition, all function decls are treated as __host__ __device__ when
839// ForceHostDeviceDepth > 0 (corresponding to code within a
840// #pragma clang force_cuda_host_device_begin/end
841// pair).
843 const LookupResult &Previous) {
844 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
845
846 if (ForceHostDeviceDepth > 0) {
847 if (!NewD->hasAttr<CUDAHostAttr>())
848 NewD->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
849 if (!NewD->hasAttr<CUDADeviceAttr>())
850 NewD->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
851 return;
852 }
853
854 // If a template function has no host/device/global attributes,
855 // make it implicitly host device function.
856 if (getLangOpts().OffloadImplicitHostDeviceTemplates &&
857 !NewD->hasAttr<CUDAHostAttr>() && !NewD->hasAttr<CUDADeviceAttr>() &&
858 !NewD->hasAttr<CUDAGlobalAttr>() &&
861 NewD->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
862 NewD->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
863 return;
864 }
865
866 if (!getLangOpts().CUDAHostDeviceConstexpr || !NewD->isConstexpr() ||
867 NewD->isVariadic() || NewD->hasAttr<CUDAHostAttr>() ||
868 NewD->hasAttr<CUDADeviceAttr>() || NewD->hasAttr<CUDAGlobalAttr>())
869 return;
870
871 // Is D a __device__ function with the same signature as NewD, ignoring CUDA
872 // attributes?
873 auto IsMatchingDeviceFn = [&](NamedDecl *D) {
874 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(D))
875 D = Using->getTargetDecl();
876 FunctionDecl *OldD = D->getAsFunction();
877 return OldD && OldD->hasAttr<CUDADeviceAttr>() &&
878 !OldD->hasAttr<CUDAHostAttr>() &&
879 !SemaRef.IsOverload(NewD, OldD,
880 /* UseMemberUsingDeclRules = */ false,
881 /* ConsiderCudaAttrs = */ false);
882 };
883 auto It = llvm::find_if(Previous, IsMatchingDeviceFn);
884 if (It != Previous.end()) {
885 // We found a __device__ function with the same name and signature as NewD
886 // (ignoring CUDA attrs). This is an error unless that function is defined
887 // in a system header, in which case we simply return without making NewD
888 // host+device.
889 NamedDecl *Match = *It;
890 if (!SemaRef.getSourceManager().isInSystemHeader(Match->getLocation())) {
891 Diag(NewD->getLocation(),
892 diag::err_cuda_unattributed_constexpr_cannot_overload_device)
893 << NewD;
894 Diag(Match->getLocation(),
895 diag::note_cuda_conflicting_device_function_declared_here);
896 }
897 return;
898 }
899
900 NewD->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
901 NewD->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
902}
903
904// TODO: `__constant__` memory may be a limited resource for certain targets.
905// A safeguard may be needed at the end of compilation pipeline if
906// `__constant__` memory usage goes beyond limit.
908 // Do not promote dependent variables since the cotr/dtor/initializer are
909 // not determined. Do it after instantiation.
910 if (getLangOpts().CUDAIsDevice && !VD->hasAttr<CUDAConstantAttr>() &&
911 !VD->hasAttr<CUDASharedAttr>() &&
912 (VD->isFileVarDecl() || VD->isStaticDataMember()) &&
913 !IsDependentVar(VD) &&
914 ((VD->isConstexpr() || VD->getType().isConstQualified()) &&
915 HasAllowedCUDADeviceStaticInitializer(*this, VD,
916 CICK_DeviceOrConstant))) {
917 VD->addAttr(CUDAConstantAttr::CreateImplicit(getASTContext()));
918 }
919}
920
922 unsigned DiagID) {
923 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
924 FunctionDecl *CurFunContext =
925 SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
926 SemaDiagnosticBuilder::Kind DiagKind = [&] {
927 if (!CurFunContext)
928 return SemaDiagnosticBuilder::K_Nop;
929 switch (CurrentTarget()) {
932 return SemaDiagnosticBuilder::K_Immediate;
934 // An HD function counts as host code if we're compiling for host, and
935 // device code if we're compiling for device. Defer any errors in device
936 // mode until the function is known-emitted.
937 if (!getLangOpts().CUDAIsDevice)
938 return SemaDiagnosticBuilder::K_Nop;
939 if (SemaRef.IsLastErrorImmediate &&
940 getDiagnostics().getDiagnosticIDs()->isNote(DiagID))
941 return SemaDiagnosticBuilder::K_Immediate;
942 return (SemaRef.getEmissionStatus(CurFunContext) ==
944 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
945 : SemaDiagnosticBuilder::K_Deferred;
946 default:
947 return SemaDiagnosticBuilder::K_Nop;
948 }
949 }();
950 return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, CurFunContext, SemaRef);
951}
952
954 unsigned DiagID) {
955 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
956 FunctionDecl *CurFunContext =
957 SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
958 SemaDiagnosticBuilder::Kind DiagKind = [&] {
959 if (!CurFunContext)
960 return SemaDiagnosticBuilder::K_Nop;
961 switch (CurrentTarget()) {
963 return SemaDiagnosticBuilder::K_Immediate;
965 // An HD function counts as host code if we're compiling for host, and
966 // device code if we're compiling for device. Defer any errors in device
967 // mode until the function is known-emitted.
968 if (getLangOpts().CUDAIsDevice)
969 return SemaDiagnosticBuilder::K_Nop;
970 if (SemaRef.IsLastErrorImmediate &&
971 getDiagnostics().getDiagnosticIDs()->isNote(DiagID))
972 return SemaDiagnosticBuilder::K_Immediate;
973 return (SemaRef.getEmissionStatus(CurFunContext) ==
975 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
976 : SemaDiagnosticBuilder::K_Deferred;
977 default:
978 return SemaDiagnosticBuilder::K_Nop;
979 }
980 }();
981 return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, CurFunContext, SemaRef);
982}
983
985 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
986 assert(Callee && "Callee may not be null.");
987
988 const auto &ExprEvalCtx = SemaRef.currentEvaluationContext();
989 if (ExprEvalCtx.isUnevaluated() || ExprEvalCtx.isConstantEvaluated() ||
990 ExprEvalCtx.isDiscardedStatementContext())
991 return true;
992
993 // C++ deduction guides participate in overload resolution but are not
994 // callable functions and are never codegen'ed. Treat them as always
995 // allowed for CUDA/HIP compatibility checking.
996 if (isa<CXXDeductionGuideDecl>(Callee))
997 return true;
998
999 // FIXME: Is bailing out early correct here? Should we instead assume that
1000 // the caller is a global initializer?
1001 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
1002 if (!Caller)
1003 return true;
1004
1005 // If the caller is known-emitted, mark the callee as known-emitted.
1006 // Otherwise, mark the call in our call graph so we can traverse it later.
1007 bool CallerKnownEmitted = SemaRef.getEmissionStatus(Caller) ==
1009 SemaDiagnosticBuilder::Kind DiagKind = [this, Caller, Callee,
1010 CallerKnownEmitted] {
1011 switch (IdentifyPreference(Caller, Callee)) {
1012 case CFP_Never:
1013 case CFP_WrongSide:
1014 assert(Caller && "Never/wrongSide calls require a non-null caller");
1015 // If we know the caller will be emitted, we know this wrong-side call
1016 // will be emitted, so it's an immediate error. Otherwise, defer the
1017 // error until we know the caller is emitted.
1018 return CallerKnownEmitted
1019 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
1020 : SemaDiagnosticBuilder::K_Deferred;
1021 default:
1022 return SemaDiagnosticBuilder::K_Nop;
1023 }
1024 }();
1025
1026 bool IsDeviceKernelCall = Callee == getASTContext().getcudaLaunchDeviceDecl();
1027 bool CallerHD = Caller && Caller->hasAttr<CUDAHostAttr>() &&
1028 Caller->hasAttr<CUDADeviceAttr>();
1029 bool CallerDiscard = SemaRef.getEmissionStatus(Caller) ==
1031 bool RDC = getLangOpts().GPURelocatableDeviceCode;
1032 if (IsDeviceKernelCall && !(CallerHD && CallerDiscard) && !RDC) {
1033 Diag(Loc, diag::err_cuda_device_kernel_launch_require_rdc);
1034 return false;
1035 }
1036
1037 if (DiagKind == SemaDiagnosticBuilder::K_Nop) {
1038 // For -fgpu-rdc, keep track of external kernels used by host functions.
1039 if (getLangOpts().CUDAIsDevice && RDC &&
1040 Callee->hasAttr<CUDAGlobalAttr>() && !Callee->isDefined() &&
1041 (!Caller || (!Caller->getDescribedFunctionTemplate() &&
1042 getASTContext().GetGVALinkageForFunction(Caller) ==
1045 return true;
1046 }
1047
1048 // Avoid emitting this error twice for the same location. Using a hashtable
1049 // like this is unfortunate, but because we must continue parsing as normal
1050 // after encountering a deferred error, it's otherwise very tricky for us to
1051 // ensure that we only emit this deferred error once.
1052 if (!LocsWithCUDACallDiags.insert({Caller, Loc}).second)
1053 return true;
1054
1055 SemaDiagnosticBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller,
1056 SemaRef)
1057 << IdentifyTarget(Callee) << /*function*/ 0 << Callee
1058 << IdentifyTarget(Caller);
1059 if (!Callee->getBuiltinID())
1060 SemaDiagnosticBuilder(DiagKind, Callee->getLocation(),
1061 diag::note_previous_decl, Caller, SemaRef)
1062 << Callee;
1063 return DiagKind != SemaDiagnosticBuilder::K_Immediate &&
1064 DiagKind != SemaDiagnosticBuilder::K_ImmediateWithCallStack;
1065}
1066
1067// Check the wrong-sided reference capture of lambda for CUDA/HIP.
1068// A lambda function may capture a stack variable by reference when it is
1069// defined and uses the capture by reference when the lambda is called. When
1070// the capture and use happen on different sides, the capture is invalid and
1071// should be diagnosed.
1073 const sema::Capture &Capture) {
1074 // In host compilation we only need to check lambda functions emitted on host
1075 // side. In such lambda functions, a reference capture is invalid only
1076 // if the lambda structure is populated by a device function or kernel then
1077 // is passed to and called by a host function. However that is impossible,
1078 // since a device function or kernel can only call a device function, also a
1079 // kernel cannot pass a lambda back to a host function since we cannot
1080 // define a kernel argument type which can hold the lambda before the lambda
1081 // itself is defined.
1082 if (!getLangOpts().CUDAIsDevice)
1083 return;
1084
1085 // File-scope lambda can only do init captures for global variables, which
1086 // results in passing by value for these global variables.
1087 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
1088 if (!Caller)
1089 return;
1090
1091 // In device compilation, we only need to check lambda functions which are
1092 // emitted on device side. For such lambdas, a reference capture is invalid
1093 // only if the lambda structure is populated by a host function then passed
1094 // to and called in a device function or kernel.
1095 bool CalleeIsDevice = Callee->hasAttr<CUDADeviceAttr>();
1096 bool CallerIsHost =
1097 !Caller->hasAttr<CUDAGlobalAttr>() && !Caller->hasAttr<CUDADeviceAttr>();
1098 bool ShouldCheck = CalleeIsDevice && CallerIsHost;
1099 if (!ShouldCheck || !Capture.isReferenceCapture())
1100 return;
1101 auto DiagKind = SemaDiagnosticBuilder::K_Deferred;
1102 if (Capture.isVariableCapture() && !getLangOpts().HIPStdPar) {
1104 diag::err_capture_bad_target, Callee, SemaRef)
1105 << Capture.getVariable();
1106 } else if (Capture.isThisCapture()) {
1107 // Capture of this pointer is allowed since this pointer may be pointing to
1108 // managed memory which is accessible on both device and host sides. It only
1109 // results in invalid memory access if this pointer points to memory not
1110 // accessible on device side.
1112 diag::warn_maybe_capture_bad_target_this_ptr, Callee,
1113 SemaRef);
1114 }
1115}
1116
1118 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
1119 if (Method->hasAttr<CUDAHostAttr>() || Method->hasAttr<CUDADeviceAttr>())
1120 return;
1121 Method->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
1122 Method->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
1123}
1124
1126 const LookupResult &Previous) {
1127 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
1128 CUDAFunctionTarget NewTarget = IdentifyTarget(NewFD);
1129 for (NamedDecl *OldND : Previous) {
1130 FunctionDecl *OldFD = OldND->getAsFunction();
1131 if (!OldFD)
1132 continue;
1133
1134 CUDAFunctionTarget OldTarget = IdentifyTarget(OldFD);
1135 // Don't allow HD and global functions to overload other functions with the
1136 // same signature. We allow overloading based on CUDA attributes so that
1137 // functions can have different implementations on the host and device, but
1138 // HD/global functions "exist" in some sense on both the host and device, so
1139 // should have the same implementation on both sides.
1140 if (NewTarget != OldTarget &&
1141 !SemaRef.IsOverload(NewFD, OldFD, /* UseMemberUsingDeclRules = */ false,
1142 /* ConsiderCudaAttrs = */ false)) {
1143 if ((NewTarget == CUDAFunctionTarget::HostDevice &&
1144 !(getLangOpts().OffloadImplicitHostDeviceTemplates &&
1146 OldTarget == CUDAFunctionTarget::Device)) ||
1147 (OldTarget == CUDAFunctionTarget::HostDevice &&
1148 !(getLangOpts().OffloadImplicitHostDeviceTemplates &&
1150 NewTarget == CUDAFunctionTarget::Device)) ||
1151 (NewTarget == CUDAFunctionTarget::Global) ||
1152 (OldTarget == CUDAFunctionTarget::Global)) {
1153 Diag(NewFD->getLocation(), diag::err_cuda_ovl_target)
1154 << NewTarget << NewFD->getDeclName() << OldTarget << OldFD;
1155 Diag(OldFD->getLocation(), diag::note_previous_declaration);
1156 NewFD->setInvalidDecl();
1157 break;
1158 }
1159 if ((NewTarget == CUDAFunctionTarget::Host &&
1160 OldTarget == CUDAFunctionTarget::Device) ||
1161 (NewTarget == CUDAFunctionTarget::Device &&
1162 OldTarget == CUDAFunctionTarget::Host)) {
1163 Diag(NewFD->getLocation(), diag::warn_offload_incompatible_redeclare)
1164 << NewTarget << OldTarget;
1165 Diag(OldFD->getLocation(), diag::note_previous_declaration);
1166 }
1167 }
1168 }
1169}
1170
1171template <typename AttrTy>
1173 const FunctionDecl &TemplateFD) {
1174 if (AttrTy *Attribute = TemplateFD.getAttr<AttrTy>()) {
1175 AttrTy *Clone = Attribute->clone(S.Context);
1176 Clone->setInherited(true);
1177 FD->addAttr(Clone);
1178 }
1179}
1180
1182 const FunctionTemplateDecl &TD) {
1183 const FunctionDecl &TemplateFD = *TD.getTemplatedDecl();
1187}
1188
1190 if (getLangOpts().OffloadViaLLVM)
1191 return "__llvmPushCallConfiguration";
1192
1193 if (getLangOpts().HIP)
1194 return getLangOpts().HIPUseNewLaunchAPI ? "__hipPushCallConfiguration"
1195 : "hipConfigureCall";
1196
1197 // New CUDA kernel launch sequence.
1198 if (CudaFeatureEnabled(getASTContext().getTargetInfo().getSDKVersion(),
1200 return "__cudaPushCallConfiguration";
1201
1202 // Legacy CUDA kernel configuration call
1203 return "cudaConfigureCall";
1204}
1205
1207 return "cudaGetParameterBuffer";
1208}
1209
1211 return "cudaLaunchDevice";
1212}
1213
1214// Record any local constexpr variables that are passed one way on the host
1215// and another on the device.
1217 MultiExprArg Arguments, OverloadCandidateSet &Candidates) {
1218 sema::LambdaScopeInfo *LambdaInfo = SemaRef.getCurLambda();
1219 if (!LambdaInfo)
1220 return;
1221
1222 for (unsigned I = 0; I < Arguments.size(); ++I) {
1223 auto *DeclRef = dyn_cast<DeclRefExpr>(Arguments[I]);
1224 if (!DeclRef)
1225 continue;
1226 auto *Variable = dyn_cast<VarDecl>(DeclRef->getDecl());
1227 if (!Variable || !Variable->isLocalVarDecl() || !Variable->isConstexpr())
1228 continue;
1229
1230 bool HostByValue = false, HostByRef = false;
1231 bool DeviceByValue = false, DeviceByRef = false;
1232
1233 for (OverloadCandidate &Candidate : Candidates) {
1234 FunctionDecl *Callee = Candidate.Function;
1235 if (!Callee || I >= Callee->getNumParams())
1236 continue;
1237
1241 continue;
1242
1243 bool CoversHost = (Target == CUDAFunctionTarget::Host ||
1245 bool CoversDevice = (Target == CUDAFunctionTarget::Device ||
1247
1248 bool IsRef = Callee->getParamDecl(I)->getType()->isReferenceType();
1249 HostByValue |= CoversHost && !IsRef;
1250 HostByRef |= CoversHost && IsRef;
1251 DeviceByValue |= CoversDevice && !IsRef;
1252 DeviceByRef |= CoversDevice && IsRef;
1253 }
1254
1255 if ((HostByValue && DeviceByRef) || (HostByRef && DeviceByValue))
1256 LambdaInfo->CUDAPotentialODRUsedVars.insert(Variable);
1257 }
1258}
Defines the clang::ASTContext interface.
static bool hasImplicitAttr(const ValueDecl *decl)
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Previous
The previous token in the unwrapped line.
Defines the clang::Preprocessor interface.
static bool resolveCalleeCUDATargetConflict(CUDAFunctionTarget Target1, CUDAFunctionTarget Target2, CUDAFunctionTarget *ResolvedTarget)
When an implicitly-declared special member has to invoke more than one base/field special member,...
Definition SemaCUDA.cpp:435
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:183
static void copyAttrIfPresent(Sema &S, FunctionDecl *FD, const FunctionDecl &TemplateFD)
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
FunctionDecl * getcudaGetParameterBufferDecl()
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
llvm::DenseSet< const FunctionDecl * > CUDAImplicitHostDeviceFunUsedByDevice
Keep track of CUDA/HIP implicit host device functions used on device side in device compilation.
FunctionDecl * getcudaConfigureCallDecl()
FunctionDecl * getcudaLaunchDeviceDecl()
Attr - This represents one attribute.
Definition Attr.h:46
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Represents a C++ constructor within a class.
Definition DeclCXX.h:2620
Represents a C++ base or member initializer.
Definition DeclCXX.h:2385
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
bool isVirtual() const
Definition DeclCXX.h:2187
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2271
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
base_class_range bases()
Definition DeclCXX.h:608
base_class_range vbases()
Definition DeclCXX.h:625
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1221
bool isDynamicClass() const
Definition DeclCXX.h:574
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2138
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:581
bool hasAttrs() const
Definition DeclBase.h:526
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
AttrVec & getAttrs()
Definition DeclBase.h:532
bool hasAttr() const
Definition DeclBase.h:585
This represents one expression.
Definition Expr.h:112
Represents a member of a struct/union/class.
Definition Decl.h:3178
Represents a function declaration or definition.
Definition Decl.h:2018
bool hasTrivialBody() const
Returns whether the function has a trivial body that does not require any specific codegen.
Definition Decl.cpp:3205
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4200
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4188
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2395
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3128
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4252
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2488
bool isConsteval() const
Definition Decl.h:2500
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2428
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3821
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:3241
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:975
Represents the results of name lookup.
Definition Lookup.h:147
This represents a decl that may have a name.
Definition Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
A (possibly-)qualified type.
Definition TypeBase.h:937
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8476
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8509
LangAS getAddressSpace() const
Definition TypeBase.h:571
field_range fields() const
Definition Decl.h:4546
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
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:111
SemaBase(Sema &S)
Definition SemaBase.cpp:7
ASTContext & getASTContext() const
Definition SemaBase.cpp:9
Sema & SemaRef
Definition SemaBase.h:40
const LangOptions & getLangOpts() const
Definition SemaBase.cpp:11
DiagnosticsEngine & getDiagnostics() const
Definition SemaBase.cpp:10
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
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:39
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:754
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:808
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:44
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:208
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:842
ExprResult ActOnExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc)
Definition SemaCUDA.cpp:52
bool isEmptyConstructor(SourceLocation Loc, CXXConstructorDecl *CD)
Definition SemaCUDA.cpp:608
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:646
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:153
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:953
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:455
struct clang::SemaCUDA::CUDATargetContext CurCUDATargetCtx
CUDATargetContextKind
Defines kinds of CUDA global host/device context where a function may be called.
Definition SemaCUDA.h:130
@ CTCK_InitGlobalVar
Unknown context.
Definition SemaCUDA.h:132
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:921
llvm::DenseSet< FunctionDeclAndLoc > LocsWithCUDACallDiags
FunctionDecls and SourceLocations for which CheckCall has emitted a (maybe deferred) "bad call" diagn...
Definition SemaCUDA.h:73
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition SemaCUDA.cpp:984
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:396
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:907
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:402
SemaCUDA(Sema &S)
Definition SemaCUDA.cpp:29
void SetLambdaAttrs(CXXMethodDecl *Method)
Set device or host device attributes on the given lambda operator() method.
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:308
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:121
@ CVT_Both
Emitted on host side only.
Definition SemaCUDA.h:122
@ CVT_Unified
Emitted on both sides with different addresses.
Definition SemaCUDA.h:123
A RAII object to temporarily push a declaration context.
Definition Sema.h:3526
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition Sema.h:9373
CXXMethodDecl * getMethod() const
Definition Sema.h:9385
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
ASTContext & Context
Definition Sema.h:1308
Encodes a location in the source.
bool isUnion() const
Definition Decl.h:3946
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isReferenceType() const
Definition TypeBase.h:8697
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
Definition Type.cpp:5460
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2837
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
Definition Type.cpp:5469
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3404
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1582
bool hasInit() const
Definition Decl.cpp:2377
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1296
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1239
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1355
const Expr * getInit() const
Definition Decl.h:1381
ValueDecl * getVariable() const
Definition ScopeInfo.h:679
bool isVariableCapture() const
Definition ScopeInfo.h:654
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:690
bool isThisCapture() const
Definition ScopeInfo.h:653
bool isReferenceCapture() const
Definition ScopeInfo.h:659
llvm::SmallPtrSet< VarDecl *, 4 > CUDAPotentialODRUsedVars
Variables that are potentially ODR-used in CUDA/HIP.
Definition ScopeInfo.h:957
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ GVA_StrongExternal
Definition Linkage.h:76
CUDAFunctionTarget
Definition Cuda.h:61
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
bool CudaFeatureEnabled(llvm::VersionTuple, CudaFeature)
Definition Cuda.cpp:163
ExprResult ExprError()
Definition Ownership.h:265
@ CUDA_USES_NEW_LAUNCH
Definition Cuda.h:78
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:933
SemaCUDA::CUDATargetContext SavedCtx
Definition SemaCUDA.h:146
CUDATargetContextRAII(SemaCUDA &S_, SemaCUDA::CUDATargetContextKind K, Decl *D)
Definition SemaCUDA.cpp:190