SemaStmtAttr.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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/Sema/SemaInternal.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/Basic/SourceManager.h"
  15. #include "clang/Sema/DelayedDiagnostic.h"
  16. #include "clang/Sema/Lookup.h"
  17. #include "clang/Sema/ScopeInfo.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. using namespace clang;
  20. using namespace sema;
  21. static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A,
  22. SourceRange Range) {
  23. FallThroughAttr Attr(A.getRange(), S.Context,
  24. A.getAttributeSpellingListIndex());
  25. if (!isa<NullStmt>(St)) {
  26. S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target)
  27. << Attr.getSpelling() << St->getBeginLoc();
  28. if (isa<SwitchCase>(St)) {
  29. SourceLocation L = S.getLocForEndOfToken(Range.getEnd());
  30. S.Diag(L, diag::note_fallthrough_insert_semi_fixit)
  31. << FixItHint::CreateInsertion(L, ";");
  32. }
  33. return nullptr;
  34. }
  35. auto *FnScope = S.getCurFunction();
  36. if (FnScope->SwitchStack.empty()) {
  37. S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch);
  38. return nullptr;
  39. }
  40. // If this is spelled as the standard C++17 attribute, but not in C++17, warn
  41. // about using it as an extension.
  42. if (!S.getLangOpts().CPlusPlus17 && A.isCXX11Attribute() &&
  43. !A.getScopeName())
  44. S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A.getName();
  45. FnScope->setHasFallthroughStmt();
  46. return ::new (S.Context) auto(Attr);
  47. }
  48. static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A,
  49. SourceRange Range) {
  50. if (A.getNumArgs() < 1) {
  51. S.Diag(A.getLoc(), diag::err_attribute_too_few_arguments) << A << 1;
  52. return nullptr;
  53. }
  54. std::vector<StringRef> DiagnosticIdentifiers;
  55. for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) {
  56. StringRef RuleName;
  57. if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr))
  58. return nullptr;
  59. // FIXME: Warn if the rule name is unknown. This is tricky because only
  60. // clang-tidy knows about available rules.
  61. DiagnosticIdentifiers.push_back(RuleName);
  62. }
  63. return ::new (S.Context) SuppressAttr(
  64. A.getRange(), S.Context, DiagnosticIdentifiers.data(),
  65. DiagnosticIdentifiers.size(), A.getAttributeSpellingListIndex());
  66. }
  67. static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
  68. SourceRange) {
  69. IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
  70. IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
  71. IdentifierLoc *StateLoc = A.getArgAsIdent(2);
  72. Expr *ValueExpr = A.getArgAsExpr(3);
  73. StringRef PragmaName =
  74. llvm::StringSwitch<StringRef>(PragmaNameLoc->Ident->getName())
  75. .Cases("unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam",
  76. PragmaNameLoc->Ident->getName())
  77. .Default("clang loop");
  78. if (St->getStmtClass() != Stmt::DoStmtClass &&
  79. St->getStmtClass() != Stmt::ForStmtClass &&
  80. St->getStmtClass() != Stmt::CXXForRangeStmtClass &&
  81. St->getStmtClass() != Stmt::WhileStmtClass) {
  82. std::string Pragma = "#pragma " + std::string(PragmaName);
  83. S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma;
  84. return nullptr;
  85. }
  86. LoopHintAttr::Spelling Spelling =
  87. LoopHintAttr::Spelling(A.getAttributeSpellingListIndex());
  88. LoopHintAttr::OptionType Option;
  89. LoopHintAttr::LoopHintState State;
  90. auto SetHints = [&Option, &State](LoopHintAttr::OptionType O,
  91. LoopHintAttr::LoopHintState S) {
  92. Option = O;
  93. State = S;
  94. };
  95. if (PragmaName == "nounroll") {
  96. SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
  97. } else if (PragmaName == "unroll") {
  98. // #pragma unroll N
  99. if (ValueExpr)
  100. SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
  101. else
  102. SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable);
  103. } else if (PragmaName == "nounroll_and_jam") {
  104. SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable);
  105. } else if (PragmaName == "unroll_and_jam") {
  106. // #pragma unroll_and_jam N
  107. if (ValueExpr)
  108. SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric);
  109. else
  110. SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable);
  111. } else {
  112. // #pragma clang loop ...
  113. assert(OptionLoc && OptionLoc->Ident &&
  114. "Attribute must have valid option info.");
  115. Option = llvm::StringSwitch<LoopHintAttr::OptionType>(
  116. OptionLoc->Ident->getName())
  117. .Case("vectorize", LoopHintAttr::Vectorize)
  118. .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
  119. .Case("interleave", LoopHintAttr::Interleave)
  120. .Case("interleave_count", LoopHintAttr::InterleaveCount)
  121. .Case("unroll", LoopHintAttr::Unroll)
  122. .Case("unroll_count", LoopHintAttr::UnrollCount)
  123. .Case("pipeline", LoopHintAttr::PipelineDisabled)
  124. .Case("pipeline_initiation_interval",
  125. LoopHintAttr::PipelineInitiationInterval)
  126. .Case("distribute", LoopHintAttr::Distribute)
  127. .Default(LoopHintAttr::Vectorize);
  128. if (Option == LoopHintAttr::VectorizeWidth ||
  129. Option == LoopHintAttr::InterleaveCount ||
  130. Option == LoopHintAttr::UnrollCount ||
  131. Option == LoopHintAttr::PipelineInitiationInterval) {
  132. assert(ValueExpr && "Attribute must have a valid value expression.");
  133. if (S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc()))
  134. return nullptr;
  135. State = LoopHintAttr::Numeric;
  136. } else if (Option == LoopHintAttr::Vectorize ||
  137. Option == LoopHintAttr::Interleave ||
  138. Option == LoopHintAttr::Unroll ||
  139. Option == LoopHintAttr::Distribute ||
  140. Option == LoopHintAttr::PipelineDisabled) {
  141. assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument");
  142. if (StateLoc->Ident->isStr("disable"))
  143. State = LoopHintAttr::Disable;
  144. else if (StateLoc->Ident->isStr("assume_safety"))
  145. State = LoopHintAttr::AssumeSafety;
  146. else if (StateLoc->Ident->isStr("full"))
  147. State = LoopHintAttr::Full;
  148. else if (StateLoc->Ident->isStr("enable"))
  149. State = LoopHintAttr::Enable;
  150. else
  151. llvm_unreachable("bad loop hint argument");
  152. } else
  153. llvm_unreachable("bad loop hint");
  154. }
  155. return LoopHintAttr::CreateImplicit(S.Context, Spelling, Option, State,
  156. ValueExpr, A.getRange());
  157. }
  158. static void
  159. CheckForIncompatibleAttributes(Sema &S,
  160. const SmallVectorImpl<const Attr *> &Attrs) {
  161. // There are 6 categories of loop hints attributes: vectorize, interleave,
  162. // unroll, unroll_and_jam, pipeline and distribute. Except for distribute they
  163. // come in two variants: a state form and a numeric form. The state form
  164. // selectively defaults/enables/disables the transformation for the loop
  165. // (for unroll, default indicates full unrolling rather than enabling the
  166. // transformation). The numeric form form provides an integer hint (for
  167. // example, unroll count) to the transformer. The following array accumulates
  168. // the hints encountered while iterating through the attributes to check for
  169. // compatibility.
  170. struct {
  171. const LoopHintAttr *StateAttr;
  172. const LoopHintAttr *NumericAttr;
  173. } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
  174. {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}};
  175. for (const auto *I : Attrs) {
  176. const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
  177. // Skip non loop hint attributes
  178. if (!LH)
  179. continue;
  180. LoopHintAttr::OptionType Option = LH->getOption();
  181. enum {
  182. Vectorize,
  183. Interleave,
  184. Unroll,
  185. UnrollAndJam,
  186. Distribute,
  187. Pipeline
  188. } Category;
  189. switch (Option) {
  190. case LoopHintAttr::Vectorize:
  191. case LoopHintAttr::VectorizeWidth:
  192. Category = Vectorize;
  193. break;
  194. case LoopHintAttr::Interleave:
  195. case LoopHintAttr::InterleaveCount:
  196. Category = Interleave;
  197. break;
  198. case LoopHintAttr::Unroll:
  199. case LoopHintAttr::UnrollCount:
  200. Category = Unroll;
  201. break;
  202. case LoopHintAttr::UnrollAndJam:
  203. case LoopHintAttr::UnrollAndJamCount:
  204. Category = UnrollAndJam;
  205. break;
  206. case LoopHintAttr::Distribute:
  207. // Perform the check for duplicated 'distribute' hints.
  208. Category = Distribute;
  209. break;
  210. case LoopHintAttr::PipelineDisabled:
  211. case LoopHintAttr::PipelineInitiationInterval:
  212. Category = Pipeline;
  213. break;
  214. };
  215. assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0]));
  216. auto &CategoryState = HintAttrs[Category];
  217. const LoopHintAttr *PrevAttr;
  218. if (Option == LoopHintAttr::Vectorize ||
  219. Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll ||
  220. Option == LoopHintAttr::UnrollAndJam ||
  221. Option == LoopHintAttr::PipelineDisabled ||
  222. Option == LoopHintAttr::Distribute) {
  223. // Enable|Disable|AssumeSafety hint. For example, vectorize(enable).
  224. PrevAttr = CategoryState.StateAttr;
  225. CategoryState.StateAttr = LH;
  226. } else {
  227. // Numeric hint. For example, vectorize_width(8).
  228. PrevAttr = CategoryState.NumericAttr;
  229. CategoryState.NumericAttr = LH;
  230. }
  231. PrintingPolicy Policy(S.Context.getLangOpts());
  232. SourceLocation OptionLoc = LH->getRange().getBegin();
  233. if (PrevAttr)
  234. // Cannot specify same type of attribute twice.
  235. S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
  236. << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
  237. << LH->getDiagnosticName(Policy);
  238. if (CategoryState.StateAttr && CategoryState.NumericAttr &&
  239. (Category == Unroll || Category == UnrollAndJam ||
  240. CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
  241. // Disable hints are not compatible with numeric hints of the same
  242. // category. As a special case, numeric unroll hints are also not
  243. // compatible with enable or full form of the unroll pragma because these
  244. // directives indicate full unrolling.
  245. S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
  246. << /*Duplicate=*/false
  247. << CategoryState.StateAttr->getDiagnosticName(Policy)
  248. << CategoryState.NumericAttr->getDiagnosticName(Policy);
  249. }
  250. }
  251. }
  252. static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A,
  253. SourceRange Range) {
  254. // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
  255. // useful for OpenCL 1.x too and doesn't require HW support.
  256. // opencl_unroll_hint can have 0 arguments (compiler
  257. // determines unrolling factor) or 1 argument (the unroll factor provided
  258. // by the user).
  259. unsigned NumArgs = A.getNumArgs();
  260. if (NumArgs > 1) {
  261. S.Diag(A.getLoc(), diag::err_attribute_too_many_arguments) << A << 1;
  262. return nullptr;
  263. }
  264. unsigned UnrollFactor = 0;
  265. if (NumArgs == 1) {
  266. Expr *E = A.getArgAsExpr(0);
  267. llvm::APSInt ArgVal(32);
  268. if (!E->isIntegerConstantExpr(ArgVal, S.Context)) {
  269. S.Diag(A.getLoc(), diag::err_attribute_argument_type)
  270. << A << AANT_ArgumentIntegerConstant << E->getSourceRange();
  271. return nullptr;
  272. }
  273. int Val = ArgVal.getSExtValue();
  274. if (Val <= 0) {
  275. S.Diag(A.getRange().getBegin(),
  276. diag::err_attribute_requires_positive_integer)
  277. << A << /* positive */ 0;
  278. return nullptr;
  279. }
  280. UnrollFactor = Val;
  281. }
  282. return OpenCLUnrollHintAttr::CreateImplicit(S.Context, UnrollFactor);
  283. }
  284. static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
  285. SourceRange Range) {
  286. switch (A.getKind()) {
  287. case ParsedAttr::UnknownAttribute:
  288. S.Diag(A.getLoc(), A.isDeclspecAttribute()
  289. ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
  290. : (unsigned)diag::warn_unknown_attribute_ignored)
  291. << A.getName();
  292. return nullptr;
  293. case ParsedAttr::AT_FallThrough:
  294. return handleFallThroughAttr(S, St, A, Range);
  295. case ParsedAttr::AT_LoopHint:
  296. return handleLoopHintAttr(S, St, A, Range);
  297. case ParsedAttr::AT_OpenCLUnrollHint:
  298. return handleOpenCLUnrollHint(S, St, A, Range);
  299. case ParsedAttr::AT_Suppress:
  300. return handleSuppressAttr(S, St, A, Range);
  301. default:
  302. // if we're here, then we parsed a known attribute, but didn't recognize
  303. // it as a statement attribute => it is declaration attribute
  304. S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
  305. << A.getName() << St->getBeginLoc();
  306. return nullptr;
  307. }
  308. }
  309. StmtResult Sema::ProcessStmtAttributes(Stmt *S,
  310. const ParsedAttributesView &AttrList,
  311. SourceRange Range) {
  312. SmallVector<const Attr*, 8> Attrs;
  313. for (const ParsedAttr &AL : AttrList) {
  314. if (Attr *a = ProcessStmtAttribute(*this, S, AL, Range))
  315. Attrs.push_back(a);
  316. }
  317. CheckForIncompatibleAttributes(*this, Attrs);
  318. if (Attrs.empty())
  319. return S;
  320. return ActOnAttributedStmt(Range.getBegin(), Attrs, S);
  321. }