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