SemaCUDA.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/Decl.h"
  14. #include "clang/AST/ExprCXX.h"
  15. #include "clang/Basic/Cuda.h"
  16. #include "clang/Basic/TargetInfo.h"
  17. #include "clang/Lex/Preprocessor.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "clang/Sema/ScopeInfo.h"
  20. #include "clang/Sema/Sema.h"
  21. #include "clang/Sema/SemaDiagnostic.h"
  22. #include "clang/Sema/SemaInternal.h"
  23. #include "clang/Sema/Template.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include <optional>
  26. using namespace clang;
  27. template <typename AttrT> static bool hasExplicitAttr(const VarDecl *D) {
  28. if (!D)
  29. return false;
  30. if (auto *A = D->getAttr<AttrT>())
  31. return !A->isImplicit();
  32. return false;
  33. }
  34. void Sema::PushForceCUDAHostDevice() {
  35. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  36. ForceCUDAHostDeviceDepth++;
  37. }
  38. bool Sema::PopForceCUDAHostDevice() {
  39. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  40. if (ForceCUDAHostDeviceDepth == 0)
  41. return false;
  42. ForceCUDAHostDeviceDepth--;
  43. return true;
  44. }
  45. ExprResult Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
  46. MultiExprArg ExecConfig,
  47. SourceLocation GGGLoc) {
  48. FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
  49. if (!ConfigDecl)
  50. return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
  51. << getCudaConfigureFuncName());
  52. QualType ConfigQTy = ConfigDecl->getType();
  53. DeclRefExpr *ConfigDR = new (Context)
  54. DeclRefExpr(Context, ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
  55. MarkFunctionReferenced(LLLLoc, ConfigDecl);
  56. return BuildCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
  57. /*IsExecConfig=*/true);
  58. }
  59. Sema::CUDAFunctionTarget
  60. Sema::IdentifyCUDATarget(const ParsedAttributesView &Attrs) {
  61. bool HasHostAttr = false;
  62. bool HasDeviceAttr = false;
  63. bool HasGlobalAttr = false;
  64. bool HasInvalidTargetAttr = false;
  65. for (const ParsedAttr &AL : Attrs) {
  66. switch (AL.getKind()) {
  67. case ParsedAttr::AT_CUDAGlobal:
  68. HasGlobalAttr = true;
  69. break;
  70. case ParsedAttr::AT_CUDAHost:
  71. HasHostAttr = true;
  72. break;
  73. case ParsedAttr::AT_CUDADevice:
  74. HasDeviceAttr = true;
  75. break;
  76. case ParsedAttr::AT_CUDAInvalidTarget:
  77. HasInvalidTargetAttr = true;
  78. break;
  79. default:
  80. break;
  81. }
  82. }
  83. if (HasInvalidTargetAttr)
  84. return CFT_InvalidTarget;
  85. if (HasGlobalAttr)
  86. return CFT_Global;
  87. if (HasHostAttr && HasDeviceAttr)
  88. return CFT_HostDevice;
  89. if (HasDeviceAttr)
  90. return CFT_Device;
  91. return CFT_Host;
  92. }
  93. template <typename A>
  94. static bool hasAttr(const FunctionDecl *D, bool IgnoreImplicitAttr) {
  95. return D->hasAttrs() && llvm::any_of(D->getAttrs(), [&](Attr *Attribute) {
  96. return isa<A>(Attribute) &&
  97. !(IgnoreImplicitAttr && Attribute->isImplicit());
  98. });
  99. }
  100. /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
  101. Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D,
  102. bool IgnoreImplicitHDAttr) {
  103. // Code that lives outside a function is run on the host.
  104. if (D == nullptr)
  105. return CFT_Host;
  106. if (D->hasAttr<CUDAInvalidTargetAttr>())
  107. return CFT_InvalidTarget;
  108. if (D->hasAttr<CUDAGlobalAttr>())
  109. return CFT_Global;
  110. if (hasAttr<CUDADeviceAttr>(D, IgnoreImplicitHDAttr)) {
  111. if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr))
  112. return CFT_HostDevice;
  113. return CFT_Device;
  114. } else if (hasAttr<CUDAHostAttr>(D, IgnoreImplicitHDAttr)) {
  115. return CFT_Host;
  116. } else if ((D->isImplicit() || !D->isUserProvided()) &&
  117. !IgnoreImplicitHDAttr) {
  118. // Some implicit declarations (like intrinsic functions) are not marked.
  119. // Set the most lenient target on them for maximal flexibility.
  120. return CFT_HostDevice;
  121. }
  122. return CFT_Host;
  123. }
  124. /// IdentifyTarget - Determine the CUDA compilation target for this variable.
  125. Sema::CUDAVariableTarget Sema::IdentifyCUDATarget(const VarDecl *Var) {
  126. if (Var->hasAttr<HIPManagedAttr>())
  127. return CVT_Unified;
  128. // Only constexpr and const variabless with implicit constant attribute
  129. // are emitted on both sides. Such variables are promoted to device side
  130. // only if they have static constant intializers on device side.
  131. if ((Var->isConstexpr() || Var->getType().isConstQualified()) &&
  132. Var->hasAttr<CUDAConstantAttr>() &&
  133. !hasExplicitAttr<CUDAConstantAttr>(Var))
  134. return CVT_Both;
  135. if (Var->hasAttr<CUDADeviceAttr>() || Var->hasAttr<CUDAConstantAttr>() ||
  136. Var->hasAttr<CUDASharedAttr>() ||
  137. Var->getType()->isCUDADeviceBuiltinSurfaceType() ||
  138. Var->getType()->isCUDADeviceBuiltinTextureType())
  139. return CVT_Device;
  140. // Function-scope static variable without explicit device or constant
  141. // attribute are emitted
  142. // - on both sides in host device functions
  143. // - on device side in device or global functions
  144. if (auto *FD = dyn_cast<FunctionDecl>(Var->getDeclContext())) {
  145. switch (IdentifyCUDATarget(FD)) {
  146. case CFT_HostDevice:
  147. return CVT_Both;
  148. case CFT_Device:
  149. case CFT_Global:
  150. return CVT_Device;
  151. default:
  152. return CVT_Host;
  153. }
  154. }
  155. return CVT_Host;
  156. }
  157. // * CUDA Call preference table
  158. //
  159. // F - from,
  160. // T - to
  161. // Ph - preference in host mode
  162. // Pd - preference in device mode
  163. // H - handled in (x)
  164. // Preferences: N:native, SS:same side, HD:host-device, WS:wrong side, --:never.
  165. //
  166. // | F | T | Ph | Pd | H |
  167. // |----+----+-----+-----+-----+
  168. // | d | d | N | N | (c) |
  169. // | d | g | -- | -- | (a) |
  170. // | d | h | -- | -- | (e) |
  171. // | d | hd | HD | HD | (b) |
  172. // | g | d | N | N | (c) |
  173. // | g | g | -- | -- | (a) |
  174. // | g | h | -- | -- | (e) |
  175. // | g | hd | HD | HD | (b) |
  176. // | h | d | -- | -- | (e) |
  177. // | h | g | N | N | (c) |
  178. // | h | h | N | N | (c) |
  179. // | h | hd | HD | HD | (b) |
  180. // | hd | d | WS | SS | (d) |
  181. // | hd | g | SS | -- |(d/a)|
  182. // | hd | h | SS | WS | (d) |
  183. // | hd | hd | HD | HD | (b) |
  184. Sema::CUDAFunctionPreference
  185. Sema::IdentifyCUDAPreference(const FunctionDecl *Caller,
  186. const FunctionDecl *Callee) {
  187. assert(Callee && "Callee must be valid.");
  188. CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller);
  189. CUDAFunctionTarget CalleeTarget = IdentifyCUDATarget(Callee);
  190. // If one of the targets is invalid, the check always fails, no matter what
  191. // the other target is.
  192. if (CallerTarget == CFT_InvalidTarget || CalleeTarget == CFT_InvalidTarget)
  193. return CFP_Never;
  194. // (a) Can't call global from some contexts until we support CUDA's
  195. // dynamic parallelism.
  196. if (CalleeTarget == CFT_Global &&
  197. (CallerTarget == CFT_Global || CallerTarget == CFT_Device))
  198. return CFP_Never;
  199. // (b) Calling HostDevice is OK for everyone.
  200. if (CalleeTarget == CFT_HostDevice)
  201. return CFP_HostDevice;
  202. // (c) Best case scenarios
  203. if (CalleeTarget == CallerTarget ||
  204. (CallerTarget == CFT_Host && CalleeTarget == CFT_Global) ||
  205. (CallerTarget == CFT_Global && CalleeTarget == CFT_Device))
  206. return CFP_Native;
  207. // (d) HostDevice behavior depends on compilation mode.
  208. if (CallerTarget == CFT_HostDevice) {
  209. // It's OK to call a compilation-mode matching function from an HD one.
  210. if ((getLangOpts().CUDAIsDevice && CalleeTarget == CFT_Device) ||
  211. (!getLangOpts().CUDAIsDevice &&
  212. (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)))
  213. return CFP_SameSide;
  214. // Calls from HD to non-mode-matching functions (i.e., to host functions
  215. // when compiling in device mode or to device functions when compiling in
  216. // host mode) are allowed at the sema level, but eventually rejected if
  217. // they're ever codegened. TODO: Reject said calls earlier.
  218. return CFP_WrongSide;
  219. }
  220. // (e) Calling across device/host boundary is not something you should do.
  221. if ((CallerTarget == CFT_Host && CalleeTarget == CFT_Device) ||
  222. (CallerTarget == CFT_Device && CalleeTarget == CFT_Host) ||
  223. (CallerTarget == CFT_Global && CalleeTarget == CFT_Host))
  224. return CFP_Never;
  225. llvm_unreachable("All cases should've been handled by now.");
  226. }
  227. template <typename AttrT> static bool hasImplicitAttr(const FunctionDecl *D) {
  228. if (!D)
  229. return false;
  230. if (auto *A = D->getAttr<AttrT>())
  231. return A->isImplicit();
  232. return D->isImplicit();
  233. }
  234. bool Sema::isCUDAImplicitHostDeviceFunction(const FunctionDecl *D) {
  235. bool IsImplicitDevAttr = hasImplicitAttr<CUDADeviceAttr>(D);
  236. bool IsImplicitHostAttr = hasImplicitAttr<CUDAHostAttr>(D);
  237. return IsImplicitDevAttr && IsImplicitHostAttr;
  238. }
  239. void Sema::EraseUnwantedCUDAMatches(
  240. const FunctionDecl *Caller,
  241. SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches) {
  242. if (Matches.size() <= 1)
  243. return;
  244. using Pair = std::pair<DeclAccessPair, FunctionDecl*>;
  245. // Gets the CUDA function preference for a call from Caller to Match.
  246. auto GetCFP = [&](const Pair &Match) {
  247. return IdentifyCUDAPreference(Caller, Match.second);
  248. };
  249. // Find the best call preference among the functions in Matches.
  250. CUDAFunctionPreference BestCFP = GetCFP(*std::max_element(
  251. Matches.begin(), Matches.end(),
  252. [&](const Pair &M1, const Pair &M2) { return GetCFP(M1) < GetCFP(M2); }));
  253. // Erase all functions with lower priority.
  254. llvm::erase_if(Matches,
  255. [&](const Pair &Match) { return GetCFP(Match) < BestCFP; });
  256. }
  257. /// When an implicitly-declared special member has to invoke more than one
  258. /// base/field special member, conflicts may occur in the targets of these
  259. /// members. For example, if one base's member __host__ and another's is
  260. /// __device__, it's a conflict.
  261. /// This function figures out if the given targets \param Target1 and
  262. /// \param Target2 conflict, and if they do not it fills in
  263. /// \param ResolvedTarget with a target that resolves for both calls.
  264. /// \return true if there's a conflict, false otherwise.
  265. static bool
  266. resolveCalleeCUDATargetConflict(Sema::CUDAFunctionTarget Target1,
  267. Sema::CUDAFunctionTarget Target2,
  268. Sema::CUDAFunctionTarget *ResolvedTarget) {
  269. // Only free functions and static member functions may be global.
  270. assert(Target1 != Sema::CFT_Global);
  271. assert(Target2 != Sema::CFT_Global);
  272. if (Target1 == Sema::CFT_HostDevice) {
  273. *ResolvedTarget = Target2;
  274. } else if (Target2 == Sema::CFT_HostDevice) {
  275. *ResolvedTarget = Target1;
  276. } else if (Target1 != Target2) {
  277. return true;
  278. } else {
  279. *ResolvedTarget = Target1;
  280. }
  281. return false;
  282. }
  283. bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
  284. CXXSpecialMember CSM,
  285. CXXMethodDecl *MemberDecl,
  286. bool ConstRHS,
  287. bool Diagnose) {
  288. // If the defaulted special member is defined lexically outside of its
  289. // owning class, or the special member already has explicit device or host
  290. // attributes, do not infer.
  291. bool InClass = MemberDecl->getLexicalParent() == MemberDecl->getParent();
  292. bool HasH = MemberDecl->hasAttr<CUDAHostAttr>();
  293. bool HasD = MemberDecl->hasAttr<CUDADeviceAttr>();
  294. bool HasExplicitAttr =
  295. (HasD && !MemberDecl->getAttr<CUDADeviceAttr>()->isImplicit()) ||
  296. (HasH && !MemberDecl->getAttr<CUDAHostAttr>()->isImplicit());
  297. if (!InClass || HasExplicitAttr)
  298. return false;
  299. std::optional<CUDAFunctionTarget> InferredTarget;
  300. // We're going to invoke special member lookup; mark that these special
  301. // members are called from this one, and not from its caller.
  302. ContextRAII MethodContext(*this, MemberDecl);
  303. // Look for special members in base classes that should be invoked from here.
  304. // Infer the target of this member base on the ones it should call.
  305. // Skip direct and indirect virtual bases for abstract classes.
  306. llvm::SmallVector<const CXXBaseSpecifier *, 16> Bases;
  307. for (const auto &B : ClassDecl->bases()) {
  308. if (!B.isVirtual()) {
  309. Bases.push_back(&B);
  310. }
  311. }
  312. if (!ClassDecl->isAbstract()) {
  313. llvm::append_range(Bases, llvm::make_pointer_range(ClassDecl->vbases()));
  314. }
  315. for (const auto *B : Bases) {
  316. const RecordType *BaseType = B->getType()->getAs<RecordType>();
  317. if (!BaseType) {
  318. continue;
  319. }
  320. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  321. Sema::SpecialMemberOverloadResult SMOR =
  322. LookupSpecialMember(BaseClassDecl, CSM,
  323. /* ConstArg */ ConstRHS,
  324. /* VolatileArg */ false,
  325. /* RValueThis */ false,
  326. /* ConstThis */ false,
  327. /* VolatileThis */ false);
  328. if (!SMOR.getMethod())
  329. continue;
  330. CUDAFunctionTarget BaseMethodTarget = IdentifyCUDATarget(SMOR.getMethod());
  331. if (!InferredTarget) {
  332. InferredTarget = BaseMethodTarget;
  333. } else {
  334. bool ResolutionError = resolveCalleeCUDATargetConflict(
  335. *InferredTarget, BaseMethodTarget, &*InferredTarget);
  336. if (ResolutionError) {
  337. if (Diagnose) {
  338. Diag(ClassDecl->getLocation(),
  339. diag::note_implicit_member_target_infer_collision)
  340. << (unsigned)CSM << *InferredTarget << BaseMethodTarget;
  341. }
  342. MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
  343. return true;
  344. }
  345. }
  346. }
  347. // Same as for bases, but now for special members of fields.
  348. for (const auto *F : ClassDecl->fields()) {
  349. if (F->isInvalidDecl()) {
  350. continue;
  351. }
  352. const RecordType *FieldType =
  353. Context.getBaseElementType(F->getType())->getAs<RecordType>();
  354. if (!FieldType) {
  355. continue;
  356. }
  357. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(FieldType->getDecl());
  358. Sema::SpecialMemberOverloadResult SMOR =
  359. LookupSpecialMember(FieldRecDecl, CSM,
  360. /* ConstArg */ ConstRHS && !F->isMutable(),
  361. /* VolatileArg */ false,
  362. /* RValueThis */ false,
  363. /* ConstThis */ false,
  364. /* VolatileThis */ false);
  365. if (!SMOR.getMethod())
  366. continue;
  367. CUDAFunctionTarget FieldMethodTarget =
  368. IdentifyCUDATarget(SMOR.getMethod());
  369. if (!InferredTarget) {
  370. InferredTarget = FieldMethodTarget;
  371. } else {
  372. bool ResolutionError = resolveCalleeCUDATargetConflict(
  373. *InferredTarget, FieldMethodTarget, &*InferredTarget);
  374. if (ResolutionError) {
  375. if (Diagnose) {
  376. Diag(ClassDecl->getLocation(),
  377. diag::note_implicit_member_target_infer_collision)
  378. << (unsigned)CSM << *InferredTarget << FieldMethodTarget;
  379. }
  380. MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
  381. return true;
  382. }
  383. }
  384. }
  385. // If no target was inferred, mark this member as __host__ __device__;
  386. // it's the least restrictive option that can be invoked from any target.
  387. bool NeedsH = true, NeedsD = true;
  388. if (InferredTarget) {
  389. if (*InferredTarget == CFT_Device)
  390. NeedsH = false;
  391. else if (*InferredTarget == CFT_Host)
  392. NeedsD = false;
  393. }
  394. // We either setting attributes first time, or the inferred ones must match
  395. // previously set ones.
  396. if (NeedsD && !HasD)
  397. MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
  398. if (NeedsH && !HasH)
  399. MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
  400. return false;
  401. }
  402. bool Sema::isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD) {
  403. if (!CD->isDefined() && CD->isTemplateInstantiation())
  404. InstantiateFunctionDefinition(Loc, CD->getFirstDecl());
  405. // (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
  406. // empty at a point in the translation unit, if it is either a
  407. // trivial constructor
  408. if (CD->isTrivial())
  409. return true;
  410. // ... or it satisfies all of the following conditions:
  411. // The constructor function has been defined.
  412. // The constructor function has no parameters,
  413. // and the function body is an empty compound statement.
  414. if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
  415. return false;
  416. // Its class has no virtual functions and no virtual base classes.
  417. if (CD->getParent()->isDynamicClass())
  418. return false;
  419. // Union ctor does not call ctors of its data members.
  420. if (CD->getParent()->isUnion())
  421. return true;
  422. // The only form of initializer allowed is an empty constructor.
  423. // This will recursively check all base classes and member initializers
  424. if (!llvm::all_of(CD->inits(), [&](const CXXCtorInitializer *CI) {
  425. if (const CXXConstructExpr *CE =
  426. dyn_cast<CXXConstructExpr>(CI->getInit()))
  427. return isEmptyCudaConstructor(Loc, CE->getConstructor());
  428. return false;
  429. }))
  430. return false;
  431. return true;
  432. }
  433. bool Sema::isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *DD) {
  434. // No destructor -> no problem.
  435. if (!DD)
  436. return true;
  437. if (!DD->isDefined() && DD->isTemplateInstantiation())
  438. InstantiateFunctionDefinition(Loc, DD->getFirstDecl());
  439. // (E.2.3.1, CUDA 7.5) A destructor for a class type is considered
  440. // empty at a point in the translation unit, if it is either a
  441. // trivial constructor
  442. if (DD->isTrivial())
  443. return true;
  444. // ... or it satisfies all of the following conditions:
  445. // The destructor function has been defined.
  446. // and the function body is an empty compound statement.
  447. if (!DD->hasTrivialBody())
  448. return false;
  449. const CXXRecordDecl *ClassDecl = DD->getParent();
  450. // Its class has no virtual functions and no virtual base classes.
  451. if (ClassDecl->isDynamicClass())
  452. return false;
  453. // Union does not have base class and union dtor does not call dtors of its
  454. // data members.
  455. if (DD->getParent()->isUnion())
  456. return true;
  457. // Only empty destructors are allowed. This will recursively check
  458. // destructors for all base classes...
  459. if (!llvm::all_of(ClassDecl->bases(), [&](const CXXBaseSpecifier &BS) {
  460. if (CXXRecordDecl *RD = BS.getType()->getAsCXXRecordDecl())
  461. return isEmptyCudaDestructor(Loc, RD->getDestructor());
  462. return true;
  463. }))
  464. return false;
  465. // ... and member fields.
  466. if (!llvm::all_of(ClassDecl->fields(), [&](const FieldDecl *Field) {
  467. if (CXXRecordDecl *RD = Field->getType()
  468. ->getBaseElementTypeUnsafe()
  469. ->getAsCXXRecordDecl())
  470. return isEmptyCudaDestructor(Loc, RD->getDestructor());
  471. return true;
  472. }))
  473. return false;
  474. return true;
  475. }
  476. namespace {
  477. enum CUDAInitializerCheckKind {
  478. CICK_DeviceOrConstant, // Check initializer for device/constant variable
  479. CICK_Shared, // Check initializer for shared variable
  480. };
  481. bool IsDependentVar(VarDecl *VD) {
  482. if (VD->getType()->isDependentType())
  483. return true;
  484. if (const auto *Init = VD->getInit())
  485. return Init->isValueDependent();
  486. return false;
  487. }
  488. // Check whether a variable has an allowed initializer for a CUDA device side
  489. // variable with global storage. \p VD may be a host variable to be checked for
  490. // potential promotion to device side variable.
  491. //
  492. // CUDA/HIP allows only empty constructors as initializers for global
  493. // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
  494. // __shared__ variables whether they are local or not (they all are implicitly
  495. // static in CUDA). One exception is that CUDA allows constant initializers
  496. // for __constant__ and __device__ variables.
  497. bool HasAllowedCUDADeviceStaticInitializer(Sema &S, VarDecl *VD,
  498. CUDAInitializerCheckKind CheckKind) {
  499. assert(!VD->isInvalidDecl() && VD->hasGlobalStorage());
  500. assert(!IsDependentVar(VD) && "do not check dependent var");
  501. const Expr *Init = VD->getInit();
  502. auto IsEmptyInit = [&](const Expr *Init) {
  503. if (!Init)
  504. return true;
  505. if (const auto *CE = dyn_cast<CXXConstructExpr>(Init)) {
  506. return S.isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
  507. }
  508. return false;
  509. };
  510. auto IsConstantInit = [&](const Expr *Init) {
  511. assert(Init);
  512. ASTContext::CUDAConstantEvalContextRAII EvalCtx(S.Context,
  513. /*NoWronSidedVars=*/true);
  514. return Init->isConstantInitializer(S.Context,
  515. VD->getType()->isReferenceType());
  516. };
  517. auto HasEmptyDtor = [&](VarDecl *VD) {
  518. if (const auto *RD = VD->getType()->getAsCXXRecordDecl())
  519. return S.isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
  520. return true;
  521. };
  522. if (CheckKind == CICK_Shared)
  523. return IsEmptyInit(Init) && HasEmptyDtor(VD);
  524. return S.LangOpts.GPUAllowDeviceInit ||
  525. ((IsEmptyInit(Init) || IsConstantInit(Init)) && HasEmptyDtor(VD));
  526. }
  527. } // namespace
  528. void Sema::checkAllowedCUDAInitializer(VarDecl *VD) {
  529. // Do not check dependent variables since the ctor/dtor/initializer are not
  530. // determined. Do it after instantiation.
  531. if (VD->isInvalidDecl() || !VD->hasInit() || !VD->hasGlobalStorage() ||
  532. IsDependentVar(VD))
  533. return;
  534. const Expr *Init = VD->getInit();
  535. bool IsSharedVar = VD->hasAttr<CUDASharedAttr>();
  536. bool IsDeviceOrConstantVar =
  537. !IsSharedVar &&
  538. (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>());
  539. if (IsDeviceOrConstantVar || IsSharedVar) {
  540. if (HasAllowedCUDADeviceStaticInitializer(
  541. *this, VD, IsSharedVar ? CICK_Shared : CICK_DeviceOrConstant))
  542. return;
  543. Diag(VD->getLocation(),
  544. IsSharedVar ? diag::err_shared_var_init : diag::err_dynamic_var_init)
  545. << Init->getSourceRange();
  546. VD->setInvalidDecl();
  547. } else {
  548. // This is a host-side global variable. Check that the initializer is
  549. // callable from the host side.
  550. const FunctionDecl *InitFn = nullptr;
  551. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
  552. InitFn = CE->getConstructor();
  553. } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
  554. InitFn = CE->getDirectCallee();
  555. }
  556. if (InitFn) {
  557. CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
  558. if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
  559. Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
  560. << InitFnTarget << InitFn;
  561. Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
  562. VD->setInvalidDecl();
  563. }
  564. }
  565. }
  566. }
  567. // With -fcuda-host-device-constexpr, an unattributed constexpr function is
  568. // treated as implicitly __host__ __device__, unless:
  569. // * it is a variadic function (device-side variadic functions are not
  570. // allowed), or
  571. // * a __device__ function with this signature was already declared, in which
  572. // case in which case we output an error, unless the __device__ decl is in a
  573. // system header, in which case we leave the constexpr function unattributed.
  574. //
  575. // In addition, all function decls are treated as __host__ __device__ when
  576. // ForceCUDAHostDeviceDepth > 0 (corresponding to code within a
  577. // #pragma clang force_cuda_host_device_begin/end
  578. // pair).
  579. void Sema::maybeAddCUDAHostDeviceAttrs(FunctionDecl *NewD,
  580. const LookupResult &Previous) {
  581. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  582. if (ForceCUDAHostDeviceDepth > 0) {
  583. if (!NewD->hasAttr<CUDAHostAttr>())
  584. NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
  585. if (!NewD->hasAttr<CUDADeviceAttr>())
  586. NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
  587. return;
  588. }
  589. if (!getLangOpts().CUDAHostDeviceConstexpr || !NewD->isConstexpr() ||
  590. NewD->isVariadic() || NewD->hasAttr<CUDAHostAttr>() ||
  591. NewD->hasAttr<CUDADeviceAttr>() || NewD->hasAttr<CUDAGlobalAttr>())
  592. return;
  593. // Is D a __device__ function with the same signature as NewD, ignoring CUDA
  594. // attributes?
  595. auto IsMatchingDeviceFn = [&](NamedDecl *D) {
  596. if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(D))
  597. D = Using->getTargetDecl();
  598. FunctionDecl *OldD = D->getAsFunction();
  599. return OldD && OldD->hasAttr<CUDADeviceAttr>() &&
  600. !OldD->hasAttr<CUDAHostAttr>() &&
  601. !IsOverload(NewD, OldD, /* UseMemberUsingDeclRules = */ false,
  602. /* ConsiderCudaAttrs = */ false);
  603. };
  604. auto It = llvm::find_if(Previous, IsMatchingDeviceFn);
  605. if (It != Previous.end()) {
  606. // We found a __device__ function with the same name and signature as NewD
  607. // (ignoring CUDA attrs). This is an error unless that function is defined
  608. // in a system header, in which case we simply return without making NewD
  609. // host+device.
  610. NamedDecl *Match = *It;
  611. if (!getSourceManager().isInSystemHeader(Match->getLocation())) {
  612. Diag(NewD->getLocation(),
  613. diag::err_cuda_unattributed_constexpr_cannot_overload_device)
  614. << NewD;
  615. Diag(Match->getLocation(),
  616. diag::note_cuda_conflicting_device_function_declared_here);
  617. }
  618. return;
  619. }
  620. NewD->addAttr(CUDAHostAttr::CreateImplicit(Context));
  621. NewD->addAttr(CUDADeviceAttr::CreateImplicit(Context));
  622. }
  623. // TODO: `__constant__` memory may be a limited resource for certain targets.
  624. // A safeguard may be needed at the end of compilation pipeline if
  625. // `__constant__` memory usage goes beyond limit.
  626. void Sema::MaybeAddCUDAConstantAttr(VarDecl *VD) {
  627. // Do not promote dependent variables since the cotr/dtor/initializer are
  628. // not determined. Do it after instantiation.
  629. if (getLangOpts().CUDAIsDevice && !VD->hasAttr<CUDAConstantAttr>() &&
  630. !VD->hasAttr<CUDASharedAttr>() &&
  631. (VD->isFileVarDecl() || VD->isStaticDataMember()) &&
  632. !IsDependentVar(VD) &&
  633. ((VD->isConstexpr() || VD->getType().isConstQualified()) &&
  634. HasAllowedCUDADeviceStaticInitializer(*this, VD,
  635. CICK_DeviceOrConstant))) {
  636. VD->addAttr(CUDAConstantAttr::CreateImplicit(getASTContext()));
  637. }
  638. }
  639. Sema::SemaDiagnosticBuilder Sema::CUDADiagIfDeviceCode(SourceLocation Loc,
  640. unsigned DiagID) {
  641. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  642. FunctionDecl *CurFunContext = getCurFunctionDecl(/*AllowLambda=*/true);
  643. SemaDiagnosticBuilder::Kind DiagKind = [&] {
  644. if (!CurFunContext)
  645. return SemaDiagnosticBuilder::K_Nop;
  646. switch (CurrentCUDATarget()) {
  647. case CFT_Global:
  648. case CFT_Device:
  649. return SemaDiagnosticBuilder::K_Immediate;
  650. case CFT_HostDevice:
  651. // An HD function counts as host code if we're compiling for host, and
  652. // device code if we're compiling for device. Defer any errors in device
  653. // mode until the function is known-emitted.
  654. if (!getLangOpts().CUDAIsDevice)
  655. return SemaDiagnosticBuilder::K_Nop;
  656. if (IsLastErrorImmediate && Diags.getDiagnosticIDs()->isBuiltinNote(DiagID))
  657. return SemaDiagnosticBuilder::K_Immediate;
  658. return (getEmissionStatus(CurFunContext) ==
  659. FunctionEmissionStatus::Emitted)
  660. ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
  661. : SemaDiagnosticBuilder::K_Deferred;
  662. default:
  663. return SemaDiagnosticBuilder::K_Nop;
  664. }
  665. }();
  666. return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, CurFunContext, *this);
  667. }
  668. Sema::SemaDiagnosticBuilder Sema::CUDADiagIfHostCode(SourceLocation Loc,
  669. unsigned DiagID) {
  670. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  671. FunctionDecl *CurFunContext = getCurFunctionDecl(/*AllowLambda=*/true);
  672. SemaDiagnosticBuilder::Kind DiagKind = [&] {
  673. if (!CurFunContext)
  674. return SemaDiagnosticBuilder::K_Nop;
  675. switch (CurrentCUDATarget()) {
  676. case CFT_Host:
  677. return SemaDiagnosticBuilder::K_Immediate;
  678. case CFT_HostDevice:
  679. // An HD function counts as host code if we're compiling for host, and
  680. // device code if we're compiling for device. Defer any errors in device
  681. // mode until the function is known-emitted.
  682. if (getLangOpts().CUDAIsDevice)
  683. return SemaDiagnosticBuilder::K_Nop;
  684. if (IsLastErrorImmediate && Diags.getDiagnosticIDs()->isBuiltinNote(DiagID))
  685. return SemaDiagnosticBuilder::K_Immediate;
  686. return (getEmissionStatus(CurFunContext) ==
  687. FunctionEmissionStatus::Emitted)
  688. ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
  689. : SemaDiagnosticBuilder::K_Deferred;
  690. default:
  691. return SemaDiagnosticBuilder::K_Nop;
  692. }
  693. }();
  694. return SemaDiagnosticBuilder(DiagKind, Loc, DiagID, CurFunContext, *this);
  695. }
  696. bool Sema::CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee) {
  697. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  698. assert(Callee && "Callee may not be null.");
  699. auto &ExprEvalCtx = ExprEvalContexts.back();
  700. if (ExprEvalCtx.isUnevaluated() || ExprEvalCtx.isConstantEvaluated())
  701. return true;
  702. // FIXME: Is bailing out early correct here? Should we instead assume that
  703. // the caller is a global initializer?
  704. FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
  705. if (!Caller)
  706. return true;
  707. // If the caller is known-emitted, mark the callee as known-emitted.
  708. // Otherwise, mark the call in our call graph so we can traverse it later.
  709. bool CallerKnownEmitted =
  710. getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted;
  711. SemaDiagnosticBuilder::Kind DiagKind = [this, Caller, Callee,
  712. CallerKnownEmitted] {
  713. switch (IdentifyCUDAPreference(Caller, Callee)) {
  714. case CFP_Never:
  715. case CFP_WrongSide:
  716. assert(Caller && "Never/wrongSide calls require a non-null caller");
  717. // If we know the caller will be emitted, we know this wrong-side call
  718. // will be emitted, so it's an immediate error. Otherwise, defer the
  719. // error until we know the caller is emitted.
  720. return CallerKnownEmitted
  721. ? SemaDiagnosticBuilder::K_ImmediateWithCallStack
  722. : SemaDiagnosticBuilder::K_Deferred;
  723. default:
  724. return SemaDiagnosticBuilder::K_Nop;
  725. }
  726. }();
  727. if (DiagKind == SemaDiagnosticBuilder::K_Nop) {
  728. // For -fgpu-rdc, keep track of external kernels used by host functions.
  729. if (LangOpts.CUDAIsDevice && LangOpts.GPURelocatableDeviceCode &&
  730. Callee->hasAttr<CUDAGlobalAttr>() && !Callee->isDefined())
  731. getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Callee);
  732. return true;
  733. }
  734. // Avoid emitting this error twice for the same location. Using a hashtable
  735. // like this is unfortunate, but because we must continue parsing as normal
  736. // after encountering a deferred error, it's otherwise very tricky for us to
  737. // ensure that we only emit this deferred error once.
  738. if (!LocsWithCUDACallDiags.insert({Caller, Loc}).second)
  739. return true;
  740. SemaDiagnosticBuilder(DiagKind, Loc, diag::err_ref_bad_target, Caller, *this)
  741. << IdentifyCUDATarget(Callee) << /*function*/ 0 << Callee
  742. << IdentifyCUDATarget(Caller);
  743. if (!Callee->getBuiltinID())
  744. SemaDiagnosticBuilder(DiagKind, Callee->getLocation(),
  745. diag::note_previous_decl, Caller, *this)
  746. << Callee;
  747. return DiagKind != SemaDiagnosticBuilder::K_Immediate &&
  748. DiagKind != SemaDiagnosticBuilder::K_ImmediateWithCallStack;
  749. }
  750. // Check the wrong-sided reference capture of lambda for CUDA/HIP.
  751. // A lambda function may capture a stack variable by reference when it is
  752. // defined and uses the capture by reference when the lambda is called. When
  753. // the capture and use happen on different sides, the capture is invalid and
  754. // should be diagnosed.
  755. void Sema::CUDACheckLambdaCapture(CXXMethodDecl *Callee,
  756. const sema::Capture &Capture) {
  757. // In host compilation we only need to check lambda functions emitted on host
  758. // side. In such lambda functions, a reference capture is invalid only
  759. // if the lambda structure is populated by a device function or kernel then
  760. // is passed to and called by a host function. However that is impossible,
  761. // since a device function or kernel can only call a device function, also a
  762. // kernel cannot pass a lambda back to a host function since we cannot
  763. // define a kernel argument type which can hold the lambda before the lambda
  764. // itself is defined.
  765. if (!LangOpts.CUDAIsDevice)
  766. return;
  767. // File-scope lambda can only do init captures for global variables, which
  768. // results in passing by value for these global variables.
  769. FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
  770. if (!Caller)
  771. return;
  772. // In device compilation, we only need to check lambda functions which are
  773. // emitted on device side. For such lambdas, a reference capture is invalid
  774. // only if the lambda structure is populated by a host function then passed
  775. // to and called in a device function or kernel.
  776. bool CalleeIsDevice = Callee->hasAttr<CUDADeviceAttr>();
  777. bool CallerIsHost =
  778. !Caller->hasAttr<CUDAGlobalAttr>() && !Caller->hasAttr<CUDADeviceAttr>();
  779. bool ShouldCheck = CalleeIsDevice && CallerIsHost;
  780. if (!ShouldCheck || !Capture.isReferenceCapture())
  781. return;
  782. auto DiagKind = SemaDiagnosticBuilder::K_Deferred;
  783. if (Capture.isVariableCapture()) {
  784. SemaDiagnosticBuilder(DiagKind, Capture.getLocation(),
  785. diag::err_capture_bad_target, Callee, *this)
  786. << Capture.getVariable();
  787. } else if (Capture.isThisCapture()) {
  788. // Capture of this pointer is allowed since this pointer may be pointing to
  789. // managed memory which is accessible on both device and host sides. It only
  790. // results in invalid memory access if this pointer points to memory not
  791. // accessible on device side.
  792. SemaDiagnosticBuilder(DiagKind, Capture.getLocation(),
  793. diag::warn_maybe_capture_bad_target_this_ptr, Callee,
  794. *this);
  795. }
  796. }
  797. void Sema::CUDASetLambdaAttrs(CXXMethodDecl *Method) {
  798. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  799. if (Method->hasAttr<CUDAHostAttr>() || Method->hasAttr<CUDADeviceAttr>())
  800. return;
  801. Method->addAttr(CUDADeviceAttr::CreateImplicit(Context));
  802. Method->addAttr(CUDAHostAttr::CreateImplicit(Context));
  803. }
  804. void Sema::checkCUDATargetOverload(FunctionDecl *NewFD,
  805. const LookupResult &Previous) {
  806. assert(getLangOpts().CUDA && "Should only be called during CUDA compilation");
  807. CUDAFunctionTarget NewTarget = IdentifyCUDATarget(NewFD);
  808. for (NamedDecl *OldND : Previous) {
  809. FunctionDecl *OldFD = OldND->getAsFunction();
  810. if (!OldFD)
  811. continue;
  812. CUDAFunctionTarget OldTarget = IdentifyCUDATarget(OldFD);
  813. // Don't allow HD and global functions to overload other functions with the
  814. // same signature. We allow overloading based on CUDA attributes so that
  815. // functions can have different implementations on the host and device, but
  816. // HD/global functions "exist" in some sense on both the host and device, so
  817. // should have the same implementation on both sides.
  818. if (NewTarget != OldTarget &&
  819. ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
  820. (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) &&
  821. !IsOverload(NewFD, OldFD, /* UseMemberUsingDeclRules = */ false,
  822. /* ConsiderCudaAttrs = */ false)) {
  823. Diag(NewFD->getLocation(), diag::err_cuda_ovl_target)
  824. << NewTarget << NewFD->getDeclName() << OldTarget << OldFD;
  825. Diag(OldFD->getLocation(), diag::note_previous_declaration);
  826. NewFD->setInvalidDecl();
  827. break;
  828. }
  829. }
  830. }
  831. template <typename AttrTy>
  832. static void copyAttrIfPresent(Sema &S, FunctionDecl *FD,
  833. const FunctionDecl &TemplateFD) {
  834. if (AttrTy *Attribute = TemplateFD.getAttr<AttrTy>()) {
  835. AttrTy *Clone = Attribute->clone(S.Context);
  836. Clone->setInherited(true);
  837. FD->addAttr(Clone);
  838. }
  839. }
  840. void Sema::inheritCUDATargetAttrs(FunctionDecl *FD,
  841. const FunctionTemplateDecl &TD) {
  842. const FunctionDecl &TemplateFD = *TD.getTemplatedDecl();
  843. copyAttrIfPresent<CUDAGlobalAttr>(*this, FD, TemplateFD);
  844. copyAttrIfPresent<CUDAHostAttr>(*this, FD, TemplateFD);
  845. copyAttrIfPresent<CUDADeviceAttr>(*this, FD, TemplateFD);
  846. }
  847. std::string Sema::getCudaConfigureFuncName() const {
  848. if (getLangOpts().HIP)
  849. return getLangOpts().HIPUseNewLaunchAPI ? "__hipPushCallConfiguration"
  850. : "hipConfigureCall";
  851. // New CUDA kernel launch sequence.
  852. if (CudaFeatureEnabled(Context.getTargetInfo().getSDKVersion(),
  853. CudaFeature::CUDA_USES_NEW_LAUNCH))
  854. return "__cudaPushCallConfiguration";
  855. // Legacy CUDA kernel configuration call
  856. return "cudaConfigureCall";
  857. }