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