SemaCUDA.cpp 37 KB

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