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