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