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
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 the defaulted special member is defined lexically outside of its
465 // owning class, or the special member already has explicit device or host
466 // attributes, do not infer.
467 bool InClass = MemberDecl->getLexicalParent() == MemberDecl->getParent();
468 bool HasH = MemberDecl->hasAttr<CUDAHostAttr>();
469 bool HasD = MemberDecl->hasAttr<CUDADeviceAttr>();
470 bool HasExplicitAttr =
471 (HasD && !MemberDecl->getAttr<CUDADeviceAttr>()->isImplicit()) ||
472 (HasH && !MemberDecl->getAttr<CUDAHostAttr>()->isImplicit());
473 if (!InClass || HasExplicitAttr)
474 return false;
475
476 std::optional<CUDAFunctionTarget> InferredTarget;
477
478 // We're going to invoke special member lookup; mark that these special
479 // members are called from this one, and not from its caller.
480 Sema::ContextRAII MethodContext(SemaRef, MemberDecl);
481
482 // Look for special members in base classes that should be invoked from here.
483 // Infer the target of this member base on the ones it should call.
484 // Skip direct and indirect virtual bases for abstract classes, except for
485 // destructors — the complete destructor variant destroys virtual bases
486 // regardless of whether the class is abstract.
488 for (const auto &B : ClassDecl->bases()) {
489 if (!B.isVirtual()) {
490 Bases.push_back(&B);
491 }
492 }
493
494 if (!ClassDecl->isAbstract() || CSM == CXXSpecialMemberKind::Destructor)
495 llvm::append_range(Bases, llvm::make_pointer_range(ClassDecl->vbases()));
496
497 for (const auto *B : Bases) {
498 auto *BaseClassDecl = B->getType()->getAsCXXRecordDecl();
499 if (!BaseClassDecl)
500 continue;
501
503 SemaRef.LookupSpecialMember(BaseClassDecl, CSM,
504 /* ConstArg */ ConstRHS,
505 /* VolatileArg */ false,
506 /* RValueThis */ false,
507 /* ConstThis */ false,
508 /* VolatileThis */ false);
509
510 if (!SMOR.getMethod())
511 continue;
512
513 CUDAFunctionTarget BaseMethodTarget = IdentifyTarget(SMOR.getMethod());
514
515 if (!InferredTarget) {
516 InferredTarget = BaseMethodTarget;
517 } else {
518 bool ResolutionError = resolveCalleeCUDATargetConflict(
519 *InferredTarget, BaseMethodTarget, &*InferredTarget);
520 if (ResolutionError) {
521 if (Diagnose) {
522 Diag(ClassDecl->getLocation(),
523 diag::note_implicit_member_target_infer_collision)
524 << (unsigned)CSM << *InferredTarget << BaseMethodTarget;
525 }
526 MemberDecl->addAttr(
527 CUDAInvalidTargetAttr::CreateImplicit(getASTContext()));
528 return true;
529 }
530 }
531 }
532
533 // Same as for bases, but now for special members of fields.
534 for (const auto *F : ClassDecl->fields()) {
535 if (F->isInvalidDecl()) {
536 continue;
537 }
538
539 auto *FieldRecDecl =
541 if (!FieldRecDecl)
542 continue;
543
545 SemaRef.LookupSpecialMember(FieldRecDecl, CSM,
546 /* ConstArg */ ConstRHS && !F->isMutable(),
547 /* VolatileArg */ false,
548 /* RValueThis */ false,
549 /* ConstThis */ false,
550 /* VolatileThis */ false);
551
552 if (!SMOR.getMethod())
553 continue;
554
555 CUDAFunctionTarget FieldMethodTarget = IdentifyTarget(SMOR.getMethod());
556
557 if (!InferredTarget) {
558 InferredTarget = FieldMethodTarget;
559 } else {
560 bool ResolutionError = resolveCalleeCUDATargetConflict(
561 *InferredTarget, FieldMethodTarget, &*InferredTarget);
562 if (ResolutionError) {
563 if (Diagnose) {
564 Diag(ClassDecl->getLocation(),
565 diag::note_implicit_member_target_infer_collision)
566 << (unsigned)CSM << *InferredTarget << FieldMethodTarget;
567 }
568 MemberDecl->addAttr(
569 CUDAInvalidTargetAttr::CreateImplicit(getASTContext()));
570 return true;
571 }
572 }
573 }
574
575 // If no target was inferred, mark this member as __host__ __device__;
576 // it's the least restrictive option that can be invoked from any target.
577 bool NeedsH = true, NeedsD = true;
578 if (InferredTarget) {
579 if (*InferredTarget == CUDAFunctionTarget::Device)
580 NeedsH = false;
581 else if (*InferredTarget == CUDAFunctionTarget::Host)
582 NeedsD = false;
583 }
584
585 // We either setting attributes first time, or the inferred ones must match
586 // previously set ones.
587 if (NeedsD && !HasD)
588 MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
589 if (NeedsH && !HasH)
590 MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
591
592 return false;
593}
594
596 if (!CD->isDefined() && CD->isTemplateInstantiation())
597 SemaRef.InstantiateFunctionDefinition(Loc, CD->getFirstDecl());
598
599 // (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
600 // empty at a point in the translation unit, if it is either a
601 // trivial constructor
602 if (CD->isTrivial())
603 return true;
604
605 // ... or it satisfies all of the following conditions:
606 // The constructor function has been defined.
607 // The constructor function has no parameters,
608 // and the function body is an empty compound statement.
609 if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
610 return false;
611
612 // Its class has no virtual functions and no virtual base classes.
613 if (CD->getParent()->isDynamicClass())
614 return false;
615
616 // Union ctor does not call ctors of its data members.
617 if (CD->getParent()->isUnion())
618 return true;
619
620 // The only form of initializer allowed is an empty constructor.
621 // This will recursively check all base classes and member initializers
622 if (!llvm::all_of(CD->inits(), [&](const CXXCtorInitializer *CI) {
623 if (const CXXConstructExpr *CE =
624 dyn_cast<CXXConstructExpr>(CI->getInit()))
625 return isEmptyConstructor(Loc, CE->getConstructor());
626 return false;
627 }))
628 return false;
629
630 return true;
631}
632
634 // No destructor -> no problem.
635 if (!DD)
636 return true;
637
638 if (!DD->isDefined() && DD->isTemplateInstantiation())
639 SemaRef.InstantiateFunctionDefinition(Loc, DD->getFirstDecl());
640
641 // (E.2.3.1, CUDA 7.5) A destructor for a class type is considered
642 // empty at a point in the translation unit, if it is either a
643 // trivial constructor
644 if (DD->isTrivial())
645 return true;
646
647 // ... or it satisfies all of the following conditions:
648 // The destructor function has been defined.
649 // and the function body is an empty compound statement.
650 if (!DD->hasTrivialBody())
651 return false;
652
653 const CXXRecordDecl *ClassDecl = DD->getParent();
654
655 // Its class has no virtual functions and no virtual base classes.
656 if (ClassDecl->isDynamicClass())
657 return false;
658
659 // Union does not have base class and union dtor does not call dtors of its
660 // data members.
661 if (DD->getParent()->isUnion())
662 return true;
663
664 // Only empty destructors are allowed. This will recursively check
665 // destructors for all base classes...
666 if (!llvm::all_of(ClassDecl->bases(), [&](const CXXBaseSpecifier &BS) {
667 if (CXXRecordDecl *RD = BS.getType()->getAsCXXRecordDecl())
668 return isEmptyDestructor(Loc, RD->getDestructor());
669 return true;
670 }))
671 return false;
672
673 // ... and member fields.
674 if (!llvm::all_of(ClassDecl->fields(), [&](const FieldDecl *Field) {
675 if (CXXRecordDecl *RD = Field->getType()
676 ->getBaseElementTypeUnsafe()
677 ->getAsCXXRecordDecl())
678 return isEmptyDestructor(Loc, RD->getDestructor());
679 return true;
680 }))
681 return false;
682
683 return true;
684}
685
686namespace {
687enum CUDAInitializerCheckKind {
688 CICK_DeviceOrConstant, // Check initializer for device/constant variable
689 CICK_Shared, // Check initializer for shared variable
690};
691
692bool IsDependentVar(VarDecl *VD) {
693 if (VD->getType()->isDependentType())
694 return true;
695 if (const auto *Init = VD->getInit())
696 return Init->isValueDependent();
697 return false;
698}
699
700// Check whether a variable has an allowed initializer for a CUDA device side
701// variable with global storage. \p VD may be a host variable to be checked for
702// potential promotion to device side variable.
703//
704// CUDA/HIP allows only empty constructors as initializers for global
705// variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
706// __shared__ variables whether they are local or not (they all are implicitly
707// static in CUDA). One exception is that CUDA allows constant initializers
708// for __constant__ and __device__ variables.
709bool HasAllowedCUDADeviceStaticInitializer(SemaCUDA &S, VarDecl *VD,
710 CUDAInitializerCheckKind CheckKind) {
711 assert(!VD->isInvalidDecl() && VD->hasGlobalStorage());
712 assert(!IsDependentVar(VD) && "do not check dependent var");
713 const Expr *Init = VD->getInit();
714 auto IsEmptyInit = [&](const Expr *Init) {
715 if (!Init)
716 return true;
717 if (const auto *CE = dyn_cast<CXXConstructExpr>(Init)) {
718 return S.isEmptyConstructor(VD->getLocation(), CE->getConstructor());
719 }
720 return false;
721 };
722 auto IsConstantInit = [&](const Expr *Init) {
723 assert(Init);
724 ASTContext::CUDAConstantEvalContextRAII EvalCtx(S.getASTContext(),
725 /*NoWronSidedVars=*/true);
726 return Init->isConstantInitializer(S.getASTContext(),
727 VD->getType()->isReferenceType());
728 };
729 auto HasEmptyDtor = [&](VarDecl *VD) {
730 if (const auto *RD = VD->getType()->getAsCXXRecordDecl())
731 return S.isEmptyDestructor(VD->getLocation(), RD->getDestructor());
732 return true;
733 };
734 if (CheckKind == CICK_Shared)
735 return IsEmptyInit(Init) && HasEmptyDtor(VD);
736 return S.getLangOpts().GPUAllowDeviceInit ||
737 ((IsEmptyInit(Init) || IsConstantInit(Init)) && HasEmptyDtor(VD));
738}
739} // namespace
740
742 // Return early if VD is inside a non-instantiated template function since
743 // the implicit constructor is not defined yet.
744 if (const FunctionDecl *FD =
745 dyn_cast_or_null<FunctionDecl>(VD->getDeclContext());
746 FD && FD->isDependentContext())
747 return;
748
749 bool IsSharedVar = VD->hasAttr<CUDASharedAttr>();
750 bool IsDeviceOrConstantVar =
751 !IsSharedVar &&
752 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>());
753 if ((IsSharedVar || IsDeviceOrConstantVar) &&
755 Diag(VD->getLocation(), diag::err_cuda_address_space_gpuvar);
756 VD->setInvalidDecl();
757 return;
758 }
759 // Do not check dependent variables since the ctor/dtor/initializer are not
760 // determined. Do it after instantiation.
761 if (VD->isInvalidDecl() || !VD->hasInit() || !VD->hasGlobalStorage() ||
762 IsDependentVar(VD))
763 return;
764 const Expr *Init = VD->getInit();
765 if (IsDeviceOrConstantVar || IsSharedVar) {
766 if (HasAllowedCUDADeviceStaticInitializer(
767 *this, VD, IsSharedVar ? CICK_Shared : CICK_DeviceOrConstant))
768 return;
769 Diag(VD->getLocation(),
770 IsSharedVar ? diag::err_shared_var_init : diag::err_dynamic_var_init)
771 << Init->getSourceRange();
772 VD->setInvalidDecl();
773 } else {
774 // This is a host-side global variable. Check that the initializer is
775 // callable from the host side.
776 const FunctionDecl *InitFn = nullptr;
777 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
778 InitFn = CE->getConstructor();
779 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
780 InitFn = CE->getDirectCallee();
781 }
782 if (InitFn) {
783 CUDAFunctionTarget InitFnTarget = IdentifyTarget(InitFn);
784 if (InitFnTarget != CUDAFunctionTarget::Host &&
785 InitFnTarget != CUDAFunctionTarget::HostDevice) {
786 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
787 << InitFnTarget << InitFn;
788 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
789 VD->setInvalidDecl();
790 }
791 }
792 }
793}
794
796 const FunctionDecl *Callee) {
797 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
798 if (!Caller)
799 return;
800
801 if (!isImplicitHostDeviceFunction(Callee))
802 return;
803
804 CUDAFunctionTarget CallerTarget = IdentifyTarget(Caller);
805
806 // Record whether an implicit host device function is used on device side.
807 if (CallerTarget != CUDAFunctionTarget::Device &&
808 CallerTarget != CUDAFunctionTarget::Global &&
809 (CallerTarget != CUDAFunctionTarget::HostDevice ||
811 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Caller))))
812 return;
813
815}
816
817// With -fcuda-host-device-constexpr, an unattributed constexpr function is
818// treated as implicitly __host__ __device__, unless:
819// * it is a variadic function (device-side variadic functions are not
820// allowed), or
821// * a __device__ function with this signature was already declared, in which
822// case in which case we output an error, unless the __device__ decl is in a
823// system header, in which case we leave the constexpr function unattributed.
824//
825// In addition, all function decls are treated as __host__ __device__ when
826// ForceHostDeviceDepth > 0 (corresponding to code within a
827// #pragma clang force_cuda_host_device_begin/end
828// pair).
830 const LookupResult &Previous) {
831 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
832
833 if (ForceHostDeviceDepth > 0) {
834 if (!NewD->hasAttr<CUDAHostAttr>())
835 NewD->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
836 if (!NewD->hasAttr<CUDADeviceAttr>())
837 NewD->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
838 return;
839 }
840
841 // If a template function has no host/device/global attributes,
842 // make it implicitly host device function.
843 if (getLangOpts().OffloadImplicitHostDeviceTemplates &&
844 !NewD->hasAttr<CUDAHostAttr>() && !NewD->hasAttr<CUDADeviceAttr>() &&
845 !NewD->hasAttr<CUDAGlobalAttr>() &&
848 NewD->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
849 NewD->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
850 return;
851 }
852
853 if (!getLangOpts().CUDAHostDeviceConstexpr || !NewD->isConstexpr() ||
854 NewD->isVariadic() || NewD->hasAttr<CUDAHostAttr>() ||
855 NewD->hasAttr<CUDADeviceAttr>() || NewD->hasAttr<CUDAGlobalAttr>())
856 return;
857
858 // Is D a __device__ function with the same signature as NewD, ignoring CUDA
859 // attributes?
860 auto IsMatchingDeviceFn = [&](NamedDecl *D) {
861 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(D))
862 D = Using->getTargetDecl();
863 FunctionDecl *OldD = D->getAsFunction();
864 return OldD && OldD->hasAttr<CUDADeviceAttr>() &&
865 !OldD->hasAttr<CUDAHostAttr>() &&
866 !SemaRef.IsOverload(NewD, OldD,
867 /* UseMemberUsingDeclRules = */ false,
868 /* ConsiderCudaAttrs = */ false);
869 };
870 auto It = llvm::find_if(Previous, IsMatchingDeviceFn);
871 if (It != Previous.end()) {
872 // We found a __device__ function with the same name and signature as NewD
873 // (ignoring CUDA attrs). This is an error unless that function is defined
874 // in a system header, in which case we simply return without making NewD
875 // host+device.
876 NamedDecl *Match = *It;
877 if (!SemaRef.getSourceManager().isInSystemHeader(Match->getLocation())) {
878 Diag(NewD->getLocation(),
879 diag::err_cuda_unattributed_constexpr_cannot_overload_device)
880 << NewD;
881 Diag(Match->getLocation(),
882 diag::note_cuda_conflicting_device_function_declared_here);
883 }
884 return;
885 }
886
887 NewD->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
888 NewD->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
889}
890
891// TODO: `__constant__` memory may be a limited resource for certain targets.
892// A safeguard may be needed at the end of compilation pipeline if
893// `__constant__` memory usage goes beyond limit.
895 // Do not promote dependent variables since the cotr/dtor/initializer are
896 // not determined. Do it after instantiation.
897 if (getLangOpts().CUDAIsDevice && !VD->hasAttr<CUDAConstantAttr>() &&
898 !VD->hasAttr<CUDASharedAttr>() &&
899 (VD->isFileVarDecl() || VD->isStaticDataMember()) &&
900 !IsDependentVar(VD) &&
901 ((VD->isConstexpr() || VD->getType().isConstQualified()) &&
902 HasAllowedCUDADeviceStaticInitializer(*this, VD,
903 CICK_DeviceOrConstant))) {
904 VD->addAttr(CUDAConstantAttr::CreateImplicit(getASTContext()));
905 }
906}
907
909 unsigned DiagID) {
910 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
911 FunctionDecl *CurFunContext =
912 SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
913 SemaDiagnosticBuilder::Kind DiagKind = [&] {
914 if (!CurFunContext)
915 return SemaDiagnosticBuilder::K_Nop;
916 switch (CurrentTarget()) {
919 return SemaDiagnosticBuilder::K_Immediate;
921 // An HD function counts as host code if we're compiling for host, and
922 // device code if we're compiling for device. Defer any errors in device
923 // mode until the function is known-emitted.
924 if (!getLangOpts().CUDAIsDevice)
925 return SemaDiagnosticBuilder::K_Nop;
926 if (SemaRef.IsLastErrorImmediate &&
927 getDiagnostics().getDiagnosticIDs()->isNote(DiagID))
928 return SemaDiagnosticBuilder::K_Immediate;
929 if (isImplicitHDExplicitInstantiation(CurFunContext))
930 return SemaDiagnosticBuilder::K_Deferred;
931 return (SemaRef.getEmissionStatus(CurFunContext) ==
933 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
934 : SemaDiagnosticBuilder::K_Deferred;
935 default:
936 return SemaDiagnosticBuilder::K_Nop;
937 }
938 }();
939 return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, CurFunContext, SemaRef);
940}
941
943 unsigned DiagID) {
944 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
945 FunctionDecl *CurFunContext =
946 SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
947 SemaDiagnosticBuilder::Kind DiagKind = [&] {
948 if (!CurFunContext)
949 return SemaDiagnosticBuilder::K_Nop;
950 switch (CurrentTarget()) {
952 return SemaDiagnosticBuilder::K_Immediate;
954 // An HD function counts as host code if we're compiling for host, and
955 // device code if we're compiling for device. Defer any errors in device
956 // mode until the function is known-emitted.
957 if (getLangOpts().CUDAIsDevice)
958 return SemaDiagnosticBuilder::K_Nop;
959 if (SemaRef.IsLastErrorImmediate &&
960 getDiagnostics().getDiagnosticIDs()->isNote(DiagID))
961 return SemaDiagnosticBuilder::K_Immediate;
962 return (SemaRef.getEmissionStatus(CurFunContext) ==
964 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
965 : SemaDiagnosticBuilder::K_Deferred;
966 default:
967 return SemaDiagnosticBuilder::K_Nop;
968 }
969 }();
970 return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, CurFunContext, SemaRef);
971}
972
974 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
975 assert(Callee && "Callee may not be null.");
976
977 const auto &ExprEvalCtx = SemaRef.currentEvaluationContext();
978 if (ExprEvalCtx.isUnevaluated() || ExprEvalCtx.isConstantEvaluated() ||
979 ExprEvalCtx.isDiscardedStatementContext())
980 return true;
981
982 // C++ deduction guides participate in overload resolution but are not
983 // callable functions and are never codegen'ed. Treat them as always
984 // allowed for CUDA/HIP compatibility checking.
985 if (isa<CXXDeductionGuideDecl>(Callee))
986 return true;
987
988 // FIXME: Is bailing out early correct here? Should we instead assume that
989 // the caller is a global initializer?
990 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
991 if (!Caller)
992 return true;
993
994 // If the caller is known-emitted, mark the callee as known-emitted.
995 // Otherwise, mark the call in our call graph so we can traverse it later.
996 bool CallerKnownEmitted = SemaRef.getEmissionStatus(Caller) ==
998 bool CallerIsImplicitHDExplicitInst =
1000 SemaDiagnosticBuilder::Kind DiagKind = [this, Caller, Callee,
1001 CallerKnownEmitted,
1002 CallerIsImplicitHDExplicitInst] {
1003 switch (IdentifyPreference(Caller, Callee)) {
1004 case CFP_Never:
1005 case CFP_WrongSide:
1006 assert(Caller && "Never/wrongSide calls require a non-null caller");
1007 // If we know the caller will be emitted, we know this wrong-side call
1008 // will be emitted, so it's an immediate error. Otherwise, defer the
1009 // error until we know the caller is emitted.
1010 return (CallerKnownEmitted && !CallerIsImplicitHDExplicitInst)
1011 ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
1012 : SemaDiagnosticBuilder::K_Deferred;
1013 default:
1014 return SemaDiagnosticBuilder::K_Nop;
1015 }
1016 }();
1017
1018 bool IsDeviceKernelCall = Callee == getASTContext().getcudaLaunchDeviceDecl();
1019 bool CallerHD = Caller && Caller->hasAttr<CUDAHostAttr>() &&
1020 Caller->hasAttr<CUDADeviceAttr>();
1021 bool CallerDiscard = SemaRef.getEmissionStatus(Caller) ==
1023 bool RDC = getLangOpts().GPURelocatableDeviceCode;
1024 if (IsDeviceKernelCall && !(CallerHD && CallerDiscard) && !RDC) {
1025 Diag(Loc, diag::err_cuda_device_kernel_launch_require_rdc);
1026 return false;
1027 }
1028
1029 if (DiagKind == SemaDiagnosticBuilder::K_Nop) {
1030 // For -fgpu-rdc, keep track of external kernels used by host functions.
1031 if (getLangOpts().CUDAIsDevice && RDC &&
1032 Callee->hasAttr<CUDAGlobalAttr>() && !Callee->isDefined() &&
1033 (!Caller || (!Caller->getDescribedFunctionTemplate() &&
1034 getASTContext().GetGVALinkageForFunction(Caller) ==
1037 return true;
1038 }
1039
1040 // Avoid emitting this error twice for the same location. Using a hashtable
1041 // like this is unfortunate, but because we must continue parsing as normal
1042 // after encountering a deferred error, it's otherwise very tricky for us to
1043 // ensure that we only emit this deferred error once.
1044 if (!LocsWithCUDACallDiags.insert({Caller, Loc}).second)
1045 return true;
1046
1047 SemaDiagnosticBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller,
1048 SemaRef)
1049 << IdentifyTarget(Callee) << /*function*/ 0 << Callee
1050 << IdentifyTarget(Caller);
1051 if (!Callee->getBuiltinID())
1052 SemaDiagnosticBuilder(DiagKind, Callee->getLocation(),
1053 diag::note_previous_decl, Caller, SemaRef)
1054 << Callee;
1055 return DiagKind != SemaDiagnosticBuilder::K_Immediate &&
1056 DiagKind != SemaDiagnosticBuilder::K_ImmediateWithCallStack;
1057}
1058
1059// Check the wrong-sided reference capture of lambda for CUDA/HIP.
1060// A lambda function may capture a stack variable by reference when it is
1061// defined and uses the capture by reference when the lambda is called. When
1062// the capture and use happen on different sides, the capture is invalid and
1063// should be diagnosed.
1065 const sema::Capture &Capture) {
1066 // In host compilation we only need to check lambda functions emitted on host
1067 // side. In such lambda functions, a reference capture is invalid only
1068 // if the lambda structure is populated by a device function or kernel then
1069 // is passed to and called by a host function. However that is impossible,
1070 // since a device function or kernel can only call a device function, also a
1071 // kernel cannot pass a lambda back to a host function since we cannot
1072 // define a kernel argument type which can hold the lambda before the lambda
1073 // itself is defined.
1074 if (!getLangOpts().CUDAIsDevice)
1075 return;
1076
1077 // File-scope lambda can only do init captures for global variables, which
1078 // results in passing by value for these global variables.
1079 FunctionDecl *Caller = SemaRef.getCurFunctionDecl(/*AllowLambda=*/true);
1080 if (!Caller)
1081 return;
1082
1083 // In device compilation, we only need to check lambda functions which are
1084 // emitted on device side. For such lambdas, a reference capture is invalid
1085 // only if the lambda structure is populated by a host function then passed
1086 // to and called in a device function or kernel.
1087 bool CalleeIsDevice = Callee->hasAttr<CUDADeviceAttr>();
1088 bool CallerIsHost =
1089 !Caller->hasAttr<CUDAGlobalAttr>() && !Caller->hasAttr<CUDADeviceAttr>();
1090 bool ShouldCheck = CalleeIsDevice && CallerIsHost;
1091 if (!ShouldCheck || !Capture.isReferenceCapture())
1092 return;
1093 auto DiagKind = SemaDiagnosticBuilder::K_Deferred;
1094 if (Capture.isVariableCapture() && !getLangOpts().HIPStdPar) {
1096 diag::err_capture_bad_target, Callee, SemaRef)
1097 << Capture.getVariable();
1098 } else if (Capture.isThisCapture()) {
1099 // Capture of this pointer is allowed since this pointer may be pointing to
1100 // managed memory which is accessible on both device and host sides. It only
1101 // results in invalid memory access if this pointer points to memory not
1102 // accessible on device side.
1104 diag::warn_maybe_capture_bad_target_this_ptr, Callee,
1105 SemaRef);
1106 }
1107}
1108
1110 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
1111 if (Method->hasAttr<CUDAHostAttr>() || Method->hasAttr<CUDADeviceAttr>())
1112 return;
1113 Method->addAttr(CUDADeviceAttr::CreateImplicit(getASTContext()));
1114 Method->addAttr(CUDAHostAttr::CreateImplicit(getASTContext()));
1115}
1116
1118 const LookupResult &Previous) {
1119 assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
1120 CUDAFunctionTarget NewTarget = IdentifyTarget(NewFD);
1121 for (NamedDecl *OldND : Previous) {
1122 FunctionDecl *OldFD = OldND->getAsFunction();
1123 if (!OldFD)
1124 continue;
1125
1126 CUDAFunctionTarget OldTarget = IdentifyTarget(OldFD);
1127 // Don't allow HD and global functions to overload other functions with the
1128 // same signature. We allow overloading based on CUDA attributes so that
1129 // functions can have different implementations on the host and device, but
1130 // HD/global functions "exist" in some sense on both the host and device, so
1131 // should have the same implementation on both sides.
1132 if (NewTarget != OldTarget &&
1133 !SemaRef.IsOverload(NewFD, OldFD, /* UseMemberUsingDeclRules = */ false,
1134 /* ConsiderCudaAttrs = */ false)) {
1135 if ((NewTarget == CUDAFunctionTarget::HostDevice &&
1136 !(getLangOpts().OffloadImplicitHostDeviceTemplates &&
1138 OldTarget == CUDAFunctionTarget::Device)) ||
1139 (OldTarget == CUDAFunctionTarget::HostDevice &&
1140 !(getLangOpts().OffloadImplicitHostDeviceTemplates &&
1142 NewTarget == CUDAFunctionTarget::Device)) ||
1143 (NewTarget == CUDAFunctionTarget::Global) ||
1144 (OldTarget == CUDAFunctionTarget::Global)) {
1145 Diag(NewFD->getLocation(), diag::err_cuda_ovl_target)
1146 << NewTarget << NewFD->getDeclName() << OldTarget << OldFD;
1147 Diag(OldFD->getLocation(), diag::note_previous_declaration);
1148 NewFD->setInvalidDecl();
1149 break;
1150 }
1151 if ((NewTarget == CUDAFunctionTarget::Host &&
1152 OldTarget == CUDAFunctionTarget::Device) ||
1153 (NewTarget == CUDAFunctionTarget::Device &&
1154 OldTarget == CUDAFunctionTarget::Host)) {
1155 Diag(NewFD->getLocation(), diag::warn_offload_incompatible_redeclare)
1156 << NewTarget << OldTarget;
1157 Diag(OldFD->getLocation(), diag::note_previous_declaration);
1158 }
1159 }
1160 }
1161}
1162
1163template <typename AttrTy>
1165 const FunctionDecl &TemplateFD) {
1166 if (AttrTy *Attribute = TemplateFD.getAttr<AttrTy>()) {
1167 AttrTy *Clone = Attribute->clone(S.Context);
1168 Clone->setInherited(true);
1169 FD->addAttr(Clone);
1170 }
1171}
1172
1174 const FunctionTemplateDecl &TD) {
1175 const FunctionDecl &TemplateFD = *TD.getTemplatedDecl();
1179}
1180
1182 if (getLangOpts().OffloadViaLLVM)
1183 return "__llvmPushCallConfiguration";
1184
1185 if (getLangOpts().HIP)
1186 return getLangOpts().HIPUseNewLaunchAPI ? "__hipPushCallConfiguration"
1187 : "hipConfigureCall";
1188
1189 // New CUDA kernel launch sequence.
1190 if (CudaFeatureEnabled(getASTContext().getTargetInfo().getSDKVersion(),
1192 return "__cudaPushCallConfiguration";
1193
1194 // Legacy CUDA kernel configuration call
1195 return "cudaConfigureCall";
1196}
1197
1199 return "cudaGetParameterBuffer";
1200}
1201
1203 return "cudaLaunchDevice";
1204}
1205
1206// Record any local constexpr variables that are passed one way on the host
1207// and another on the device.
1209 MultiExprArg Arguments, OverloadCandidateSet &Candidates) {
1210 sema::LambdaScopeInfo *LambdaInfo = SemaRef.getCurLambda();
1211 if (!LambdaInfo)
1212 return;
1213
1214 for (unsigned I = 0; I < Arguments.size(); ++I) {
1215 auto *DeclRef = dyn_cast<DeclRefExpr>(Arguments[I]);
1216 if (!DeclRef)
1217 continue;
1218 auto *Variable = dyn_cast<VarDecl>(DeclRef->getDecl());
1219 if (!Variable || !Variable->isLocalVarDecl() || !Variable->isConstexpr())
1220 continue;
1221
1222 bool HostByValue = false, HostByRef = false;
1223 bool DeviceByValue = false, DeviceByRef = false;
1224
1225 for (OverloadCandidate &Candidate : Candidates) {
1226 FunctionDecl *Callee = Candidate.Function;
1227 if (!Callee || I >= Callee->getNumParams())
1228 continue;
1229
1233 continue;
1234
1235 bool CoversHost = (Target == CUDAFunctionTarget::Host ||
1237 bool CoversDevice = (Target == CUDAFunctionTarget::Device ||
1239
1240 bool IsRef = Callee->getParamDecl(I)->getType()->isReferenceType();
1241 HostByValue |= CoversHost && !IsRef;
1242 HostByRef |= CoversHost && IsRef;
1243 DeviceByValue |= CoversDevice && !IsRef;
1244 DeviceByRef |= CoversDevice && IsRef;
1245 }
1246
1247 if ((HostByValue && DeviceByRef) || (HostByRef && DeviceByValue))
1248 LambdaInfo->CUDAPotentialODRUsedVars.insert(Variable);
1249 }
1250}
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:439
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
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:3182
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:3184
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4179
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4167
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:3107
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4231
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
bool isImplicitHDExplicitInstantiation() const
True if both host and device are implicit attributes and this is (or is a member of) an explicit temp...
Definition Decl.cpp:4488
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3800
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:3220
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:980
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:8485
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8518
LangAS getAddressSpace() const
Definition TypeBase.h:571
field_range fields() const
Definition Decl.h:4550
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:741
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:795
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
static bool isImplicitHDExplicitInstantiation(const FunctionDecl *FD)
Null-tolerant wrapper for FunctionDecl::isImplicitHDExplicitInstantiation.
Definition SemaCUDA.cpp:402
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:829
ExprResult ActOnExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc)
Definition SemaCUDA.cpp:52
bool isEmptyConstructor(SourceLocation Loc, CXXConstructorDecl *CD)
Definition SemaCUDA.cpp:595
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:633
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:942
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: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:908
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:973
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:894
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: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:9378
CXXMethodDecl * getMethod() const
Definition Sema.h:9390
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:3950
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:8706
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:2844
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:63
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
bool CudaFeatureEnabled(llvm::VersionTuple, CudaFeature)
Definition Cuda.cpp:172
ExprResult ExprError()
Definition Ownership.h:265
@ CUDA_USES_NEW_LAUNCH
Definition Cuda.h:80
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
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