clang 19.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
18#include "clang/Sema/Lookup.h"
21#include "llvm/ADT/StringExtras.h"
22#include <optional>
23
24using namespace clang;
25using namespace sema;
26
27static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A,
28 SourceRange Range) {
29 FallThroughAttr Attr(S.Context, A);
30 if (isa<SwitchCase>(St)) {
31 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target)
32 << A << St->getBeginLoc();
33 SourceLocation L = S.getLocForEndOfToken(Range.getEnd());
34 S.Diag(L, diag::note_fallthrough_insert_semi_fixit)
36 return nullptr;
37 }
38 auto *FnScope = S.getCurFunction();
39 if (FnScope->SwitchStack.empty()) {
40 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch);
41 return nullptr;
42 }
43
44 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
45 // about using it as an extension.
46 if (!S.getLangOpts().CPlusPlus17 && A.isCXX11Attribute() &&
47 !A.getScopeName())
48 S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A;
49
50 FnScope->setHasFallthroughStmt();
51 return ::new (S.Context) FallThroughAttr(S.Context, A);
52}
53
54static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A,
55 SourceRange Range) {
56 if (A.getAttributeSpellingListIndex() == SuppressAttr::CXX11_gsl_suppress &&
57 A.getNumArgs() < 1) {
58 // Suppression attribute with GSL spelling requires at least 1 argument.
59 S.Diag(A.getLoc(), diag::err_attribute_too_few_arguments) << A << 1;
60 return nullptr;
61 }
62
63 std::vector<StringRef> DiagnosticIdentifiers;
64 for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) {
65 StringRef RuleName;
66
67 if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr))
68 return nullptr;
69
70 DiagnosticIdentifiers.push_back(RuleName);
71 }
72
73 return ::new (S.Context) SuppressAttr(
74 S.Context, A, DiagnosticIdentifiers.data(), DiagnosticIdentifiers.size());
75}
76
77static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A,
79 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
80 IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
81 IdentifierLoc *StateLoc = A.getArgAsIdent(2);
82 Expr *ValueExpr = A.getArgAsExpr(3);
83
84 StringRef PragmaName =
85 llvm::StringSwitch<StringRef>(PragmaNameLoc->Ident->getName())
86 .Cases("unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam",
87 PragmaNameLoc->Ident->getName())
88 .Default("clang loop");
89
90 // This could be handled automatically by adding a Subjects definition in
91 // Attr.td, but that would make the diagnostic behavior worse in this case
92 // because the user spells this attribute as a pragma.
93 if (!isa<DoStmt, ForStmt, CXXForRangeStmt, WhileStmt>(St)) {
94 std::string Pragma = "#pragma " + std::string(PragmaName);
95 S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma;
96 return nullptr;
97 }
98
99 LoopHintAttr::OptionType Option;
100 LoopHintAttr::LoopHintState State;
101
102 auto SetHints = [&Option, &State](LoopHintAttr::OptionType O,
103 LoopHintAttr::LoopHintState S) {
104 Option = O;
105 State = S;
106 };
107
108 if (PragmaName == "nounroll") {
109 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
110 } else if (PragmaName == "unroll") {
111 // #pragma unroll N
112 if (ValueExpr) {
113 if (!ValueExpr->isValueDependent()) {
114 auto Value = ValueExpr->EvaluateKnownConstInt(S.getASTContext());
115 if (Value.isZero() || Value.isOne())
116 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
117 else
118 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
119 } else
120 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric);
121 } else
122 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable);
123 } else if (PragmaName == "nounroll_and_jam") {
124 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable);
125 } else if (PragmaName == "unroll_and_jam") {
126 // #pragma unroll_and_jam N
127 if (ValueExpr)
128 SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric);
129 else
130 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable);
131 } else {
132 // #pragma clang loop ...
133 assert(OptionLoc && OptionLoc->Ident &&
134 "Attribute must have valid option info.");
135 Option = llvm::StringSwitch<LoopHintAttr::OptionType>(
136 OptionLoc->Ident->getName())
137 .Case("vectorize", LoopHintAttr::Vectorize)
138 .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
139 .Case("interleave", LoopHintAttr::Interleave)
140 .Case("vectorize_predicate", LoopHintAttr::VectorizePredicate)
141 .Case("interleave_count", LoopHintAttr::InterleaveCount)
142 .Case("unroll", LoopHintAttr::Unroll)
143 .Case("unroll_count", LoopHintAttr::UnrollCount)
144 .Case("pipeline", LoopHintAttr::PipelineDisabled)
145 .Case("pipeline_initiation_interval",
146 LoopHintAttr::PipelineInitiationInterval)
147 .Case("distribute", LoopHintAttr::Distribute)
148 .Default(LoopHintAttr::Vectorize);
149 if (Option == LoopHintAttr::VectorizeWidth) {
150 assert((ValueExpr || (StateLoc && StateLoc->Ident)) &&
151 "Attribute must have a valid value expression or argument.");
152 if (ValueExpr && S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc(),
153 /*AllowZero=*/false))
154 return nullptr;
155 if (StateLoc && StateLoc->Ident && StateLoc->Ident->isStr("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(ValueExpr, 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 assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument");
174 if (StateLoc->Ident->isStr("disable"))
175 State = LoopHintAttr::Disable;
176 else if (StateLoc->Ident->isStr("assume_safety"))
177 State = LoopHintAttr::AssumeSafety;
178 else if (StateLoc->Ident->isStr("full"))
179 State = LoopHintAttr::Full;
180 else if (StateLoc->Ident->isStr("enable"))
181 State = LoopHintAttr::Enable;
182 else
183 llvm_unreachable("bad loop hint argument");
184 } else
185 llvm_unreachable("bad loop hint");
186 }
187
188 return LoopHintAttr::CreateImplicit(S.Context, Option, State, ValueExpr, A);
189}
190
191namespace {
192class CallExprFinder : public ConstEvaluatedExprVisitor<CallExprFinder> {
193 bool FoundAsmStmt = false;
194 std::vector<const CallExpr *> CallExprs;
195
196public:
198
199 CallExprFinder(Sema &S, const Stmt *St) : Inherited(S.Context) { Visit(St); }
200
201 bool foundCallExpr() { return !CallExprs.empty(); }
202 const std::vector<const CallExpr *> &getCallExprs() { return CallExprs; }
203
204 bool foundAsmStmt() { return FoundAsmStmt; }
205
206 void VisitCallExpr(const CallExpr *E) { CallExprs.push_back(E); }
207
208 void VisitAsmStmt(const AsmStmt *S) { FoundAsmStmt = true; }
209
210 void Visit(const Stmt *St) {
211 if (!St)
212 return;
214 }
215};
216} // namespace
217
218static Attr *handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
219 SourceRange Range) {
220 NoMergeAttr NMA(S.Context, A);
221 CallExprFinder CEF(S, St);
222
223 if (!CEF.foundCallExpr() && !CEF.foundAsmStmt()) {
224 S.Diag(St->getBeginLoc(), diag::warn_attribute_ignored_no_calls_in_stmt)
225 << A;
226 return nullptr;
227 }
228
229 return ::new (S.Context) NoMergeAttr(S.Context, A);
230}
231
232template <typename OtherAttr, int DiagIdx>
233static bool CheckStmtInlineAttr(Sema &SemaRef, const Stmt *OrigSt,
234 const Stmt *CurSt,
235 const AttributeCommonInfo &A) {
236 CallExprFinder OrigCEF(SemaRef, OrigSt);
237 CallExprFinder CEF(SemaRef, CurSt);
238
239 // If the call expressions lists are equal in size, we can skip
240 // previously emitted diagnostics. However, if the statement has a pack
241 // expansion, we have no way of telling which CallExpr is the instantiated
242 // version of the other. In this case, we will end up re-diagnosing in the
243 // instantiation.
244 // ie: [[clang::always_inline]] non_dependent(), (other_call<Pack>()...)
245 // will diagnose nondependent again.
246 bool CanSuppressDiag =
247 OrigSt && CEF.getCallExprs().size() == OrigCEF.getCallExprs().size();
248
249 if (!CEF.foundCallExpr()) {
250 return SemaRef.Diag(CurSt->getBeginLoc(),
251 diag::warn_attribute_ignored_no_calls_in_stmt)
252 << A;
253 }
254
255 for (const auto &Tup :
256 llvm::zip_longest(OrigCEF.getCallExprs(), CEF.getCallExprs())) {
257 // If the original call expression already had a callee, we already
258 // diagnosed this, so skip it here. We can't skip if there isn't a 1:1
259 // relationship between the two lists of call expressions.
260 if (!CanSuppressDiag || !(*std::get<0>(Tup))->getCalleeDecl()) {
261 const Decl *Callee = (*std::get<1>(Tup))->getCalleeDecl();
262 if (Callee &&
263 (Callee->hasAttr<OtherAttr>() || Callee->hasAttr<FlattenAttr>())) {
264 SemaRef.Diag(CurSt->getBeginLoc(),
265 diag::warn_function_stmt_attribute_precedence)
266 << A << (Callee->hasAttr<OtherAttr>() ? DiagIdx : 1);
267 SemaRef.Diag(Callee->getBeginLoc(), diag::note_conflicting_attribute);
268 }
269 }
270 }
271
272 return false;
273}
274
275bool Sema::CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
276 const AttributeCommonInfo &A) {
277 return CheckStmtInlineAttr<AlwaysInlineAttr, 0>(*this, OrigSt, CurSt, A);
278}
279
280bool Sema::CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
281 const AttributeCommonInfo &A) {
282 return CheckStmtInlineAttr<NoInlineAttr, 2>(*this, OrigSt, CurSt, A);
283}
284
285static Attr *handleNoInlineAttr(Sema &S, Stmt *St, const ParsedAttr &A,
286 SourceRange Range) {
287 NoInlineAttr NIA(S.Context, A);
288 if (!NIA.isClangNoInline()) {
289 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
290 << "[[clang::noinline]]";
291 return nullptr;
292 }
293
294 if (S.CheckNoInlineAttr(/*OrigSt=*/nullptr, St, A))
295 return nullptr;
296
297 return ::new (S.Context) NoInlineAttr(S.Context, A);
298}
299
301 SourceRange Range) {
302 AlwaysInlineAttr AIA(S.Context, A);
303 if (!AIA.isClangAlwaysInline()) {
304 S.Diag(St->getBeginLoc(), diag::warn_function_attribute_ignored_in_stmt)
305 << "[[clang::always_inline]]";
306 return nullptr;
307 }
308
309 if (S.CheckAlwaysInlineAttr(/*OrigSt=*/nullptr, St, A))
310 return nullptr;
311
312 return ::new (S.Context) AlwaysInlineAttr(S.Context, A);
313}
314
315static Attr *handleCXXAssumeAttr(Sema &S, Stmt *St, const ParsedAttr &A,
316 SourceRange Range) {
317 ExprResult Res = S.ActOnCXXAssumeAttr(St, A, Range);
318 if (!Res.isUsable())
319 return nullptr;
320
321 return ::new (S.Context) CXXAssumeAttr(S.Context, A, Res.get());
322}
323
324static Attr *handleMustTailAttr(Sema &S, Stmt *St, const ParsedAttr &A,
325 SourceRange Range) {
326 // Validation is in Sema::ActOnAttributedStmt().
327 return ::new (S.Context) MustTailAttr(S.Context, A);
328}
329
330static Attr *handleLikely(Sema &S, Stmt *St, const ParsedAttr &A,
331 SourceRange Range) {
332
333 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
334 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
335
336 return ::new (S.Context) LikelyAttr(S.Context, A);
337}
338
339static Attr *handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A,
340 SourceRange Range) {
341
342 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName())
343 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range;
344
345 return ::new (S.Context) UnlikelyAttr(S.Context, A);
346}
347
349 Expr *E) {
350 if (!E->isValueDependent()) {
351 llvm::APSInt ArgVal;
353 if (Res.isInvalid())
354 return nullptr;
355 E = Res.get();
356
357 // This attribute requires an integer argument which is a constant power of
358 // two between 1 and 4096 inclusive.
359 if (ArgVal < CodeAlignAttr::MinimumAlignment ||
360 ArgVal > CodeAlignAttr::MaximumAlignment || !ArgVal.isPowerOf2()) {
361 if (std::optional<int64_t> Value = ArgVal.trySExtValue())
362 Diag(CI.getLoc(), diag::err_attribute_power_of_two_in_range)
363 << CI << CodeAlignAttr::MinimumAlignment
364 << CodeAlignAttr::MaximumAlignment << Value.value();
365 else
366 Diag(CI.getLoc(), diag::err_attribute_power_of_two_in_range)
367 << CI << CodeAlignAttr::MinimumAlignment
368 << CodeAlignAttr::MaximumAlignment << E;
369 return nullptr;
370 }
371 }
372 return new (Context) CodeAlignAttr(Context, CI, E);
373}
374
375static Attr *handleCodeAlignAttr(Sema &S, Stmt *St, const ParsedAttr &A) {
376
377 Expr *E = A.getArgAsExpr(0);
378 return S.BuildCodeAlignAttr(A, E);
379}
380
381// Diagnose non-identical duplicates as a 'conflicting' loop attributes
382// and suppress duplicate errors in cases where the two match.
383template <typename LoopAttrT>
385 auto FindFunc = [](const Attr *A) { return isa<const LoopAttrT>(A); };
386 const auto *FirstItr = std::find_if(Attrs.begin(), Attrs.end(), FindFunc);
387
388 if (FirstItr == Attrs.end()) // no attributes found
389 return;
390
391 const auto *LastFoundItr = FirstItr;
392 std::optional<llvm::APSInt> FirstValue;
393
394 const auto *CAFA =
395 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*FirstItr)->getAlignment());
396 // Return early if first alignment expression is dependent (since we don't
397 // know what the effective size will be), and skip the loop entirely.
398 if (!CAFA)
399 return;
400
401 while (Attrs.end() != (LastFoundItr = std::find_if(LastFoundItr + 1,
402 Attrs.end(), FindFunc))) {
403 const auto *CASA =
404 dyn_cast<ConstantExpr>(cast<LoopAttrT>(*LastFoundItr)->getAlignment());
405 // If the value is dependent, we can not test anything.
406 if (!CASA)
407 return;
408 // Test the attribute values.
409 llvm::APSInt SecondValue = CASA->getResultAsAPSInt();
410 if (!FirstValue)
411 FirstValue = CAFA->getResultAsAPSInt();
412
413 if (FirstValue != SecondValue) {
414 S.Diag((*LastFoundItr)->getLocation(), diag::err_loop_attr_conflict)
415 << *FirstItr;
416 S.Diag((*FirstItr)->getLocation(), diag::note_previous_attribute);
417 }
418 }
419 return;
420}
421
423 SourceRange Range) {
425 S.Diag(A.getLoc(), diag::warn_unknown_attribute_ignored)
426 << A << A.getRange();
427 return nullptr;
428 }
429 return ::new (S.Context) MSConstexprAttr(S.Context, A);
430}
431
432#define WANT_STMT_MERGE_LOGIC
433#include "clang/Sema/AttrParsedAttrImpl.inc"
434#undef WANT_STMT_MERGE_LOGIC
435
436static void
438 const SmallVectorImpl<const Attr *> &Attrs) {
439 // The vast majority of attributed statements will only have one attribute
440 // on them, so skip all of the checking in the common case.
441 if (Attrs.size() < 2)
442 return;
443
444 // First, check for the easy cases that are table-generated for us.
445 if (!DiagnoseMutualExclusions(S, Attrs))
446 return;
447
448 enum CategoryType {
449 // For the following categories, they come in two variants: a state form and
450 // a numeric form. The state form may be one of default, enable, and
451 // disable. The numeric form provides an integer hint (for example, unroll
452 // count) to the transformer.
453 Vectorize,
454 Interleave,
455 UnrollAndJam,
456 Pipeline,
457 // For unroll, default indicates full unrolling rather than enabling the
458 // transformation.
459 Unroll,
460 // The loop distribution transformation only has a state form that is
461 // exposed by #pragma clang loop distribute (enable | disable).
462 Distribute,
463 // The vector predication only has a state form that is exposed by
464 // #pragma clang loop vectorize_predicate (enable | disable).
465 VectorizePredicate,
466 // This serves as a indicator to how many category are listed in this enum.
467 NumberOfCategories
468 };
469 // The following array accumulates the hints encountered while iterating
470 // through the attributes to check for compatibility.
471 struct {
472 const LoopHintAttr *StateAttr;
473 const LoopHintAttr *NumericAttr;
474 } HintAttrs[CategoryType::NumberOfCategories] = {};
475
476 for (const auto *I : Attrs) {
477 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
478
479 // Skip non loop hint attributes
480 if (!LH)
481 continue;
482
483 CategoryType Category = CategoryType::NumberOfCategories;
484 LoopHintAttr::OptionType Option = LH->getOption();
485 switch (Option) {
486 case LoopHintAttr::Vectorize:
487 case LoopHintAttr::VectorizeWidth:
488 Category = Vectorize;
489 break;
490 case LoopHintAttr::Interleave:
491 case LoopHintAttr::InterleaveCount:
492 Category = Interleave;
493 break;
494 case LoopHintAttr::Unroll:
495 case LoopHintAttr::UnrollCount:
496 Category = Unroll;
497 break;
498 case LoopHintAttr::UnrollAndJam:
499 case LoopHintAttr::UnrollAndJamCount:
500 Category = UnrollAndJam;
501 break;
502 case LoopHintAttr::Distribute:
503 // Perform the check for duplicated 'distribute' hints.
504 Category = Distribute;
505 break;
506 case LoopHintAttr::PipelineDisabled:
507 case LoopHintAttr::PipelineInitiationInterval:
508 Category = Pipeline;
509 break;
510 case LoopHintAttr::VectorizePredicate:
511 Category = VectorizePredicate;
512 break;
513 };
514
515 assert(Category != NumberOfCategories && "Unhandled loop hint option");
516 auto &CategoryState = HintAttrs[Category];
517 const LoopHintAttr *PrevAttr;
518 if (Option == LoopHintAttr::Vectorize ||
519 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll ||
520 Option == LoopHintAttr::UnrollAndJam ||
521 Option == LoopHintAttr::VectorizePredicate ||
522 Option == LoopHintAttr::PipelineDisabled ||
523 Option == LoopHintAttr::Distribute) {
524 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable).
525 PrevAttr = CategoryState.StateAttr;
526 CategoryState.StateAttr = LH;
527 } else {
528 // Numeric hint. For example, vectorize_width(8).
529 PrevAttr = CategoryState.NumericAttr;
530 CategoryState.NumericAttr = LH;
531 }
532
534 SourceLocation OptionLoc = LH->getRange().getBegin();
535 if (PrevAttr)
536 // Cannot specify same type of attribute twice.
537 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
538 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
539 << LH->getDiagnosticName(Policy);
540
541 if (CategoryState.StateAttr && CategoryState.NumericAttr &&
542 (Category == Unroll || Category == UnrollAndJam ||
543 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
544 // Disable hints are not compatible with numeric hints of the same
545 // category. As a special case, numeric unroll hints are also not
546 // compatible with enable or full form of the unroll pragma because these
547 // directives indicate full unrolling.
548 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
549 << /*Duplicate=*/false
550 << CategoryState.StateAttr->getDiagnosticName(Policy)
551 << CategoryState.NumericAttr->getDiagnosticName(Policy);
552 }
553 }
554}
555
557 SourceRange Range) {
558 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's
559 // useful for OpenCL 1.x too and doesn't require HW support.
560 // opencl_unroll_hint can have 0 arguments (compiler
561 // determines unrolling factor) or 1 argument (the unroll factor provided
562 // by the user).
563 unsigned UnrollFactor = 0;
564 if (A.getNumArgs() == 1) {
565 Expr *E = A.getArgAsExpr(0);
566 std::optional<llvm::APSInt> ArgVal;
567
568 if (!(ArgVal = E->getIntegerConstantExpr(S.Context))) {
569 S.Diag(A.getLoc(), diag::err_attribute_argument_type)
571 return nullptr;
572 }
573
574 int Val = ArgVal->getSExtValue();
575 if (Val <= 0) {
576 S.Diag(A.getRange().getBegin(),
577 diag::err_attribute_requires_positive_integer)
578 << A << /* positive */ 0;
579 return nullptr;
580 }
581 UnrollFactor = static_cast<unsigned>(Val);
582 }
583
584 return ::new (S.Context) OpenCLUnrollHintAttr(S.Context, A, UnrollFactor);
585}
586
587static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A,
588 SourceRange Range) {
590 return nullptr;
591
592 // Unknown attributes are automatically warned on. Target-specific attributes
593 // which do not apply to the current target architecture are treated as
594 // though they were unknown attributes.
595 const TargetInfo *Aux = S.Context.getAuxTargetInfo();
598 (S.Context.getLangOpts().SYCLIsDevice && Aux &&
599 A.existsInTarget(*Aux)))) {
601 ? (unsigned)diag::err_keyword_not_supported_on_target
603 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
604 : (unsigned)diag::warn_unknown_attribute_ignored)
605 << A << A.getRange();
606 return nullptr;
607 }
608
609 if (S.checkCommonAttributeFeatures(St, A))
610 return nullptr;
611
612 switch (A.getKind()) {
613 case ParsedAttr::AT_AlwaysInline:
614 return handleAlwaysInlineAttr(S, St, A, Range);
615 case ParsedAttr::AT_CXXAssume:
616 return handleCXXAssumeAttr(S, St, A, Range);
617 case ParsedAttr::AT_FallThrough:
618 return handleFallThroughAttr(S, St, A, Range);
619 case ParsedAttr::AT_LoopHint:
620 return handleLoopHintAttr(S, St, A, Range);
621 case ParsedAttr::AT_OpenCLUnrollHint:
622 return handleOpenCLUnrollHint(S, St, A, Range);
623 case ParsedAttr::AT_Suppress:
624 return handleSuppressAttr(S, St, A, Range);
625 case ParsedAttr::AT_NoMerge:
626 return handleNoMergeAttr(S, St, A, Range);
627 case ParsedAttr::AT_NoInline:
628 return handleNoInlineAttr(S, St, A, Range);
629 case ParsedAttr::AT_MustTail:
630 return handleMustTailAttr(S, St, A, Range);
631 case ParsedAttr::AT_Likely:
632 return handleLikely(S, St, A, Range);
633 case ParsedAttr::AT_Unlikely:
634 return handleUnlikely(S, St, A, Range);
635 case ParsedAttr::AT_CodeAlign:
636 return handleCodeAlignAttr(S, St, A);
637 case ParsedAttr::AT_MSConstexpr:
638 return handleMSConstexprAttr(S, St, A, Range);
639 default:
640 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
641 // declaration attribute is not written on a statement, but this code is
642 // needed for attributes in Attr.td that do not list any subjects.
643 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
644 << A << A.isRegularKeywordAttribute() << St->getBeginLoc();
645 return nullptr;
646 }
647}
648
651 for (const ParsedAttr &AL : InAttrs) {
652 if (const Attr *A = ProcessStmtAttribute(*this, S, AL, InAttrs.Range))
653 OutAttrs.push_back(A);
654 }
655
656 CheckForIncompatibleAttributes(*this, OutAttrs);
657 CheckForDuplicateLoopAttrs<CodeAlignAttr>(*this, OutAttrs);
658}
659
661 CheckForDuplicateLoopAttrs<CodeAlignAttr>(*this, Attrs);
662 return false;
663}
664
666 SourceRange Range) {
667 if (A.getNumArgs() != 1 || !A.getArgAsExpr(0)) {
668 Diag(A.getLoc(), diag::err_assume_attr_args) << A.getAttrName() << Range;
669 return ExprError();
670 }
671
672 auto *Assumption = A.getArgAsExpr(0);
673 if (Assumption->getDependence() == ExprDependence::None) {
674 ExprResult Res = BuildCXXAssumeExpr(Assumption, A.getAttrName(), Range);
675 if (Res.isInvalid())
676 return ExprError();
677 Assumption = Res.get();
678 }
679
681 Diag(A.getLoc(), diag::ext_cxx23_attr) << A << Range;
682
683 return Assumption;
684}
685
687 const IdentifierInfo *AttrName,
688 SourceRange Range) {
689 ExprResult Res = CorrectDelayedTyposInExpr(Assumption);
690 if (Res.isInvalid())
691 return ExprError();
692
693 Res = CheckPlaceholderExpr(Res.get());
694 if (Res.isInvalid())
695 return ExprError();
696
698 if (Res.isInvalid())
699 return ExprError();
700
701 Assumption = Res.get();
702 if (Assumption->HasSideEffects(Context))
703 Diag(Assumption->getBeginLoc(), diag::warn_assume_side_effects)
704 << AttrName << Range;
705
706 return Assumption;
707}
Defines the clang::ASTContext interface.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
int Category
Definition: Format.cpp:2974
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 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 void CheckForIncompatibleAttributes(Sema &S, const SmallVectorImpl< const Attr * > &Attrs)
static bool CheckStmtInlineAttr(Sema &SemaRef, const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
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)
Defines the SourceManager interface.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:758
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
AsmStmt is the base class for GCCAsmStmt and MSAsmStmt.
Definition: Stmt.h:3100
Attr - This represents one attribute.
Definition: Attr.h:42
unsigned getAttributeSpellingListIndex() const
const IdentifierInfo * getScopeName() const
SourceLocation getLoc() const
const IdentifierInfo * getAttrName() const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
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:110
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
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:3556
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
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:97
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.
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:625
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:126
bool existsInTarget(const TargetInfo &Target) const
Definition: ParsedAttr.cpp:201
IdentifierLoc * getArgAsIdent(unsigned Arg) const
Definition: ParsedAttr.h:402
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition: ParsedAttr.h:382
Expr * getArgAsExpr(unsigned Arg) const
Definition: ParsedAttr.h:394
AttributeCommonInfo::Kind getKind() const
Definition: ParsedAttr.h:617
bool isInvalid() const
Definition: ParsedAttr.h:355
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:946
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
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 ...
Definition: SemaAttr.cpp:1470
ExprResult BuildCXXAssumeExpr(Expr *Assumption, const IdentifierInfo *AttrName, SourceRange Range)
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17458
ASTContext & Context
Definition: Sema.h:858
ASTContext & getASTContext() const
Definition: Sema.h:527
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
const LangOptions & getLangOpts() const
Definition: Sema.h:520
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:892
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
Definition: SemaExpr.cpp:3886
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.
Definition: SemaExpr.cpp:21227
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)
ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A, SourceRange Range)
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 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
RetTy Visit(PTR(Stmt) S, ParamTys... P)
Definition: StmtVisitor.h:44
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
Exposes information about the current target.
Definition: TargetInfo.h:214
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
@ CPlusPlus23
Definition: LangStandard.h:60
@ AANT_ArgumentIntegerConstant
Definition: ParsedAttr.h:1067
ExprResult ExprError()
Definition: Ownership.h:264
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:100
IdentifierInfo * Ident
Definition: ParsedAttr.h:102
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57