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
366/// Return true if E is an atomic expression or a fence.
367static bool isAtomicExprOrFence(const Expr *E) {
368 E = E->IgnoreParenCasts();
369
370 if (isa<AtomicExpr>(Val: E))
371 return true;
372
373 // _Atomic type qualifier operations: assignments and compound assignments
374 // to atomic lvalues, and loads from atomic lvalues.
375 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
376 if (BO->getLHS()->getType()->isAtomicType())
377 return true;
378 } else if (E->getType()->isAtomicType()) {
379 return true;
380 }
381
382 // Target-independent fence builtins.
383 if (const auto *CE = dyn_cast<CallExpr>(Val: E)) {
384 switch (CE->getBuiltinCallee()) {
385 case Builtin::BI__c11_atomic_thread_fence:
386 case Builtin::BI__c11_atomic_signal_fence:
387 case Builtin::BI__atomic_thread_fence:
388 case Builtin::BI__atomic_signal_fence:
389 case Builtin::BI__scoped_atomic_thread_fence:
390 return true;
391 default:
392 break;
393 }
394 }
395
396 return false;
397}
398
399static Attr *handleAMDGPUAvailableVisibleAttr(Sema &S, Stmt *St,
400 const ParsedAttr &A,
401 SourceRange Range) {
402 StringRef Mode;
403 if (!S.checkStringLiteralArgumentAttr(Attr: A, ArgNum: 0, Str&: Mode))
404 return nullptr;
405
406 if (Mode != "none") {
407 S.Diag(Loc: A.getLoc(), DiagID: diag::warn_attribute_type_not_supported) << A << Mode;
408 return nullptr;
409 }
410
411 if (const auto *E = dyn_cast<Expr>(Val: St)) {
412 if (!isAtomicExprOrFence(E)) {
413 S.Diag(Loc: A.getLoc(), DiagID: diag::warn_amdgpu_av_requires_atomic) << A;
414 return nullptr;
415 }
416 } else {
417 S.Diag(Loc: A.getLoc(), DiagID: diag::warn_amdgpu_av_requires_expr) << A;
418 return nullptr;
419 }
420
421 return ::new (S.Context) AMDGPUAvailableVisibleAttr(S.Context, A, Mode);
422}
423
424static Attr *handleLikely(Sema &S, Stmt *St, const ParsedAttr &A,
425 SourceRange Range) {
426
427 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
428 S.Diag(Loc: A.getLoc(), DiagID: diag::ext_cxx20_attr) << A << Range;
429
430 return ::new (S.Context) LikelyAttr(S.Context, A);
431}
432
433static Attr *handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A,
434 SourceRange Range) {
435
436 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
437 S.Diag(Loc: A.getLoc(), DiagID: diag::ext_cxx20_attr) << A << Range;
438
439 return ::new (S.Context) UnlikelyAttr(S.Context, A);
440}
441
442CodeAlignAttr *Sema::BuildCodeAlignAttr(const AttributeCommonInfo &CI,
443 Expr *E) {
444 if (!E->isValueDependent()) {
445 llvm::APSInt ArgVal;
446 ExprResult Res = VerifyIntegerConstantExpression(E, Result: &ArgVal);
447 if (Res.isInvalid())
448 return nullptr;
449 E = Res.get();
450
451 // This attribute requires an integer argument which is a constant power of
452 // two between 1 and 4096 inclusive.
453 if (ArgVal < CodeAlignAttr::MinimumAlignment ||
454 ArgVal > CodeAlignAttr::MaximumAlignment || !ArgVal.isPowerOf2()) {
455 if (std::optional<int64_t> Value = ArgVal.trySExtValue())
456 Diag(Loc: CI.getLoc(), DiagID: diag::err_attribute_power_of_two_in_range)
457 << CI << CodeAlignAttr::MinimumAlignment
458 << CodeAlignAttr::MaximumAlignment << Value.value();
459 else
460 Diag(Loc: CI.getLoc(), DiagID: diag::err_attribute_power_of_two_in_range)
461 << CI << CodeAlignAttr::MinimumAlignment
462 << CodeAlignAttr::MaximumAlignment << E;
463 return nullptr;
464 }
465 }
466 return new (Context) CodeAlignAttr(Context, CI, E);
467}
468
469static Attr *handleCodeAlignAttr(Sema &S, Stmt *St, const ParsedAttr &A) {
470
471 Expr *E = A.getArgAsExpr(Arg: 0);
472 return S.BuildCodeAlignAttr(CI: A, E);
473}
474
475// Diagnose non-identical duplicates as a 'conflicting' loop attributes
476// and suppress duplicate errors in cases where the two match.
477template <typename LoopAttrT>
478static void CheckForDuplicateLoopAttrs(Sema &S, ArrayRef<const Attr *> Attrs) {
479 auto FindFunc = [](const Attr *A) { return isa<const LoopAttrT>(A); };
480 const auto *FirstItr = llvm::find_if(Attrs, FindFunc);
481
482 if (FirstItr == Attrs.end()) // no attributes found
483 return;
484
485 const auto *LastFoundItr = FirstItr;
486 std::optional<llvm::APSInt> FirstValue;
487
488 const auto *CAFA =
489 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*FirstItr)->getAlignment());
490 // Return early if first alignment expression is dependent (since we don't
491 // know what the effective size will be), and skip the loop entirely.
492 if (!CAFA)
493 return;
494
495 while (Attrs.end() != (LastFoundItr = std::find_if(LastFoundItr + 1,
496 Attrs.end(), FindFunc))) {
497 const auto *CASA =
498 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*LastFoundItr)->getAlignment());
499 // If the value is dependent, we can not test anything.
500 if (!CASA)
501 return;
502 // Test the attribute values.
503 llvm::APSInt SecondValue = CASA->getResultAsAPSInt();
504 if (!FirstValue)
505 FirstValue = CAFA->getResultAsAPSInt();
506
507 if (llvm::APSInt::isSameValue(I1: *FirstValue, I2: SecondValue))
508 continue;
509
510 S.Diag((*LastFoundItr)->getLocation(), diag::err_loop_attr_conflict)
511 << *FirstItr;
512 S.Diag((*FirstItr)->getLocation(), diag::note_previous_attribute);
513 }
514}
515
516static Attr *handleMSConstexprAttr(Sema &S, Stmt *St, const ParsedAttr &A,
517 SourceRange Range) {
518 if (!S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2022_3)) {
519 S.Diag(Loc: A.getLoc(), DiagID: diag::warn_unknown_attribute_ignored)
520 << A << A.getRange();
521 return nullptr;
522 }
523 return ::new (S.Context) MSConstexprAttr(S.Context, A);
524}
525
526#define WANT_STMT_MERGE_LOGIC
527#include "clang/Sema/AttrParsedAttrImpl.inc"
528#undef WANT_STMT_MERGE_LOGIC
529
530static void
531CheckForIncompatibleAttributes(Sema &S,
532 const SmallVectorImpl<const Attr *> &Attrs) {
533 // The vast majority of attributed statements will only have one attribute
534 // on them, so skip all of the checking in the common case.
535 if (Attrs.size() < 2)
536 return;
537
538 // First, check for the easy cases that are table-generated for us.
539 if (!DiagnoseMutualExclusions(S, C: Attrs))
540 return;
541
542 enum CategoryType {
543 // For the following categories, they come in two variants: a state form and
544 // a numeric form. The state form may be one of default, enable, and
545 // disable. The numeric form provides an integer hint (for example, unroll
546 // count) to the transformer.
547 Vectorize,
548 Interleave,
549 UnrollAndJam,
550 Pipeline,
551 // For unroll, default indicates full unrolling rather than enabling the
552 // transformation.
553 Unroll,
554 // The loop distribution transformation only has a state form that is
555 // exposed by #pragma clang loop distribute (enable | disable).
556 Distribute,
557 // The vector predication only has a state form that is exposed by
558 // #pragma clang loop vectorize_predicate (enable | disable).
559 VectorizePredicate,
560 // The LICM transformation only has a disable state form that is
561 // exposed by #pragma clang loop licm(disable).
562 LICM,
563 // This serves as a indicator to how many category are listed in this enum.
564 NumberOfCategories
565 };
566 // The following array accumulates the hints encountered while iterating
567 // through the attributes to check for compatibility.
568 struct {
569 const LoopHintAttr *StateAttr;
570 const LoopHintAttr *NumericAttr;
571 } HintAttrs[CategoryType::NumberOfCategories] = {};
572
573 for (const auto *I : Attrs) {
574 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(Val: I);
575
576 // Skip non loop hint attributes
577 if (!LH)
578 continue;
579
580 CategoryType Category = CategoryType::NumberOfCategories;
581 LoopHintAttr::OptionType Option = LH->getOption();
582 switch (Option) {
583 case LoopHintAttr::Vectorize:
584 case LoopHintAttr::VectorizeWidth:
585 Category = Vectorize;
586 break;
587 case LoopHintAttr::Interleave:
588 case LoopHintAttr::InterleaveCount:
589 Category = Interleave;
590 break;
591 case LoopHintAttr::Unroll:
592 case LoopHintAttr::UnrollCount:
593 Category = Unroll;
594 break;
595 case LoopHintAttr::UnrollAndJam:
596 case LoopHintAttr::UnrollAndJamCount:
597 Category = UnrollAndJam;
598 break;
599 case LoopHintAttr::Distribute:
600 // Perform the check for duplicated 'distribute' hints.
601 Category = Distribute;
602 break;
603 case LoopHintAttr::PipelineDisabled:
604 case LoopHintAttr::PipelineInitiationInterval:
605 Category = Pipeline;
606 break;
607 case LoopHintAttr::VectorizePredicate:
608 Category = VectorizePredicate;
609 break;
610 case LoopHintAttr::LICMDisabled:
611 Category = LICM;
612 break;
613 };
614
615 assert(Category != NumberOfCategories && "Unhandled loop hint option");
616 auto &CategoryState = HintAttrs[Category];
617 const LoopHintAttr *PrevAttr;
618 if (Option == LoopHintAttr::Vectorize ||
619 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll ||
620 Option == LoopHintAttr::UnrollAndJam ||
621 Option == LoopHintAttr::VectorizePredicate ||
622 Option == LoopHintAttr::PipelineDisabled ||
623 Option == LoopHintAttr::LICMDisabled ||
624 Option == LoopHintAttr::Distribute) {
625 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable).
626 PrevAttr = CategoryState.StateAttr;
627 CategoryState.StateAttr = LH;
628 } else {
629 // Numeric hint. For example, vectorize_width(8).
630 PrevAttr = CategoryState.NumericAttr;
631 CategoryState.NumericAttr = LH;
632 }
633
634 PrintingPolicy Policy(S.Context.getLangOpts());
635 SourceLocation OptionLoc = LH->getRange().getBegin();
636 if (PrevAttr)
637 // Cannot specify same type of attribute twice.
638 S.Diag(Loc: OptionLoc, DiagID: diag::err_pragma_loop_compatibility)
639 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
640 << LH->getDiagnosticName(Policy);
641
642 if (CategoryState.StateAttr && CategoryState.NumericAttr &&
643 (Category == Unroll || Category == UnrollAndJam ||
644 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
645 // Disable hints are not compatible with numeric hints of the same
646 // category. As a special case, numeric unroll hints are also not
647 // compatible with enable or full form of the unroll pragma because these
648 // directives indicate full unrolling.
649 S.Diag(Loc: OptionLoc, DiagID: diag::err_pragma_loop_compatibility)
650 << /*Duplicate=*/false
651 << CategoryState.StateAttr->getDiagnosticName(Policy)
652 << CategoryState.NumericAttr->getDiagnosticName(Policy);
653 }
654 }
655}
656
657static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A,
658 SourceRange Range) {
659 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
660 // useful for OpenCL 1.x too and doesn't require HW support.
661 // opencl_unroll_hint can have 0 arguments (compiler
662 // determines unrolling factor) or 1 argument (the unroll factor provided
663 // by the user).
664 unsigned UnrollFactor = 0;
665 if (A.getNumArgs() == 1) {
666 Expr *E = A.getArgAsExpr(Arg: 0);
667 std::optional<llvm::APSInt> ArgVal;
668
669 if (!(ArgVal = E->getIntegerConstantExpr(Ctx: S.Context))) {
670 S.Diag(Loc: A.getLoc(), DiagID: diag::err_attribute_argument_type)
671 << A << AANT_ArgumentIntegerConstant << E->getSourceRange();
672 return nullptr;
673 }
674
675 int Val = ArgVal->getSExtValue();
676 if (Val <= 0) {
677 S.Diag(Loc: A.getRange().getBegin(),
678 DiagID: diag::err_attribute_requires_positive_integer)
679 << A << /* positive */ 0;
680 return nullptr;
681 }
682 UnrollFactor = static_cast<unsigned>(Val);
683 }
684
685 return ::new (S.Context) OpenCLUnrollHintAttr(S.Context, A, UnrollFactor);
686}
687
688static Attr *handleHLSLLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
689 SourceRange Range) {
690
691 if (A.getSemanticSpelling() == HLSLLoopHintAttr::Spelling::Microsoft_loop &&
692 !A.checkAtMostNumArgs(S, Num: 0))
693 return nullptr;
694
695 unsigned UnrollFactor = 0;
696 if (A.getNumArgs() == 1) {
697 Expr *E = A.getArgAsExpr(Arg: 0);
698
699 if (S.CheckLoopHintExpr(E, Loc: St->getBeginLoc(),
700 /*AllowZero=*/false))
701 return nullptr;
702
703 std::optional<llvm::APSInt> ArgVal = E->getIntegerConstantExpr(Ctx: S.Context);
704 // CheckLoopHintExpr handles non int const cases
705 assert(ArgVal != std::nullopt && "ArgVal should be an integer constant.");
706 int Val = ArgVal->getSExtValue();
707 // CheckLoopHintExpr handles negative and zero cases
708 assert(Val > 0 && "Val should be a positive integer greater than zero.");
709 UnrollFactor = static_cast<unsigned>(Val);
710 }
711 return ::new (S.Context) HLSLLoopHintAttr(S.Context, A, UnrollFactor);
712}
713
714static Attr *handleHLSLControlFlowHint(Sema &S, Stmt *St, const ParsedAttr &A,
715 SourceRange Range) {
716
717 return ::new (S.Context) HLSLControlFlowHintAttr(S.Context, A);
718}
719
720static Attr *handleAtomicAttr(Sema &S, Stmt *St, const ParsedAttr &AL,
721 SourceRange Range) {
722 if (!AL.checkAtLeastNumArgs(S, Num: 1))
723 return nullptr;
724
725 SmallVector<AtomicAttr::ConsumedOption, 6> Options;
726 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
727 AtomicAttr::ConsumedOption Option;
728 StringRef OptionString;
729 SourceLocation Loc;
730
731 if (!AL.isArgIdent(Arg: ArgIndex)) {
732 S.Diag(Loc: AL.getArgAsExpr(Arg: ArgIndex)->getBeginLoc(),
733 DiagID: diag::err_attribute_argument_type)
734 << AL << AANT_ArgumentIdentifier;
735 return nullptr;
736 }
737
738 IdentifierLoc *Ident = AL.getArgAsIdent(Arg: ArgIndex);
739 OptionString = Ident->getIdentifierInfo()->getName();
740 Loc = Ident->getLoc();
741 if (!AtomicAttr::ConvertStrToConsumedOption(Val: OptionString, Out&: Option)) {
742 S.Diag(Loc, DiagID: diag::err_attribute_invalid_atomic_argument) << OptionString;
743 return nullptr;
744 }
745 Options.push_back(Elt: Option);
746 }
747
748 return ::new (S.Context)
749 AtomicAttr(S.Context, AL, Options.data(), Options.size());
750}
751
752static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
753 SourceRange Range) {
754 if (A.isInvalid() || A.getKind() == ParsedAttr::IgnoredAttribute)
755 return nullptr;
756
757 // Unknown attributes are automatically warned on. Target-specific attributes
758 // which do not apply to the current target architecture are treated as
759 // though they were unknown attributes.
760 const TargetInfo *Aux = S.Context.getAuxTargetInfo();
761 if (A.getKind() == ParsedAttr::UnknownAttribute ||
762 !(A.existsInTarget(Target: S.Context.getTargetInfo()) ||
763 (S.Context.getLangOpts().SYCLIsDevice && Aux &&
764 A.existsInTarget(Target: *Aux)))) {
765 if (A.isRegularKeywordAttribute()) {
766 S.Diag(Loc: A.getLoc(), DiagID: diag::err_keyword_not_supported_on_target)
767 << A << A.getRange();
768 } else if (A.isDeclspecAttribute()) {
769 S.Diag(Loc: A.getLoc(), DiagID: diag::warn_unhandled_ms_attribute_ignored)
770 << A << A.getRange();
771 } else {
772 S.DiagnoseUnknownAttribute(AL: A);
773 }
774 return nullptr;
775 }
776
777 if (S.checkCommonAttributeFeatures(S: St, A))
778 return nullptr;
779
780 switch (A.getKind()) {
781 case ParsedAttr::AT_AlwaysInline:
782 return handleAlwaysInlineAttr(S, St, A, Range);
783 case ParsedAttr::AT_CXXAssume:
784 return handleCXXAssumeAttr(S, St, A, Range);
785 case ParsedAttr::AT_FallThrough:
786 return handleFallThroughAttr(S, St, A, Range);
787 case ParsedAttr::AT_LoopHint:
788 return handleLoopHintAttr(S, St, A, Range);
789 case ParsedAttr::AT_HLSLLoopHint:
790 return handleHLSLLoopHintAttr(S, St, A, Range);
791 case ParsedAttr::AT_HLSLControlFlowHint:
792 return handleHLSLControlFlowHint(S, St, A, Range);
793 case ParsedAttr::AT_OpenCLUnrollHint:
794 return handleOpenCLUnrollHint(S, St, A, Range);
795 case ParsedAttr::AT_Suppress:
796 return handleSuppressAttr(S, St, A, Range);
797 case ParsedAttr::AT_NoMerge:
798 return handleNoMergeAttr(S, St, A, Range);
799 case ParsedAttr::AT_NoInline:
800 return handleNoInlineAttr(S, St, A, Range);
801 case ParsedAttr::AT_MustTail:
802 return handleMustTailAttr(S, St, A, Range);
803 case ParsedAttr::AT_AMDGPUAvailableVisible:
804 return handleAMDGPUAvailableVisibleAttr(S, St, A, Range);
805 case ParsedAttr::AT_Likely:
806 return handleLikely(S, St, A, Range);
807 case ParsedAttr::AT_Unlikely:
808 return handleUnlikely(S, St, A, Range);
809 case ParsedAttr::AT_CodeAlign:
810 return handleCodeAlignAttr(S, St, A);
811 case ParsedAttr::AT_MSConstexpr:
812 return handleMSConstexprAttr(S, St, A, Range);
813 case ParsedAttr::AT_NoConvergent:
814 return handleNoConvergentAttr(S, St, A, Range);
815 case ParsedAttr::AT_Annotate:
816 return S.CreateAnnotationAttr(AL: A);
817 case ParsedAttr::AT_Atomic:
818 return handleAtomicAttr(S, St, AL: A, Range);
819 default:
820 if (Attr *AT = nullptr; A.getInfo().handleStmtAttribute(S, St, Attr: A, Result&: AT) !=
821 ParsedAttrInfo::NotHandled) {
822 return AT;
823 }
824 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
825 // declaration attribute is not written on a statement, but this code is
826 // needed for attributes in Attr.td that do not list any subjects.
827 S.Diag(Loc: A.getRange().getBegin(), DiagID: diag::err_decl_attribute_invalid_on_stmt)
828 << A << A.isRegularKeywordAttribute() << St->getBeginLoc();
829 return nullptr;
830 }
831}
832
833void Sema::ProcessStmtAttributes(Stmt *S, const ParsedAttributes &InAttrs,
834 SmallVectorImpl<const Attr *> &OutAttrs) {
835 for (const ParsedAttr &AL : InAttrs) {
836 if (const Attr *A = ProcessStmtAttribute(S&: *this, St: S, A: AL, Range: InAttrs.Range))
837 OutAttrs.push_back(Elt: A);
838 }
839
840 CheckForIncompatibleAttributes(S&: *this, Attrs: OutAttrs);
841 CheckForDuplicateLoopAttrs<CodeAlignAttr>(S&: *this, Attrs: OutAttrs);
842}
843
844bool Sema::CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs) {
845 CheckForDuplicateLoopAttrs<CodeAlignAttr>(S&: *this, Attrs);
846 return false;
847}
848
849ExprResult Sema::ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A,
850 SourceRange Range) {
851 if (A.getNumArgs() != 1 || !A.getArgAsExpr(Arg: 0)) {
852 Diag(Loc: A.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments)
853 << A.getAttrName() << 1 << Range;
854 return ExprError();
855 }
856
857 auto *Assumption = A.getArgAsExpr(Arg: 0);
858
859 if (DiagnoseUnexpandedParameterPack(E: Assumption)) {
860 return ExprError();
861 }
862
863 if (Assumption->getDependence() == ExprDependence::None) {
864 ExprResult Res = BuildCXXAssumeExpr(Assumption, AttrName: A.getAttrName(), Range);
865 if (Res.isInvalid())
866 return ExprError();
867 Assumption = Res.get();
868 }
869
870 if (!getLangOpts().CPlusPlus23 &&
871 A.getSyntax() == AttributeCommonInfo::AS_CXX11)
872 Diag(Loc: A.getLoc(), DiagID: diag::ext_cxx23_attr) << A << Range;
873
874 return Assumption;
875}
876
877ExprResult Sema::BuildCXXAssumeExpr(Expr *Assumption,
878 const IdentifierInfo *AttrName,
879 SourceRange Range) {
880 if (!Assumption)
881 return ExprError();
882
883 ExprResult Res = CheckPlaceholderExpr(E: Assumption);
884 if (Res.isInvalid())
885 return ExprError();
886
887 Res = PerformContextuallyConvertToBool(From: Res.get());
888 if (Res.isInvalid())
889 return ExprError();
890
891 Res = ActOnFinishFullExpr(Expr: Res.get(), /*DiscardedValue=*/false);
892 if (Res.isInvalid())
893 return ExprError();
894
895 Assumption = Res.get();
896 if (Assumption->HasSideEffects(Ctx: Context))
897 Diag(Loc: Assumption->getBeginLoc(), DiagID: diag::warn_assume_side_effects)
898 << AttrName << Range;
899
900 return Assumption;
901}
902