SemaStmtAttr.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. //===--- SemaStmtAttr.cpp - Statement Attribute Handling ------------------===//
  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. //
  9. // This file implements stmt-related attribute processing.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/EvaluatedExprVisitor.h"
  14. #include "clang/Basic/SourceManager.h"
  15. #include "clang/Basic/TargetInfo.h"
  16. #include "clang/Sema/DelayedDiagnostic.h"
  17. #include "clang/Sema/Lookup.h"
  18. #include "clang/Sema/ScopeInfo.h"
  19. #include "clang/Sema/SemaInternal.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. using namespace clang;
  22. using namespace sema;
  23. static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A,
  24. SourceRange Range) {
  25. FallThroughAttr Attr(S.Context, A);
  26. if (isa<SwitchCase>(St)) {
  27. S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target)
  28. << A << St->getBeginLoc();
  29. SourceLocation L = S.getLocForEndOfToken(Range.getEnd());
  30. S.Diag(L, diag::note_fallthrough_insert_semi_fixit)
  31. << FixItHint::CreateInsertion(L, ";");
  32. return nullptr;
  33. }
  34. auto *FnScope = S.getCurFunction();
  35. if (FnScope->SwitchStack.empty()) {
  36. S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch);
  37. return nullptr;
  38. }
  39. // If this is spelled as the standard C++17 attribute, but not in C++17, warn
  40. // about using it as an extension.
  41. if (!S.getLangOpts().CPlusPlus17 && A.isCXX11Attribute() &&
  42. !A.getScopeName())
  43. S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A;
  44. FnScope->setHasFallthroughStmt();
  45. return ::new (S.Context) FallThroughAttr(S.Context, A);
  46. }
  47. static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A,
  48. SourceRange Range) {
  49. std::vector<StringRef> DiagnosticIdentifiers;
  50. for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) {
  51. StringRef RuleName;
  52. if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr))
  53. return nullptr;
  54. // FIXME: Warn if the rule name is unknown. This is tricky because only
  55. // clang-tidy knows about available rules.
  56. DiagnosticIdentifiers.push_back(RuleName);
  57. }
  58. return ::new (S.Context) SuppressAttr(
  59. S.Context, A, DiagnosticIdentifiers.data(), DiagnosticIdentifiers.size());
  60. }
  61. static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
  62. SourceRange) {
  63. IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
  64. IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
  65. IdentifierLoc *StateLoc = A.getArgAsIdent(2);
  66. Expr *ValueExpr = A.getArgAsExpr(3);
  67. StringRef PragmaName =
  68. llvm::StringSwitch<StringRef>(PragmaNameLoc->Ident->getName())
  69. .Cases("unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam",
  70. PragmaNameLoc->Ident->getName())
  71. .Default("clang loop");
  72. // This could be handled automatically by adding a Subjects definition in
  73. // Attr.td, but that would make the diagnostic behavior worse in this case
  74. // because the user spells this attribute as a pragma.
  75. if (!isa<DoStmt, ForStmt, CXXForRangeStmt, WhileStmt>(St)) {
  76. std::string Pragma = "#pragma " + std::string(PragmaName);
  77. S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma;
  78. return nullptr;
  79. }
  80. LoopHintAttr::OptionType Option;
  81. LoopHintAttr::LoopHintState State;
  82. auto SetHints = [&Option, &State](LoopHintAttr::OptionType O,
  83. LoopHintAttr::LoopHintState S) {
  84. Option = O;
  85. State = S;
  86. };
  87. if (PragmaName == "nounroll") {
  88. SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
  89. } else if (PragmaName == "unroll") {
  90. // #pragma unroll N
  91. if (ValueExpr)
  92. SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
  93. else
  94. SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable);
  95. } else if (PragmaName == "nounroll_and_jam") {
  96. SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable);
  97. } else if (PragmaName == "unroll_and_jam") {
  98. // #pragma unroll_and_jam N
  99. if (ValueExpr)
  100. SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric);
  101. else
  102. SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable);
  103. } else {
  104. // #pragma clang loop ...
  105. assert(OptionLoc && OptionLoc->Ident &&
  106. "Attribute must have valid option info.");
  107. Option = llvm::StringSwitch<LoopHintAttr::OptionType>(
  108. OptionLoc->Ident->getName())
  109. .Case("vectorize", LoopHintAttr::Vectorize)
  110. .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
  111. .Case("interleave", LoopHintAttr::Interleave)
  112. .Case("vectorize_predicate", LoopHintAttr::VectorizePredicate)
  113. .Case("interleave_count", LoopHintAttr::InterleaveCount)
  114. .Case("unroll", LoopHintAttr::Unroll)
  115. .Case("unroll_count", LoopHintAttr::UnrollCount)
  116. .Case("pipeline", LoopHintAttr::PipelineDisabled)
  117. .Case("pipeline_initiation_interval",
  118. LoopHintAttr::PipelineInitiationInterval)
  119. .Case("distribute", LoopHintAttr::Distribute)
  120. .Default(LoopHintAttr::Vectorize);
  121. if (Option == LoopHintAttr::VectorizeWidth) {
  122. assert((ValueExpr || (StateLoc && StateLoc->Ident)) &&
  123. "Attribute must have a valid value expression or argument.");
  124. if (ValueExpr && S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc()))
  125. return nullptr;
  126. if (StateLoc && StateLoc->Ident && StateLoc->Ident->isStr("scalable"))
  127. State = LoopHintAttr::ScalableWidth;
  128. else
  129. State = LoopHintAttr::FixedWidth;
  130. } else if (Option == LoopHintAttr::InterleaveCount ||
  131. Option == LoopHintAttr::UnrollCount ||
  132. Option == LoopHintAttr::PipelineInitiationInterval) {
  133. assert(ValueExpr && "Attribute must have a valid value expression.");
  134. if (S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc()))
  135. return nullptr;
  136. State = LoopHintAttr::Numeric;
  137. } else if (Option == LoopHintAttr::Vectorize ||
  138. Option == LoopHintAttr::Interleave ||
  139. Option == LoopHintAttr::VectorizePredicate ||
  140. Option == LoopHintAttr::Unroll ||
  141. Option == LoopHintAttr::Distribute ||
  142. Option == LoopHintAttr::PipelineDisabled) {
  143. assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument");
  144. if (StateLoc->Ident->isStr("disable"))
  145. State = LoopHintAttr::Disable;
  146. else if (StateLoc->Ident->isStr("assume_safety"))
  147. State = LoopHintAttr::AssumeSafety;
  148. else if (StateLoc->Ident->isStr("full"))
  149. State = LoopHintAttr::Full;
  150. else if (StateLoc->Ident->isStr("enable"))
  151. State = LoopHintAttr::Enable;
  152. else
  153. llvm_unreachable("bad loop hint argument");
  154. } else
  155. llvm_unreachable("bad loop hint");
  156. }
  157. return LoopHintAttr::CreateImplicit(S.Context, Option, State, ValueExpr, A);
  158. }
  159. namespace {
  160. class CallExprFinder : public ConstEvaluatedExprVisitor<CallExprFinder> {
  161. bool FoundCallExpr = false;
  162. public:
  163. typedef ConstEvaluatedExprVisitor<CallExprFinder> Inherited;
  164. CallExprFinder(Sema &S, const Stmt *St) : Inherited(S.Context) { Visit(St); }
  165. bool foundCallExpr() { return FoundCallExpr; }
  166. void VisitCallExpr(const CallExpr *E) { FoundCallExpr = true; }
  167. void VisitAsmStmt(const AsmStmt *S) { FoundCallExpr = true; }
  168. void Visit(const Stmt *St) {
  169. if (!St)
  170. return;
  171. ConstEvaluatedExprVisitor<CallExprFinder>::Visit(St);
  172. }
  173. };
  174. } // namespace
  175. static Attr *handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
  176. SourceRange Range) {
  177. NoMergeAttr NMA(S.Context, A);
  178. CallExprFinder CEF(S, St);
  179. if (!CEF.foundCallExpr()) {
  180. S.Diag(St->getBeginLoc(), diag::warn_nomerge_attribute_ignored_in_stmt)
  181. << NMA.getSpelling();
  182. return nullptr;
  183. }
  184. return ::new (S.Context) NoMergeAttr(S.Context, A);
  185. }
  186. static Attr *handleMustTailAttr(Sema &S, Stmt *St, const ParsedAttr &A,
  187. SourceRange Range) {
  188. // Validation is in Sema::ActOnAttributedStmt().
  189. return ::new (S.Context) MustTailAttr(S.Context, A);
  190. }
  191. static Attr *handleLikely(Sema &S, Stmt *St, const ParsedAttr &A,
  192. SourceRange Range) {
  193. if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
  194. S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
  195. return ::new (S.Context) LikelyAttr(S.Context, A);
  196. }
  197. static Attr *handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A,
  198. SourceRange Range) {
  199. if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
  200. S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
  201. return ::new (S.Context) UnlikelyAttr(S.Context, A);
  202. }
  203. #define WANT_STMT_MERGE_LOGIC
  204. #include "clang/Sema/AttrParsedAttrImpl.inc"
  205. #undef WANT_STMT_MERGE_LOGIC
  206. static void
  207. CheckForIncompatibleAttributes(Sema &S,
  208. const SmallVectorImpl<const Attr *> &Attrs) {
  209. // The vast majority of attributed statements will only have one attribute
  210. // on them, so skip all of the checking in the common case.
  211. if (Attrs.size() < 2)
  212. return;
  213. // First, check for the easy cases that are table-generated for us.
  214. if (!DiagnoseMutualExclusions(S, Attrs))
  215. return;
  216. // There are 6 categories of loop hints attributes: vectorize, interleave,
  217. // unroll, unroll_and_jam, pipeline and distribute. Except for distribute they
  218. // come in two variants: a state form and a numeric form. The state form
  219. // selectively defaults/enables/disables the transformation for the loop
  220. // (for unroll, default indicates full unrolling rather than enabling the
  221. // transformation). The numeric form form provides an integer hint (for
  222. // example, unroll count) to the transformer. The following array accumulates
  223. // the hints encountered while iterating through the attributes to check for
  224. // compatibility.
  225. struct {
  226. const LoopHintAttr *StateAttr;
  227. const LoopHintAttr *NumericAttr;
  228. } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
  229. {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
  230. {nullptr, nullptr}};
  231. for (const auto *I : Attrs) {
  232. const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
  233. // Skip non loop hint attributes
  234. if (!LH)
  235. continue;
  236. LoopHintAttr::OptionType Option = LH->getOption();
  237. enum {
  238. Vectorize,
  239. Interleave,
  240. Unroll,
  241. UnrollAndJam,
  242. Distribute,
  243. Pipeline,
  244. VectorizePredicate
  245. } Category;
  246. switch (Option) {
  247. case LoopHintAttr::Vectorize:
  248. case LoopHintAttr::VectorizeWidth:
  249. Category = Vectorize;
  250. break;
  251. case LoopHintAttr::Interleave:
  252. case LoopHintAttr::InterleaveCount:
  253. Category = Interleave;
  254. break;
  255. case LoopHintAttr::Unroll:
  256. case LoopHintAttr::UnrollCount:
  257. Category = Unroll;
  258. break;
  259. case LoopHintAttr::UnrollAndJam:
  260. case LoopHintAttr::UnrollAndJamCount:
  261. Category = UnrollAndJam;
  262. break;
  263. case LoopHintAttr::Distribute:
  264. // Perform the check for duplicated 'distribute' hints.
  265. Category = Distribute;
  266. break;
  267. case LoopHintAttr::PipelineDisabled:
  268. case LoopHintAttr::PipelineInitiationInterval:
  269. Category = Pipeline;
  270. break;
  271. case LoopHintAttr::VectorizePredicate:
  272. Category = VectorizePredicate;
  273. break;
  274. };
  275. assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0]));
  276. auto &CategoryState = HintAttrs[Category];
  277. const LoopHintAttr *PrevAttr;
  278. if (Option == LoopHintAttr::Vectorize ||
  279. Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll ||
  280. Option == LoopHintAttr::UnrollAndJam ||
  281. Option == LoopHintAttr::VectorizePredicate ||
  282. Option == LoopHintAttr::PipelineDisabled ||
  283. Option == LoopHintAttr::Distribute) {
  284. // Enable|Disable|AssumeSafety hint. For example, vectorize(enable).
  285. PrevAttr = CategoryState.StateAttr;
  286. CategoryState.StateAttr = LH;
  287. } else {
  288. // Numeric hint. For example, vectorize_width(8).
  289. PrevAttr = CategoryState.NumericAttr;
  290. CategoryState.NumericAttr = LH;
  291. }
  292. PrintingPolicy Policy(S.Context.getLangOpts());
  293. SourceLocation OptionLoc = LH->getRange().getBegin();
  294. if (PrevAttr)
  295. // Cannot specify same type of attribute twice.
  296. S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
  297. << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
  298. << LH->getDiagnosticName(Policy);
  299. if (CategoryState.StateAttr && CategoryState.NumericAttr &&
  300. (Category == Unroll || Category == UnrollAndJam ||
  301. CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
  302. // Disable hints are not compatible with numeric hints of the same
  303. // category. As a special case, numeric unroll hints are also not
  304. // compatible with enable or full form of the unroll pragma because these
  305. // directives indicate full unrolling.
  306. S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
  307. << /*Duplicate=*/false
  308. << CategoryState.StateAttr->getDiagnosticName(Policy)
  309. << CategoryState.NumericAttr->getDiagnosticName(Policy);
  310. }
  311. }
  312. }
  313. static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A,
  314. SourceRange Range) {
  315. // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
  316. // useful for OpenCL 1.x too and doesn't require HW support.
  317. // opencl_unroll_hint can have 0 arguments (compiler
  318. // determines unrolling factor) or 1 argument (the unroll factor provided
  319. // by the user).
  320. unsigned UnrollFactor = 0;
  321. if (A.getNumArgs() == 1) {
  322. Expr *E = A.getArgAsExpr(0);
  323. Optional<llvm::APSInt> ArgVal;
  324. if (!(ArgVal = E->getIntegerConstantExpr(S.Context))) {
  325. S.Diag(A.getLoc(), diag::err_attribute_argument_type)
  326. << A << AANT_ArgumentIntegerConstant << E->getSourceRange();
  327. return nullptr;
  328. }
  329. int Val = ArgVal->getSExtValue();
  330. if (Val <= 0) {
  331. S.Diag(A.getRange().getBegin(),
  332. diag::err_attribute_requires_positive_integer)
  333. << A << /* positive */ 0;
  334. return nullptr;
  335. }
  336. UnrollFactor = static_cast<unsigned>(Val);
  337. }
  338. return ::new (S.Context) OpenCLUnrollHintAttr(S.Context, A, UnrollFactor);
  339. }
  340. static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
  341. SourceRange Range) {
  342. if (A.isInvalid() || A.getKind() == ParsedAttr::IgnoredAttribute)
  343. return nullptr;
  344. // Unknown attributes are automatically warned on. Target-specific attributes
  345. // which do not apply to the current target architecture are treated as
  346. // though they were unknown attributes.
  347. const TargetInfo *Aux = S.Context.getAuxTargetInfo();
  348. if (A.getKind() == ParsedAttr::UnknownAttribute ||
  349. !(A.existsInTarget(S.Context.getTargetInfo()) ||
  350. (S.Context.getLangOpts().SYCLIsDevice && Aux &&
  351. A.existsInTarget(*Aux)))) {
  352. S.Diag(A.getLoc(), A.isDeclspecAttribute()
  353. ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
  354. : (unsigned)diag::warn_unknown_attribute_ignored)
  355. << A << A.getRange();
  356. return nullptr;
  357. }
  358. if (S.checkCommonAttributeFeatures(St, A))
  359. return nullptr;
  360. switch (A.getKind()) {
  361. case ParsedAttr::AT_FallThrough:
  362. return handleFallThroughAttr(S, St, A, Range);
  363. case ParsedAttr::AT_LoopHint:
  364. return handleLoopHintAttr(S, St, A, Range);
  365. case ParsedAttr::AT_OpenCLUnrollHint:
  366. return handleOpenCLUnrollHint(S, St, A, Range);
  367. case ParsedAttr::AT_Suppress:
  368. return handleSuppressAttr(S, St, A, Range);
  369. case ParsedAttr::AT_NoMerge:
  370. return handleNoMergeAttr(S, St, A, Range);
  371. case ParsedAttr::AT_MustTail:
  372. return handleMustTailAttr(S, St, A, Range);
  373. case ParsedAttr::AT_Likely:
  374. return handleLikely(S, St, A, Range);
  375. case ParsedAttr::AT_Unlikely:
  376. return handleUnlikely(S, St, A, Range);
  377. default:
  378. // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
  379. // declaration attribute is not written on a statement, but this code is
  380. // needed for attributes in Attr.td that do not list any subjects.
  381. S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
  382. << A << St->getBeginLoc();
  383. return nullptr;
  384. }
  385. }
  386. void Sema::ProcessStmtAttributes(Stmt *S,
  387. const ParsedAttributesWithRange &InAttrs,
  388. SmallVectorImpl<const Attr *> &OutAttrs) {
  389. for (const ParsedAttr &AL : InAttrs) {
  390. if (const Attr *A = ProcessStmtAttribute(*this, S, AL, InAttrs.Range))
  391. OutAttrs.push_back(A);
  392. }
  393. CheckForIncompatibleAttributes(*this, OutAttrs);
  394. }