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/TargetInfo.h"
16#include "clang/Sema/DelayedDiagnostic.h"
17#include "clang/Sema/ParsedAttr.h"
18#include "clang/Sema/ScopeInfo.h"
19#include <optional>
20
21using namespace clang;
22using namespace sema;
23
24static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A,
25 SourceRange Range) {
26 FallThroughAttr Attr(S.Context, A);
27 if (isa<SwitchCase>(Val: St)) {
28 S.Diag(Loc: A.getRange().getBegin(), DiagID: diag::err_fallthrough_attr_wrong_target)
29 << A << St->getBeginLoc();
30 SourceLocation L = S.getLocForEndOfToken(Loc: Range.getEnd());
31 S.Diag(Loc: L, DiagID: diag::note_fallthrough_insert_semi_fixit)
32 << FixItHint::CreateInsertion(InsertionLoc: L, Code: ";");
33 return nullptr;
34 }
35 auto *FnScope = S.getCurFunction();
36 if (FnScope->SwitchStack.empty()) {
37 S.Diag(Loc: A.getRange().getBegin(), DiagID: diag::err_fallthrough_attr_outside_switch);
38 return nullptr;
39 }
40
41 // CWG 3045: The innermost enclosing switch statement of a fallthrough
42 // statement S shall be contained in the innermost enclosing expansion
43 // statement (8.7 [stmt.expand]) of S, if any.
44 for (Scope *Sc = S.getCurScope();
45 Sc && !Sc->isFunctionScope() && !Sc->isSwitchScope();
46 Sc = Sc->getParent()) {
47 if (Sc->isExpansionStmtScope()) {
48 S.Diag(Loc: A.getLoc(), DiagID: diag::err_fallthrough_attr_invalid_placement);
49 return nullptr;
50 }
51 }
52
53 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
54 // about using it as an extension.
55 if (!S.getLangOpts().CPlusPlus17 && A.isCXX11Attribute() &&
56 !A.getScopeName())
57 S.Diag(Loc: A.getLoc(), DiagID: diag::ext_cxx17_attr) << A;
58
59 FnScope->setHasFallthroughStmt();
60 return ::new (S.Context) FallThroughAttr(S.Context, A);
61}
62
63static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A,
64 SourceRange Range) {
65 if (A.getAttributeSpellingListIndex() == SuppressAttr::CXX11_gsl_suppress &&
66 A.getNumArgs() < 1) {
67 // Suppression attribute with GSL spelling requires at least 1 argument.
68 S.Diag(Loc: A.getLoc(), DiagID: diag::err_attribute_too_few_arguments) << A << 1;
69 return nullptr;
70 }
71
72 std::vector<StringRef> DiagnosticIdentifiers;
73 for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) {
74 StringRef RuleName;
75
76 if (!S.checkStringLiteralArgumentAttr(Attr: A, ArgNum: I, Str&: RuleName, ArgLocation: nullptr))
77 return nullptr;
78
79 DiagnosticIdentifiers.push_back(x: RuleName);
80 }
81
82 return ::new (S.Context) SuppressAttr(
83 S.Context, A, DiagnosticIdentifiers.data(), DiagnosticIdentifiers.size());
84}
85
86static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
87 SourceRange) {
88 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(Arg: 0);
89 IdentifierLoc *OptionLoc = A.getArgAsIdent(Arg: 1);
90 IdentifierLoc *StateLoc = A.getArgAsIdent(Arg: 2);
91 Expr *ValueExpr = A.getArgAsExpr(Arg: 3);
92
93 StringRef PragmaName =
94 llvm::StringSwitch<StringRef>(
95 PragmaNameLoc->getIdentifierInfo()->getName())
96 .Cases(CaseStrings: {"unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam"},
97 Value: PragmaNameLoc->getIdentifierInfo()->getName())
98 .Default(Value: "clang loop");
99
100 // This could be handled automatically by adding a Subjects definition in
101 // Attr.td, but that would make the diagnostic behavior worse in this case
102 // because the user spells this attribute as a pragma.
103 if (!isa<DoStmt, ForStmt, CXXForRangeStmt, WhileStmt>(Val: St)) {
104 std::string Pragma = "#pragma " + std::string(PragmaName);
105 S.Diag(Loc: St->getBeginLoc(), DiagID: diag::err_pragma_loop_precedes_nonloop) << Pragma;
106 return nullptr;
107 }
108
109 LoopHintAttr::OptionType Option;
110 LoopHintAttr::LoopHintState State;
111
112 auto SetHints = [&Option, &State](LoopHintAttr::OptionType O,
113 LoopHintAttr::LoopHintState S) {
114 Option = O;
115 State = S;
116 };
117
118 if (PragmaName == "nounroll") {
119 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
120 } else if (PragmaName == "unroll") {
121 // #pragma unroll N
122 if (ValueExpr) {
123 if (!ValueExpr->isValueDependent()) {
124 auto Value = ValueExpr->EvaluateKnownConstInt(Ctx: S.getASTContext());
125 if (Value.isZero() || Value.isOne())
126 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
127 else
128 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
129 } else
130 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
131 } else
132 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable);
133 } else if (PragmaName == "nounroll_and_jam") {
134 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable);
135 } else if (PragmaName == "unroll_and_jam") {
136 // #pragma unroll_and_jam N
137 if (ValueExpr)
138 SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric);
139 else
140 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable);
141 } else {
142 // #pragma clang loop ...
143 assert(OptionLoc && OptionLoc->getIdentifierInfo() &&
144 "Attribute must have valid option info.");
145 Option = llvm::StringSwitch<LoopHintAttr::OptionType>(
146 OptionLoc->getIdentifierInfo()->getName())
147 .Case(S: "vectorize", Value: LoopHintAttr::Vectorize)
148 .Case(S: "vectorize_width", Value: LoopHintAttr::VectorizeWidth)
149 .Case(S: "interleave", Value: LoopHintAttr::Interleave)
150 .Case(S: "vectorize_predicate", Value: LoopHintAttr::VectorizePredicate)
151 .Case(S: "interleave_count", Value: LoopHintAttr::InterleaveCount)
152 .Case(S: "unroll", Value: LoopHintAttr::Unroll)
153 .Case(S: "unroll_count", Value: LoopHintAttr::UnrollCount)
154 .Case(S: "pipeline", Value: LoopHintAttr::PipelineDisabled)
155 .Case(S: "pipeline_initiation_interval",
156 Value: LoopHintAttr::PipelineInitiationInterval)
157 .Case(S: "distribute", Value: LoopHintAttr::Distribute)
158 .Case(S: "licm", Value: LoopHintAttr::LICMDisabled)
159 .Default(Value: LoopHintAttr::Vectorize);
160 if (Option == LoopHintAttr::VectorizeWidth) {
161 assert((ValueExpr || (StateLoc && StateLoc->getIdentifierInfo())) &&
162 "Attribute must have a valid value expression or argument.");
163 if (ValueExpr && S.CheckLoopHintExpr(E: ValueExpr, Loc: St->getBeginLoc(),
164 /*AllowZero=*/false))
165 return nullptr;
166 if (StateLoc && StateLoc->getIdentifierInfo() &&
167 StateLoc->getIdentifierInfo()->isStr(Str: "scalable"))
168 State = LoopHintAttr::ScalableWidth;
169 else
170 State = LoopHintAttr::FixedWidth;
171 } else if (Option == LoopHintAttr::InterleaveCount ||
172 Option == LoopHintAttr::UnrollCount ||
173 Option == LoopHintAttr::PipelineInitiationInterval) {
174 assert(ValueExpr && "Attribute must have a valid value expression.");
175 if (S.CheckLoopHintExpr(E: ValueExpr, Loc: St->getBeginLoc(),
176 /*AllowZero=*/false))
177 return nullptr;
178 State = LoopHintAttr::Numeric;
179 } else if (Option == LoopHintAttr::Vectorize ||
180 Option == LoopHintAttr::Interleave ||
181 Option == LoopHintAttr::VectorizePredicate ||
182 Option == LoopHintAttr::Unroll ||
183 Option == LoopHintAttr::Distribute ||
184 Option == LoopHintAttr::PipelineDisabled ||
185 Option == LoopHintAttr::LICMDisabled) {
186 assert(StateLoc && StateLoc->getIdentifierInfo() &&
187 "Loop hint must have an argument");
188 if (StateLoc->getIdentifierInfo()->isStr(Str: "disable"))
189 State = LoopHintAttr::Disable;
190 else if (StateLoc->getIdentifierInfo()->isStr(Str: "assume_safety"))
191 State = LoopHintAttr::AssumeSafety;
192 else if (StateLoc->getIdentifierInfo()->isStr(Str: "full"))
193 State = LoopHintAttr::Full;
194 else if (StateLoc->getIdentifierInfo()->isStr(Str: "enable"))
195 State = LoopHintAttr::Enable;
196 else
197 llvm_unreachable("bad loop hint argument");
198 } else
199 llvm_unreachable("bad loop hint");
200 }
201
202 return LoopHintAttr::CreateImplicit(Ctx&: S.Context, Option, State, Value: ValueExpr, CommonInfo: A);
203}
204
205namespace {
206class CallExprFinder : public ConstEvaluatedExprVisitor<CallExprFinder> {
207 bool FoundAsmStmt = false;
208 std::vector<const CallExpr *> CallExprs;
209
210public:
211 typedef ConstEvaluatedExprVisitor<CallExprFinder> Inherited;
212
213 CallExprFinder(Sema &S, const Stmt *St) : Inherited(S.Context) { Visit(St); }
214
215 bool foundCallExpr() { return !CallExprs.empty(); }
216 const std::vector<const CallExpr *> &getCallExprs() { return CallExprs; }
217
218 bool foundAsmStmt() { return FoundAsmStmt; }
219
220 void VisitCallExpr(const CallExpr *E) { CallExprs.push_back(x: E); }
221
222 void VisitAsmStmt(const AsmStmt *S) { FoundAsmStmt = true; }
223
224 void Visit(const Stmt *St) {
225 if (!St)
226 return;
227 ConstEvaluatedExprVisitor<CallExprFinder>::Visit(S: St);
228 }
229};
230} // namespace
231
232static Attr *handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
233 SourceRange Range) {
234 CallExprFinder CEF(S, St);
235
236 if (!CEF.foundCallExpr() && !CEF.foundAsmStmt()) {
237 S.Diag(Loc: St->getBeginLoc(), DiagID: diag::warn_attribute_ignored_no_calls_in_stmt)
238 << A;
239 return nullptr;
240 }
241
242 return ::new (S.Context) NoMergeAttr(S.Context, A);
243}
244
245static Attr *handleNoConvergentAttr(Sema &S, Stmt *St, const ParsedAttr &A,
246 SourceRange Range) {
247 CallExprFinder CEF(S, St);
248
249 if (!CEF.foundCallExpr() && !CEF.foundAsmStmt()) {
250 S.Diag(Loc: St->getBeginLoc(), DiagID: diag::warn_attribute_ignored_no_calls_in_stmt)
251 << A;
252 return nullptr;
253 }
254
255 return ::new (S.Context) NoConvergentAttr(S.Context, A);
256}
257
258template <typename OtherAttr, int DiagIdx>
259static bool CheckStmtInlineAttr(Sema &SemaRef, const Stmt *OrigSt,
260 const Stmt *CurSt,
261 const AttributeCommonInfo &A) {
262 CallExprFinder OrigCEF(SemaRef, OrigSt);
263 CallExprFinder CEF(SemaRef, CurSt);
264
265 // If the call expressions lists are equal in size, we can skip
266 // previously emitted diagnostics. However, if the statement has a pack
267 // expansion, we have no way of telling which CallExpr is the instantiated
268 // version of the other. In this case, we will end up re-diagnosing in the
269 // instantiation.
270 // ie: [[clang::always_inline]] non_dependent(), (other_call<Pack>()...)
271 // will diagnose nondependent again.
272 bool CanSuppressDiag =
273 OrigSt && CEF.getCallExprs().size() == OrigCEF.getCallExprs().size();
274
275 if (!CEF.foundCallExpr()) {
276 return SemaRef.Diag(Loc: CurSt->getBeginLoc(),
277 DiagID: diag::warn_attribute_ignored_no_calls_in_stmt)
278 << A;
279 }
280
281 for (const auto &Tup :
282 llvm::zip_longest(t: OrigCEF.getCallExprs(), u: CEF.getCallExprs())) {
283 // If the original call expression already had a callee, we already
284 // diagnosed this, so skip it here. We can't skip if there isn't a 1:1
285 // relationship between the two lists of call expressions.
286 if (!CanSuppressDiag || !(*std::get<0>(t: Tup))->getCalleeDecl()) {
287 const Decl *Callee = (*std::get<1>(t: Tup))->getCalleeDecl();
288 if (Callee &&
289 (Callee->hasAttr<OtherAttr>() || Callee->hasAttr<FlattenAttr>())) {
290 SemaRef.Diag(Loc: CurSt->getBeginLoc(),
291 DiagID: diag::warn_function_stmt_attribute_precedence)
292 << A << (Callee->hasAttr<OtherAttr>() ? DiagIdx : 1);
293 SemaRef.Diag(Loc: Callee->getBeginLoc(), DiagID: diag::note_conflicting_attribute);
294 }
295 }
296 }
297
298 return false;
299}
300
301bool Sema::CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
302 const AttributeCommonInfo &A) {
303 return CheckStmtInlineAttr<AlwaysInlineAttr, 0>(SemaRef&: *this, OrigSt, CurSt, A);
304}
305
306bool Sema::CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
307 const AttributeCommonInfo &A) {
308 return CheckStmtInlineAttr<NoInlineAttr, 2>(SemaRef&: *this, OrigSt, CurSt, A);
309}
310
311static Attr *handleNoInlineAttr(Sema &S, Stmt *St, const ParsedAttr &A,
312 SourceRange Range) {
313 NoInlineAttr NIA(S.Context, A);
314 if (!NIA.isStmtNoInline()) {
315 S.Diag(Loc: St->getBeginLoc(), DiagID: diag::warn_function_attribute_ignored_in_stmt)
316 << "[[clang::noinline]]";
317 return nullptr;
318 }
319
320 if (S.CheckNoInlineAttr(/*OrigSt=*/nullptr, CurSt: St, A))
321 return nullptr;
322
323 return ::new (S.Context) NoInlineAttr(S.Context, A);
324}
325
326static Attr *handleAlwaysInlineAttr(Sema &S, Stmt *St, const ParsedAttr &A,
327 SourceRange Range) {
328 AlwaysInlineAttr AIA(S.Context, A);
329 if (!S.getLangOpts().MicrosoftExt &&
330 (AIA.isMSVCForceInline() || AIA.isMSVCForceInlineCalls())) {
331 S.Diag(Loc: St->getBeginLoc(), DiagID: diag::warn_attribute_ignored) << A;
332 return nullptr;
333 }
334 if (AIA.isMSVCForceInline()) {
335 S.Diag(Loc: St->getBeginLoc(), DiagID: diag::warn_function_attribute_ignored_in_stmt)
336 << "[[msvc::forceinline_calls]]";
337 return nullptr;
338 }
339 if (!AIA.isClangAlwaysInline() && !AIA.isMSVCForceInlineCalls()) {
340 S.Diag(Loc: St->getBeginLoc(), DiagID: diag::warn_function_attribute_ignored_in_stmt)
341 << "[[clang::always_inline]]";
342 return nullptr;
343 }
344
345 if (S.CheckAlwaysInlineAttr(/*OrigSt=*/nullptr, CurSt: St, A))
346 return nullptr;
347
348 return ::new (S.Context) AlwaysInlineAttr(S.Context, A);
349}
350
351static Attr *handleCXXAssumeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
352 SourceRange Range) {
353 ExprResult Res = S.ActOnCXXAssumeAttr(St, A, Range);
354 if (!Res.isUsable())
355 return nullptr;
356
357 return ::new (S.Context) CXXAssumeAttr(S.Context, A, Res.get());
358}
359
360static Attr *handleMustTailAttr(Sema &S, Stmt *St, const ParsedAttr &A,
361 SourceRange Range) {
362 // Validation is in Sema::ActOnAttributedStmt().
363 return ::new (S.Context) MustTailAttr(S.Context, A);
364}
365
366static Attr *handleLikely(Sema &S, Stmt *St, const ParsedAttr &A,
367 SourceRange Range) {
368
369 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
370 S.Diag(Loc: A.getLoc(), DiagID: diag::ext_cxx20_attr) << A << Range;
371
372 return ::new (S.Context) LikelyAttr(S.Context, A);
373}
374
375static Attr *handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A,
376 SourceRange Range) {
377
378 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
379 S.Diag(Loc: A.getLoc(), DiagID: diag::ext_cxx20_attr) << A << Range;
380
381 return ::new (S.Context) UnlikelyAttr(S.Context, A);
382}
383
384CodeAlignAttr *Sema::BuildCodeAlignAttr(const AttributeCommonInfo &CI,
385 Expr *E) {
386 if (!E->isValueDependent()) {
387 llvm::APSInt ArgVal;
388 ExprResult Res = VerifyIntegerConstantExpression(E, Result: &ArgVal);
389 if (Res.isInvalid())
390 return nullptr;
391 E = Res.get();
392
393 // This attribute requires an integer argument which is a constant power of
394 // two between 1 and 4096 inclusive.
395 if (ArgVal < CodeAlignAttr::MinimumAlignment ||
396 ArgVal > CodeAlignAttr::MaximumAlignment || !ArgVal.isPowerOf2()) {
397 if (std::optional<int64_t> Value = ArgVal.trySExtValue())
398 Diag(Loc: CI.getLoc(), DiagID: diag::err_attribute_power_of_two_in_range)
399 << CI << CodeAlignAttr::MinimumAlignment
400 << CodeAlignAttr::MaximumAlignment << Value.value();
401 else
402 Diag(Loc: CI.getLoc(), DiagID: diag::err_attribute_power_of_two_in_range)
403 << CI << CodeAlignAttr::MinimumAlignment
404 << CodeAlignAttr::MaximumAlignment << E;
405 return nullptr;
406 }
407 }
408 return new (Context) CodeAlignAttr(Context, CI, E);
409}
410
411static Attr *handleCodeAlignAttr(Sema &S, Stmt *St, const ParsedAttr &A) {
412
413 Expr *E = A.getArgAsExpr(Arg: 0);
414 return S.BuildCodeAlignAttr(CI: A, E);
415}
416
417// Diagnose non-identical duplicates as a 'conflicting' loop attributes
418// and suppress duplicate errors in cases where the two match.
419template <typename LoopAttrT>
420static void CheckForDuplicateLoopAttrs(Sema &S, ArrayRef<const Attr *> Attrs) {
421 auto FindFunc = [](const Attr *A) { return isa<const LoopAttrT>(A); };
422 const auto *FirstItr = llvm::find_if(Attrs, FindFunc);
423
424 if (FirstItr == Attrs.end()) // no attributes found
425 return;
426
427 const auto *LastFoundItr = FirstItr;
428 std::optional<llvm::APSInt> FirstValue;
429
430 const auto *CAFA =
431 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*FirstItr)->getAlignment());
432 // Return early if first alignment expression is dependent (since we don't
433 // know what the effective size will be), and skip the loop entirely.
434 if (!CAFA)
435 return;
436
437 while (Attrs.end() != (LastFoundItr = std::find_if(LastFoundItr + 1,
438 Attrs.end(), FindFunc))) {
439 const auto *CASA =
440 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*LastFoundItr)->getAlignment());
441 // If the value is dependent, we can not test anything.
442 if (!CASA)
443 return;
444 // Test the attribute values.
445 llvm::APSInt SecondValue = CASA->getResultAsAPSInt();
446 if (!FirstValue)
447 FirstValue = CAFA->getResultAsAPSInt();
448
449 if (llvm::APSInt::isSameValue(I1: *FirstValue, I2: SecondValue))
450 continue;
451
452 S.Diag((*LastFoundItr)->getLocation(), diag::err_loop_attr_conflict)
453 << *FirstItr;
454 S.Diag((*FirstItr)->getLocation(), diag::note_previous_attribute);
455 }
456}
457
458static Attr *handleMSConstexprAttr(Sema &S, Stmt *St, const ParsedAttr &A,
459 SourceRange Range) {
460 if (!S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2022_3)) {
461 S.Diag(Loc: A.getLoc(), DiagID: diag::warn_unknown_attribute_ignored)
462 << A << A.getRange();
463 return nullptr;
464 }
465 return ::new (S.Context) MSConstexprAttr(S.Context, A);
466}
467
468#define WANT_STMT_MERGE_LOGIC
469#include "clang/Sema/AttrParsedAttrImpl.inc"
470#undef WANT_STMT_MERGE_LOGIC
471
472static void
473CheckForIncompatibleAttributes(Sema &S,
474 const SmallVectorImpl<const Attr *> &Attrs) {
475 // The vast majority of attributed statements will only have one attribute
476 // on them, so skip all of the checking in the common case.
477 if (Attrs.size() < 2)
478 return;
479
480 // First, check for the easy cases that are table-generated for us.
481 if (!DiagnoseMutualExclusions(S, C: Attrs))
482 return;
483
484 enum CategoryType {
485 // For the following categories, they come in two variants: a state form and
486 // a numeric form. The state form may be one of default, enable, and
487 // disable. The numeric form provides an integer hint (for example, unroll
488 // count) to the transformer.
489 Vectorize,
490 Interleave,
491 UnrollAndJam,
492 Pipeline,
493 // For unroll, default indicates full unrolling rather than enabling the
494 // transformation.
495 Unroll,
496 // The loop distribution transformation only has a state form that is
497 // exposed by #pragma clang loop distribute (enable | disable).
498 Distribute,
499 // The vector predication only has a state form that is exposed by
500 // #pragma clang loop vectorize_predicate (enable | disable).
501 VectorizePredicate,
502 // The LICM transformation only has a disable state form that is
503 // exposed by #pragma clang loop licm(disable).
504 LICM,
505 // This serves as a indicator to how many category are listed in this enum.
506 NumberOfCategories
507 };
508 // The following array accumulates the hints encountered while iterating
509 // through the attributes to check for compatibility.
510 struct {
511 const LoopHintAttr *StateAttr;
512 const LoopHintAttr *NumericAttr;
513 } HintAttrs[CategoryType::NumberOfCategories] = {};
514
515 for (const auto *I : Attrs) {
516 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(Val: I);
517
518 // Skip non loop hint attributes
519 if (!LH)
520 continue;
521
522 CategoryType Category = CategoryType::NumberOfCategories;
523 LoopHintAttr::OptionType Option = LH->getOption();
524 switch (Option) {
525 case LoopHintAttr::Vectorize:
526 case LoopHintAttr::VectorizeWidth:
527 Category = Vectorize;
528 break;
529 case LoopHintAttr::Interleave:
530 case LoopHintAttr::InterleaveCount:
531 Category = Interleave;
532 break;
533 case LoopHintAttr::Unroll:
534 case LoopHintAttr::UnrollCount:
535 Category = Unroll;
536 break;
537 case LoopHintAttr::UnrollAndJam:
538 case LoopHintAttr::UnrollAndJamCount:
539 Category = UnrollAndJam;
540 break;
541 case LoopHintAttr::Distribute:
542 // Perform the check for duplicated 'distribute' hints.
543 Category = Distribute;
544 break;
545 case LoopHintAttr::PipelineDisabled:
546 case LoopHintAttr::PipelineInitiationInterval:
547 Category = Pipeline;
548 break;
549 case LoopHintAttr::VectorizePredicate:
550 Category = VectorizePredicate;
551 break;
552 case LoopHintAttr::LICMDisabled:
553 Category = LICM;
554 break;
555 };
556
557 assert(Category != NumberOfCategories && "Unhandled loop hint option");
558 auto &CategoryState = HintAttrs[Category];
559 const LoopHintAttr *PrevAttr;
560 if (Option == LoopHintAttr::Vectorize ||
561 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll ||
562 Option == LoopHintAttr::UnrollAndJam ||
563 Option == LoopHintAttr::VectorizePredicate ||
564 Option == LoopHintAttr::PipelineDisabled ||
565 Option == LoopHintAttr::LICMDisabled ||
566 Option == LoopHintAttr::Distribute) {
567 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable).
568 PrevAttr = CategoryState.StateAttr;
569 CategoryState.StateAttr = LH;
570 } else {
571 // Numeric hint. For example, vectorize_width(8).
572 PrevAttr = CategoryState.NumericAttr;
573 CategoryState.NumericAttr = LH;
574 }
575
576 PrintingPolicy Policy(S.Context.getLangOpts());
577 SourceLocation OptionLoc = LH->getRange().getBegin();
578 if (PrevAttr)
579 // Cannot specify same type of attribute twice.
580 S.Diag(Loc: OptionLoc, DiagID: diag::err_pragma_loop_compatibility)
581 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
582 << LH->getDiagnosticName(Policy);
583
584 if (CategoryState.StateAttr && CategoryState.NumericAttr &&
585 (Category == Unroll || Category == UnrollAndJam ||
586 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
587 // Disable hints are not compatible with numeric hints of the same
588 // category. As a special case, numeric unroll hints are also not
589 // compatible with enable or full form of the unroll pragma because these
590 // directives indicate full unrolling.
591 S.Diag(Loc: OptionLoc, DiagID: diag::err_pragma_loop_compatibility)
592 << /*Duplicate=*/false
593 << CategoryState.StateAttr->getDiagnosticName(Policy)
594 << CategoryState.NumericAttr->getDiagnosticName(Policy);
595 }
596 }
597}
598
599static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A,
600 SourceRange Range) {
601 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
602 // useful for OpenCL 1.x too and doesn't require HW support.
603 // opencl_unroll_hint can have 0 arguments (compiler
604 // determines unrolling factor) or 1 argument (the unroll factor provided
605 // by the user).
606 unsigned UnrollFactor = 0;
607 if (A.getNumArgs() == 1) {
608 Expr *E = A.getArgAsExpr(Arg: 0);
609 std::optional<llvm::APSInt> ArgVal;
610
611 if (!(ArgVal = E->getIntegerConstantExpr(Ctx: S.Context))) {
612 S.Diag(Loc: A.getLoc(), DiagID: diag::err_attribute_argument_type)
613 << A << AANT_ArgumentIntegerConstant << E->getSourceRange();
614 return nullptr;
615 }
616
617 int Val = ArgVal->getSExtValue();
618 if (Val <= 0) {
619 S.Diag(Loc: A.getRange().getBegin(),
620 DiagID: diag::err_attribute_requires_positive_integer)
621 << A << /* positive */ 0;
622 return nullptr;
623 }
624 UnrollFactor = static_cast<unsigned>(Val);
625 }
626
627 return ::new (S.Context) OpenCLUnrollHintAttr(S.Context, A, UnrollFactor);
628}
629
630static Attr *handleHLSLLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
631 SourceRange Range) {
632
633 if (A.getSemanticSpelling() == HLSLLoopHintAttr::Spelling::Microsoft_loop &&
634 !A.checkAtMostNumArgs(S, Num: 0))
635 return nullptr;
636
637 unsigned UnrollFactor = 0;
638 if (A.getNumArgs() == 1) {
639 Expr *E = A.getArgAsExpr(Arg: 0);
640
641 if (S.CheckLoopHintExpr(E, Loc: St->getBeginLoc(),
642 /*AllowZero=*/false))
643 return nullptr;
644
645 std::optional<llvm::APSInt> ArgVal = E->getIntegerConstantExpr(Ctx: S.Context);
646 // CheckLoopHintExpr handles non int const cases
647 assert(ArgVal != std::nullopt && "ArgVal should be an integer constant.");
648 int Val = ArgVal->getSExtValue();
649 // CheckLoopHintExpr handles negative and zero cases
650 assert(Val > 0 && "Val should be a positive integer greater than zero.");
651 UnrollFactor = static_cast<unsigned>(Val);
652 }
653 return ::new (S.Context) HLSLLoopHintAttr(S.Context, A, UnrollFactor);
654}
655
656static Attr *handleHLSLControlFlowHint(Sema &S, Stmt *St, const ParsedAttr &A,
657 SourceRange Range) {
658
659 return ::new (S.Context) HLSLControlFlowHintAttr(S.Context, A);
660}
661
662static Attr *handleAtomicAttr(Sema &S, Stmt *St, const ParsedAttr &AL,
663 SourceRange Range) {
664 if (!AL.checkAtLeastNumArgs(S, Num: 1))
665 return nullptr;
666
667 SmallVector<AtomicAttr::ConsumedOption, 6> Options;
668 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
669 AtomicAttr::ConsumedOption Option;
670 StringRef OptionString;
671 SourceLocation Loc;
672
673 if (!AL.isArgIdent(Arg: ArgIndex)) {
674 S.Diag(Loc: AL.getArgAsExpr(Arg: ArgIndex)->getBeginLoc(),
675 DiagID: diag::err_attribute_argument_type)
676 << AL << AANT_ArgumentIdentifier;
677 return nullptr;
678 }
679
680 IdentifierLoc *Ident = AL.getArgAsIdent(Arg: ArgIndex);
681 OptionString = Ident->getIdentifierInfo()->getName();
682 Loc = Ident->getLoc();
683 if (!AtomicAttr::ConvertStrToConsumedOption(Val: OptionString, Out&: Option)) {
684 S.Diag(Loc, DiagID: diag::err_attribute_invalid_atomic_argument) << OptionString;
685 return nullptr;
686 }
687 Options.push_back(Elt: Option);
688 }
689
690 return ::new (S.Context)
691 AtomicAttr(S.Context, AL, Options.data(), Options.size());
692}
693
694static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
695 SourceRange Range) {
696 if (A.isInvalid() || A.getKind() == ParsedAttr::IgnoredAttribute)
697 return nullptr;
698
699 // Unknown attributes are automatically warned on. Target-specific attributes
700 // which do not apply to the current target architecture are treated as
701 // though they were unknown attributes.
702 const TargetInfo *Aux = S.Context.getAuxTargetInfo();
703 if (A.getKind() == ParsedAttr::UnknownAttribute ||
704 !(A.existsInTarget(Target: S.Context.getTargetInfo()) ||
705 (S.Context.getLangOpts().SYCLIsDevice && Aux &&
706 A.existsInTarget(Target: *Aux)))) {
707 if (A.isRegularKeywordAttribute()) {
708 S.Diag(Loc: A.getLoc(), DiagID: diag::err_keyword_not_supported_on_target)
709 << A << A.getRange();
710 } else if (A.isDeclspecAttribute()) {
711 S.Diag(Loc: A.getLoc(), DiagID: diag::warn_unhandled_ms_attribute_ignored)
712 << A << A.getRange();
713 } else {
714 S.DiagnoseUnknownAttribute(AL: A);
715 }
716 return nullptr;
717 }
718
719 if (S.checkCommonAttributeFeatures(S: St, A))
720 return nullptr;
721
722 switch (A.getKind()) {
723 case ParsedAttr::AT_AlwaysInline:
724 return handleAlwaysInlineAttr(S, St, A, Range);
725 case ParsedAttr::AT_CXXAssume:
726 return handleCXXAssumeAttr(S, St, A, Range);
727 case ParsedAttr::AT_FallThrough:
728 return handleFallThroughAttr(S, St, A, Range);
729 case ParsedAttr::AT_LoopHint:
730 return handleLoopHintAttr(S, St, A, Range);
731 case ParsedAttr::AT_HLSLLoopHint:
732 return handleHLSLLoopHintAttr(S, St, A, Range);
733 case ParsedAttr::AT_HLSLControlFlowHint:
734 return handleHLSLControlFlowHint(S, St, A, Range);
735 case ParsedAttr::AT_OpenCLUnrollHint:
736 return handleOpenCLUnrollHint(S, St, A, Range);
737 case ParsedAttr::AT_Suppress:
738 return handleSuppressAttr(S, St, A, Range);
739 case ParsedAttr::AT_NoMerge:
740 return handleNoMergeAttr(S, St, A, Range);
741 case ParsedAttr::AT_NoInline:
742 return handleNoInlineAttr(S, St, A, Range);
743 case ParsedAttr::AT_MustTail:
744 return handleMustTailAttr(S, St, A, Range);
745 case ParsedAttr::AT_Likely:
746 return handleLikely(S, St, A, Range);
747 case ParsedAttr::AT_Unlikely:
748 return handleUnlikely(S, St, A, Range);
749 case ParsedAttr::AT_CodeAlign:
750 return handleCodeAlignAttr(S, St, A);
751 case ParsedAttr::AT_MSConstexpr:
752 return handleMSConstexprAttr(S, St, A, Range);
753 case ParsedAttr::AT_NoConvergent:
754 return handleNoConvergentAttr(S, St, A, Range);
755 case ParsedAttr::AT_Annotate:
756 return S.CreateAnnotationAttr(AL: A);
757 case ParsedAttr::AT_Atomic:
758 return handleAtomicAttr(S, St, AL: A, Range);
759 default:
760 if (Attr *AT = nullptr; A.getInfo().handleStmtAttribute(S, St, Attr: A, Result&: AT) !=
761 ParsedAttrInfo::NotHandled) {
762 return AT;
763 }
764 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
765 // declaration attribute is not written on a statement, but this code is
766 // needed for attributes in Attr.td that do not list any subjects.
767 S.Diag(Loc: A.getRange().getBegin(), DiagID: diag::err_decl_attribute_invalid_on_stmt)
768 << A << A.isRegularKeywordAttribute() << St->getBeginLoc();
769 return nullptr;
770 }
771}
772
773void Sema::ProcessStmtAttributes(Stmt *S, const ParsedAttributes &InAttrs,
774 SmallVectorImpl<const Attr *> &OutAttrs) {
775 for (const ParsedAttr &AL : InAttrs) {
776 if (const Attr *A = ProcessStmtAttribute(S&: *this, St: S, A: AL, Range: InAttrs.Range))
777 OutAttrs.push_back(Elt: A);
778 }
779
780 CheckForIncompatibleAttributes(S&: *this, Attrs: OutAttrs);
781 CheckForDuplicateLoopAttrs<CodeAlignAttr>(S&: *this, Attrs: OutAttrs);
782}
783
784bool Sema::CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs) {
785 CheckForDuplicateLoopAttrs<CodeAlignAttr>(S&: *this, Attrs);
786 return false;
787}
788
789ExprResult Sema::ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A,
790 SourceRange Range) {
791 if (A.getNumArgs() != 1 || !A.getArgAsExpr(Arg: 0)) {
792 Diag(Loc: A.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments)
793 << A.getAttrName() << 1 << Range;
794 return ExprError();
795 }
796
797 auto *Assumption = A.getArgAsExpr(Arg: 0);
798
799 if (DiagnoseUnexpandedParameterPack(E: Assumption)) {
800 return ExprError();
801 }
802
803 if (Assumption->getDependence() == ExprDependence::None) {
804 ExprResult Res = BuildCXXAssumeExpr(Assumption, AttrName: A.getAttrName(), Range);
805 if (Res.isInvalid())
806 return ExprError();
807 Assumption = Res.get();
808 }
809
810 if (!getLangOpts().CPlusPlus23 &&
811 A.getSyntax() == AttributeCommonInfo::AS_CXX11)
812 Diag(Loc: A.getLoc(), DiagID: diag::ext_cxx23_attr) << A << Range;
813
814 return Assumption;
815}
816
817ExprResult Sema::BuildCXXAssumeExpr(Expr *Assumption,
818 const IdentifierInfo *AttrName,
819 SourceRange Range) {
820 if (!Assumption)
821 return ExprError();
822
823 ExprResult Res = CheckPlaceholderExpr(E: Assumption);
824 if (Res.isInvalid())
825 return ExprError();
826
827 Res = PerformContextuallyConvertToBool(From: Res.get());
828 if (Res.isInvalid())
829 return ExprError();
830
831 Res = ActOnFinishFullExpr(Expr: Res.get(), /*DiscardedValue=*/false);
832 if (Res.isInvalid())
833 return ExprError();
834
835 Assumption = Res.get();
836 if (Assumption->HasSideEffects(Ctx: Context))
837 Diag(Loc: Assumption->getBeginLoc(), DiagID: diag::warn_assume_side_effects)
838 << AttrName << Range;
839
840 return Assumption;
841}
842