SemaStmtAttr.cpp 14 KB

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