clang 24.0.0git
SemaStmtAttr.cpp
Go to the documentation of this file.
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
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>(St)) {
28 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target)
29 << A << St->getBeginLoc();
30 SourceLocation L = S.getLocForEndOfToken(Range.getEnd());
31 S.Diag(L, diag::note_fallthrough_insert_semi_fixit)
33 return nullptr;
34 }
35 auto *FnScope = S.getCurFunction();
36 if (FnScope->SwitchStack.empty()) {
37 S.Diag(A.getRange().getBegin(), 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(A.getLoc(), 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(A.getLoc(), 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(A.getLoc(), 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(A, I, RuleName, nullptr))
77 return nullptr;
78
79 DiagnosticIdentifiers.push_back(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,
88 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
89 IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
90 IdentifierLoc *StateLoc = A.getArgAsIdent(2);
91 Expr *ValueExpr = A.getArgAsExpr(3);
92
93 StringRef PragmaName =
94 llvm::StringSwitch<StringRef>(
95 PragmaNameLoc->getIdentifierInfo()->getName())
96 .Cases({"unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam"},
97 PragmaNameLoc->getIdentifierInfo()->getName())
98 .Default("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.
104 std::string Pragma = "#pragma " + std::string(PragmaName);
105 S.Diag(St->getBeginLoc(), 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(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("vectorize", LoopHintAttr::Vectorize)
148 .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
149 .Case("interleave", LoopHintAttr::Interleave)
150 .Case("vectorize_predicate", LoopHintAttr::VectorizePredicate)
151 .Case("interleave_count", LoopHintAttr::InterleaveCount)
152 .Case("unroll", LoopHintAttr::Unroll)
153 .Case("unroll_count", LoopHintAttr::UnrollCount)
154 .Case("pipeline", LoopHintAttr::PipelineDisabled)
155 .Case("pipeline_initiation_interval",
156 LoopHintAttr::PipelineInitiationInterval)
157 .Case("distribute", LoopHintAttr::Distribute)
158 .Case("licm", LoopHintAttr::LICMDisabled)
159 .Default(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(ValueExpr, St->getBeginLoc(),
164 /*AllowZero=*/false))
165 return nullptr;
166 if (StateLoc && StateLoc->getIdentifierInfo() &&
167 StateLoc->getIdentifierInfo()->isStr("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(ValueExpr, 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("disable"))
189 State = LoopHintAttr::Disable;
190 else if (StateLoc->getIdentifierInfo()->isStr("assume_safety"))
191 State = LoopHintAttr::AssumeSafety;
192 else if (StateLoc->getIdentifierInfo()->isStr("full"))
193 State = LoopHintAttr::Full;
194 else if (StateLoc->getIdentifierInfo()->isStr("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(S.Context, Option, State, ValueExpr, 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(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(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(St->getBeginLoc(), 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
246 SourceRange Range) {
247 CallExprFinder CEF(S, St);
248
249 if (!CEF.foundCallExpr() && !CEF.foundAsmStmt()) {
250 S.Diag(St->getBeginLoc(), 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(CurSt->getBeginLoc(),
277 diag::warn_attribute_ignored_no_calls_in_stmt)
278 << A;
279 }
280
281 for (const auto &Tup :
282 llvm::zip_longest(OrigCEF.getCallExprs(), 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>(Tup))->getCalleeDecl()) {
287 const Decl *Callee = (*std::get<1>(Tup))->getCalleeDecl();
288 if (Callee &&
289 (Callee->hasAttr<OtherAttr>() || Callee->hasAttr<FlattenAttr>())) {
290 SemaRef.Diag(CurSt->getBeginLoc(),
291 diag::warn_function_stmt_attribute_precedence)
292 << A << (Callee->hasAttr<OtherAttr>() ? DiagIdx : 1);
293 SemaRef.Diag(Callee->getBeginLoc(), 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>(*this, OrigSt, CurSt, A);
304}
305
306bool Sema::CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
307 const AttributeCommonInfo &A) {
308 return CheckStmtInlineAttr<NoInlineAttr, 2>(*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(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
316 << "[[clang::noinline]]";
317 return nullptr;
318 }
319
320 if (S.CheckNoInlineAttr(/*OrigSt=*/nullptr, St, A))
321 return nullptr;
322
323 return ::new (S.Context) NoInlineAttr(S.Context, A);
324}
325
327 SourceRange Range) {
328 AlwaysInlineAttr AIA(S.Context, A);
329 if (!S.getLangOpts().MicrosoftExt &&
330 (AIA.isMSVCForceInline() || AIA.isMSVCForceInlineCalls())) {
331 S.Diag(St->getBeginLoc(), diag::warn_attribute_ignored) << A;
332 return nullptr;
333 }
334 if (AIA.isMSVCForceInline()) {
335 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
336 << "[[msvc::forceinline_calls]]";
337 return nullptr;
338 }
339 if (!AIA.isClangAlwaysInline() && !AIA.isMSVCForceInlineCalls()) {
340 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
341 << "[[clang::always_inline]]";
342 return nullptr;
343 }
344
345 if (S.CheckAlwaysInlineAttr(/*OrigSt=*/nullptr, 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(A.getLoc(), 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(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
380
381 return ::new (S.Context) UnlikelyAttr(S.Context, A);
382}
383
385 Expr *E) {
386 if (!E->isValueDependent()) {
387 llvm::APSInt 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(CI.getLoc(), diag::err_attribute_power_of_two_in_range)
399 << CI << CodeAlignAttr::MinimumAlignment
400 << CodeAlignAttr::MaximumAlignment << Value.value();
401 else
402 Diag(CI.getLoc(), 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(0);
414 return S.BuildCodeAlignAttr(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>
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(*FirstValue, 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
459 SourceRange Range) {
461 S.Diag(A.getLoc(), 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
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, 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>(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
577 SourceLocation OptionLoc = LH->getRange().getBegin();
578 if (PrevAttr)
579 // Cannot specify same type of attribute twice.
580 S.Diag(OptionLoc, 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(OptionLoc, diag::err_pragma_loop_compatibility)
592 << /*Duplicate=*/false
593 << CategoryState.StateAttr->getDiagnosticName(Policy)
594 << CategoryState.NumericAttr->getDiagnosticName(Policy);
595 }
596 }
597}
598
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(0);
609 std::optional<llvm::APSInt> ArgVal;
610
611 if (!(ArgVal = E->getIntegerConstantExpr(S.Context))) {
612 S.Diag(A.getLoc(), diag::err_attribute_argument_type)
614 return nullptr;
615 }
616
617 int Val = ArgVal->getSExtValue();
618 if (Val <= 0) {
619 S.Diag(A.getRange().getBegin(),
620 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
631 SourceRange Range) {
632
633 if (A.getSemanticSpelling() == HLSLLoopHintAttr::Spelling::Microsoft_loop &&
634 !A.checkAtMostNumArgs(S, 0))
635 return nullptr;
636
637 unsigned UnrollFactor = 0;
638 if (A.getNumArgs() == 1) {
639 Expr *E = A.getArgAsExpr(0);
640
641 if (S.CheckLoopHintExpr(E, St->getBeginLoc(),
642 /*AllowZero=*/false))
643 return nullptr;
644
645 std::optional<llvm::APSInt> ArgVal = E->getIntegerConstantExpr(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
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, 1))
665 return nullptr;
666
668 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
669 AtomicAttr::ConsumedOption Option;
670 StringRef OptionString;
671 SourceLocation Loc;
672
673 if (!AL.isArgIdent(ArgIndex)) {
674 S.Diag(AL.getArgAsExpr(ArgIndex)->getBeginLoc(),
675 diag::err_attribute_argument_type)
677 return nullptr;
678 }
679
680 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
681 OptionString = Ident->getIdentifierInfo()->getName();
682 Loc = Ident->getLoc();
683 if (!AtomicAttr::ConvertStrToConsumedOption(OptionString, Option)) {
684 S.Diag(Loc, diag::err_attribute_invalid_atomic_argument) << OptionString;
685 return nullptr;
686 }
687 Options.push_back(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) {
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();
705 (S.Context.getLangOpts().SYCLIsDevice && Aux &&
706 A.existsInTarget(*Aux)))) {
708 S.Diag(A.getLoc(), diag::err_keyword_not_supported_on_target)
709 << A << A.getRange();
710 } else if (A.isDeclspecAttribute()) {
711 S.Diag(A.getLoc(), diag::warn_unhandled_ms_attribute_ignored)
712 << A << A.getRange();
713 } else {
715 }
716 return nullptr;
717 }
718
719 if (S.checkCommonAttributeFeatures(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(A);
757 case ParsedAttr::AT_Atomic:
758 return handleAtomicAttr(S, St, A, Range);
759 default:
760 if (Attr *AT = nullptr; A.getInfo().handleStmtAttribute(S, St, A, AT) !=
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(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
768 << A << A.isRegularKeywordAttribute() << St->getBeginLoc();
769 return nullptr;
770 }
771}
772
775 for (const ParsedAttr &AL : InAttrs) {
776 if (const Attr *A = ProcessStmtAttribute(*this, S, AL, InAttrs.Range))
777 OutAttrs.push_back(A);
778 }
779
780 CheckForIncompatibleAttributes(*this, OutAttrs);
782}
783
788
790 SourceRange Range) {
791 if (A.getNumArgs() != 1 || !A.getArgAsExpr(0)) {
792 Diag(A.getLoc(), diag::err_attribute_wrong_number_arguments)
793 << A.getAttrName() << 1 << Range;
794 return ExprError();
795 }
796
797 auto *Assumption = A.getArgAsExpr(0);
798
799 if (DiagnoseUnexpandedParameterPack(Assumption)) {
800 return ExprError();
801 }
802
803 if (Assumption->getDependence() == ExprDependence::None) {
804 ExprResult Res = BuildCXXAssumeExpr(Assumption, A.getAttrName(), Range);
805 if (Res.isInvalid())
806 return ExprError();
807 Assumption = Res.get();
808 }
809
810 if (!getLangOpts().CPlusPlus23 &&
812 Diag(A.getLoc(), diag::ext_cxx23_attr) << A << Range;
813
814 return Assumption;
815}
816
818 const IdentifierInfo *AttrName,
819 SourceRange Range) {
820 if (!Assumption)
821 return ExprError();
822
823 ExprResult Res = CheckPlaceholderExpr(Assumption);
824 if (Res.isInvalid())
825 return ExprError();
826
828 if (Res.isInvalid())
829 return ExprError();
830
831 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
832 if (Res.isInvalid())
833 return ExprError();
834
835 Assumption = Res.get();
836 if (Assumption->HasSideEffects(Context))
837 Diag(Assumption->getBeginLoc(), diag::warn_assume_side_effects)
838 << AttrName << Range;
839
840 return Assumption;
841}
Defines the clang::ASTContext interface.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static void handleNoMergeAttr(Sema &S, Decl *D, const ParsedAttr &AL)
static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL)
static void handleMSConstexprAttr(Sema &S, Decl *D, const ParsedAttr &AL)
static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL)
static Attr * handleNoConvergentAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static void CheckForDuplicateLoopAttrs(Sema &S, ArrayRef< const Attr * > Attrs)
static Attr * handleMustTailAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleCXXAssumeAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleLikely(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange)
static Attr * handleAtomicAttr(Sema &S, Stmt *St, const ParsedAttr &AL, SourceRange Range)
static void CheckForIncompatibleAttributes(Sema &S, const SmallVectorImpl< const Attr * > &Attrs)
static Attr * handleHLSLControlFlowHint(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static bool CheckStmtInlineAttr(Sema &SemaRef, const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
static Attr * handleHLSLLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleCodeAlignAttr(Sema &S, Stmt *St, const ParsedAttr &A)
static Attr * handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleNoInlineAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
const LangOptions & getLangOpts() const
Definition ASTContext.h:965
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:928
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:927
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Attr - This represents one attribute.
Definition Attr.h:46
unsigned getAttributeSpellingListIndex() const
const IdentifierInfo * getScopeName() const
SourceLocation getLoc() const
const IdentifierInfo * getAttrName() const
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:112
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3699
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:105
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
A simple pair of identifier info and location.
SourceLocation getLoc() const
IdentifierInfo * getIdentifierInfo() const
bool isCompatibleWithMSVC() const
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
unsigned getSemanticSpelling() const
If the parsed attribute has a semantic equivalent, and it would have a semantic Spelling enumeration ...
bool existsInTarget(const TargetInfo &Target) const
IdentifierLoc * getArgAsIdent(unsigned Arg) const
Definition ParsedAttr.h:389
const ParsedAttrInfo & getInfo() const
Definition ParsedAttr.h:613
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition ParsedAttr.h:371
bool isArgIdent(unsigned Arg) const
Definition ParsedAttr.h:385
Expr * getArgAsExpr(unsigned Arg) const
Definition ParsedAttr.h:383
bool checkAtLeastNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at least as many args as Num.
AttributeCommonInfo::Kind getKind() const
Definition ParsedAttr.h:610
bool isInvalid() const
Definition ParsedAttr.h:344
bool checkAtMostNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at most as many args as Num.
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:937
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isFunctionScope() const
isFunctionScope() - Return true if this scope is a function scope.
Definition Scope.h:411
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1142
void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs, SmallVectorImpl< const Attr * > &OutAttrs)
Process the attributes before creating an attributed statement.
bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A, bool SkipArgCountCheck=false)
Handles semantic checking for features that are common to all attributes, such as checking whether a ...
ExprResult BuildCXXAssumeExpr(Expr *Assumption, const IdentifierInfo *AttrName, SourceRange Range)
ASTContext & Context
Definition Sema.h:1309
ASTContext & getASTContext() const
Definition Sema.h:940
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
const LangOptions & getLangOpts() const
Definition Sema.h:933
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1342
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
bool CheckRebuiltStmtAttributes(ArrayRef< const Attr * > Attrs)
bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
void DiagnoseUnknownAttribute(const ParsedAttr &AL)
ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A, SourceRange Range)
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Attr * CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
Definition Sema.cpp:3072
CodeAlignAttr * BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E)
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8748
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Exposes information about the current target.
Definition TargetInfo.h:227
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus23
@ AANT_ArgumentIntegerConstant
@ AANT_ArgumentIdentifier
ExprResult ExprError()
Definition Ownership.h:265
U cast(CodeGen::Address addr)
Definition Address.h:327
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
Describes how types, statements, expressions, and declarations should be printed.