1 //===--- SemaStmtAttr.cpp - Statement Attribute Handling ------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements stmt-related attribute processing. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/EvaluatedExprVisitor.h" 15 #include "clang/Basic/SourceManager.h" 16 #include "clang/Basic/TargetInfo.h" 17 #include "clang/Sema/DelayedDiagnostic.h" 18 #include "clang/Sema/Lookup.h" 19 #include "clang/Sema/ScopeInfo.h" 20 #include "clang/Sema/SemaInternal.h" 21 #include "llvm/ADT/StringExtras.h" 22 23 using namespace clang; 24 using namespace sema; 25 26 static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A, 27 SourceRange Range) { 28 FallThroughAttr Attr(S.Context, A); 29 if (isa<SwitchCase>(St)) { 30 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target) 31 << A << St->getBeginLoc(); 32 SourceLocation L = S.getLocForEndOfToken(Range.getEnd()); 33 S.Diag(L, diag::note_fallthrough_insert_semi_fixit) 34 << FixItHint::CreateInsertion(L, ";"); 35 return nullptr; 36 } 37 auto *FnScope = S.getCurFunction(); 38 if (FnScope->SwitchStack.empty()) { 39 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch); 40 return nullptr; 41 } 42 43 // If this is spelled as the standard C++17 attribute, but not in C++17, warn 44 // about using it as an extension. 45 if (!S.getLangOpts().CPlusPlus17 && A.isCXX11Attribute() && 46 !A.getScopeName()) 47 S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A; 48 49 FnScope->setHasFallthroughStmt(); 50 return ::new (S.Context) FallThroughAttr(S.Context, A); 51 } 52 53 static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A, 54 SourceRange Range) { 55 std::vector<StringRef> DiagnosticIdentifiers; 56 for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) { 57 StringRef RuleName; 58 59 if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr)) 60 return nullptr; 61 62 // FIXME: Warn if the rule name is unknown. This is tricky because only 63 // clang-tidy knows about available rules. 64 DiagnosticIdentifiers.push_back(RuleName); 65 } 66 67 return ::new (S.Context) SuppressAttr( 68 S.Context, A, DiagnosticIdentifiers.data(), DiagnosticIdentifiers.size()); 69 } 70 71 static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A, 72 SourceRange) { 73 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0); 74 IdentifierLoc *OptionLoc = A.getArgAsIdent(1); 75 IdentifierLoc *StateLoc = A.getArgAsIdent(2); 76 Expr *ValueExpr = A.getArgAsExpr(3); 77 78 StringRef PragmaName = 79 llvm::StringSwitch<StringRef>(PragmaNameLoc->Ident->getName()) 80 .Cases("unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam", 81 PragmaNameLoc->Ident->getName()) 82 .Default("clang loop"); 83 84 // This could be handled automatically by adding a Subjects definition in 85 // Attr.td, but that would make the diagnostic behavior worse in this case 86 // because the user spells this attribute as a pragma. 87 if (!isa<DoStmt, ForStmt, CXXForRangeStmt, WhileStmt>(St)) { 88 std::string Pragma = "#pragma " + std::string(PragmaName); 89 S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma; 90 return nullptr; 91 } 92 93 LoopHintAttr::OptionType Option; 94 LoopHintAttr::LoopHintState State; 95 96 auto SetHints = [&Option, &State](LoopHintAttr::OptionType O, 97 LoopHintAttr::LoopHintState S) { 98 Option = O; 99 State = S; 100 }; 101 102 if (PragmaName == "nounroll") { 103 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable); 104 } else if (PragmaName == "unroll") { 105 // #pragma unroll N 106 if (ValueExpr) 107 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric); 108 else 109 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable); 110 } else if (PragmaName == "nounroll_and_jam") { 111 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable); 112 } else if (PragmaName == "unroll_and_jam") { 113 // #pragma unroll_and_jam N 114 if (ValueExpr) 115 SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric); 116 else 117 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable); 118 } else { 119 // #pragma clang loop ... 120 assert(OptionLoc && OptionLoc->Ident && 121 "Attribute must have valid option info."); 122 Option = llvm::StringSwitch<LoopHintAttr::OptionType>( 123 OptionLoc->Ident->getName()) 124 .Case("vectorize", LoopHintAttr::Vectorize) 125 .Case("vectorize_width", LoopHintAttr::VectorizeWidth) 126 .Case("interleave", LoopHintAttr::Interleave) 127 .Case("vectorize_predicate", LoopHintAttr::VectorizePredicate) 128 .Case("interleave_count", LoopHintAttr::InterleaveCount) 129 .Case("unroll", LoopHintAttr::Unroll) 130 .Case("unroll_count", LoopHintAttr::UnrollCount) 131 .Case("pipeline", LoopHintAttr::PipelineDisabled) 132 .Case("pipeline_initiation_interval", 133 LoopHintAttr::PipelineInitiationInterval) 134 .Case("distribute", LoopHintAttr::Distribute) 135 .Default(LoopHintAttr::Vectorize); 136 if (Option == LoopHintAttr::VectorizeWidth) { 137 assert((ValueExpr || (StateLoc && StateLoc->Ident)) && 138 "Attribute must have a valid value expression or argument."); 139 if (ValueExpr && S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc())) 140 return nullptr; 141 if (StateLoc && StateLoc->Ident && StateLoc->Ident->isStr("scalable")) 142 State = LoopHintAttr::ScalableWidth; 143 else 144 State = LoopHintAttr::FixedWidth; 145 } else if (Option == LoopHintAttr::InterleaveCount || 146 Option == LoopHintAttr::UnrollCount || 147 Option == LoopHintAttr::PipelineInitiationInterval) { 148 assert(ValueExpr && "Attribute must have a valid value expression."); 149 if (S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc())) 150 return nullptr; 151 State = LoopHintAttr::Numeric; 152 } else if (Option == LoopHintAttr::Vectorize || 153 Option == LoopHintAttr::Interleave || 154 Option == LoopHintAttr::VectorizePredicate || 155 Option == LoopHintAttr::Unroll || 156 Option == LoopHintAttr::Distribute || 157 Option == LoopHintAttr::PipelineDisabled) { 158 assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument"); 159 if (StateLoc->Ident->isStr("disable")) 160 State = LoopHintAttr::Disable; 161 else if (StateLoc->Ident->isStr("assume_safety")) 162 State = LoopHintAttr::AssumeSafety; 163 else if (StateLoc->Ident->isStr("full")) 164 State = LoopHintAttr::Full; 165 else if (StateLoc->Ident->isStr("enable")) 166 State = LoopHintAttr::Enable; 167 else 168 llvm_unreachable("bad loop hint argument"); 169 } else 170 llvm_unreachable("bad loop hint"); 171 } 172 173 return LoopHintAttr::CreateImplicit(S.Context, Option, State, ValueExpr, A); 174 } 175 176 namespace { 177 class CallExprFinder : public ConstEvaluatedExprVisitor<CallExprFinder> { 178 bool FoundCallExpr = false; 179 180 public: 181 typedef ConstEvaluatedExprVisitor<CallExprFinder> Inherited; 182 183 CallExprFinder(Sema &S, const Stmt *St) : Inherited(S.Context) { Visit(St); } 184 185 bool foundCallExpr() { return FoundCallExpr; } 186 187 void VisitCallExpr(const CallExpr *E) { FoundCallExpr = true; } 188 void VisitAsmStmt(const AsmStmt *S) { FoundCallExpr = true; } 189 190 void Visit(const Stmt *St) { 191 if (!St) 192 return; 193 ConstEvaluatedExprVisitor<CallExprFinder>::Visit(St); 194 } 195 }; 196 } // namespace 197 198 static Attr *handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A, 199 SourceRange Range) { 200 NoMergeAttr NMA(S.Context, A); 201 CallExprFinder CEF(S, St); 202 203 if (!CEF.foundCallExpr()) { 204 S.Diag(St->getBeginLoc(), diag::warn_nomerge_attribute_ignored_in_stmt) 205 << NMA.getSpelling(); 206 return nullptr; 207 } 208 209 return ::new (S.Context) NoMergeAttr(S.Context, A); 210 } 211 212 static Attr *handleLikely(Sema &S, Stmt *St, const ParsedAttr &A, 213 SourceRange Range) { 214 215 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName()) 216 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range; 217 218 return ::new (S.Context) LikelyAttr(S.Context, A); 219 } 220 221 static Attr *handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A, 222 SourceRange Range) { 223 224 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName()) 225 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range; 226 227 return ::new (S.Context) UnlikelyAttr(S.Context, A); 228 } 229 230 static void 231 CheckForIncompatibleAttributes(Sema &S, 232 const SmallVectorImpl<const Attr *> &Attrs) { 233 // There are 6 categories of loop hints attributes: vectorize, interleave, 234 // unroll, unroll_and_jam, pipeline and distribute. Except for distribute they 235 // come in two variants: a state form and a numeric form. The state form 236 // selectively defaults/enables/disables the transformation for the loop 237 // (for unroll, default indicates full unrolling rather than enabling the 238 // transformation). The numeric form form provides an integer hint (for 239 // example, unroll count) to the transformer. The following array accumulates 240 // the hints encountered while iterating through the attributes to check for 241 // compatibility. 242 struct { 243 const LoopHintAttr *StateAttr; 244 const LoopHintAttr *NumericAttr; 245 } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}, 246 {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}, 247 {nullptr, nullptr}}; 248 249 for (const auto *I : Attrs) { 250 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I); 251 252 // Skip non loop hint attributes 253 if (!LH) 254 continue; 255 256 LoopHintAttr::OptionType Option = LH->getOption(); 257 enum { 258 Vectorize, 259 Interleave, 260 Unroll, 261 UnrollAndJam, 262 Distribute, 263 Pipeline, 264 VectorizePredicate 265 } Category; 266 switch (Option) { 267 case LoopHintAttr::Vectorize: 268 case LoopHintAttr::VectorizeWidth: 269 Category = Vectorize; 270 break; 271 case LoopHintAttr::Interleave: 272 case LoopHintAttr::InterleaveCount: 273 Category = Interleave; 274 break; 275 case LoopHintAttr::Unroll: 276 case LoopHintAttr::UnrollCount: 277 Category = Unroll; 278 break; 279 case LoopHintAttr::UnrollAndJam: 280 case LoopHintAttr::UnrollAndJamCount: 281 Category = UnrollAndJam; 282 break; 283 case LoopHintAttr::Distribute: 284 // Perform the check for duplicated 'distribute' hints. 285 Category = Distribute; 286 break; 287 case LoopHintAttr::PipelineDisabled: 288 case LoopHintAttr::PipelineInitiationInterval: 289 Category = Pipeline; 290 break; 291 case LoopHintAttr::VectorizePredicate: 292 Category = VectorizePredicate; 293 break; 294 }; 295 296 assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0])); 297 auto &CategoryState = HintAttrs[Category]; 298 const LoopHintAttr *PrevAttr; 299 if (Option == LoopHintAttr::Vectorize || 300 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll || 301 Option == LoopHintAttr::UnrollAndJam || 302 Option == LoopHintAttr::VectorizePredicate || 303 Option == LoopHintAttr::PipelineDisabled || 304 Option == LoopHintAttr::Distribute) { 305 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable). 306 PrevAttr = CategoryState.StateAttr; 307 CategoryState.StateAttr = LH; 308 } else { 309 // Numeric hint. For example, vectorize_width(8). 310 PrevAttr = CategoryState.NumericAttr; 311 CategoryState.NumericAttr = LH; 312 } 313 314 PrintingPolicy Policy(S.Context.getLangOpts()); 315 SourceLocation OptionLoc = LH->getRange().getBegin(); 316 if (PrevAttr) 317 // Cannot specify same type of attribute twice. 318 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility) 319 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy) 320 << LH->getDiagnosticName(Policy); 321 322 if (CategoryState.StateAttr && CategoryState.NumericAttr && 323 (Category == Unroll || Category == UnrollAndJam || 324 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) { 325 // Disable hints are not compatible with numeric hints of the same 326 // category. As a special case, numeric unroll hints are also not 327 // compatible with enable or full form of the unroll pragma because these 328 // directives indicate full unrolling. 329 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility) 330 << /*Duplicate=*/false 331 << CategoryState.StateAttr->getDiagnosticName(Policy) 332 << CategoryState.NumericAttr->getDiagnosticName(Policy); 333 } 334 } 335 336 // C++20 [dcl.attr.likelihood]p1 The attribute-token likely shall not appear 337 // in an attribute-specifier-seq that contains the attribute-token unlikely. 338 const LikelyAttr *Likely = nullptr; 339 const UnlikelyAttr *Unlikely = nullptr; 340 for (const auto *I : Attrs) { 341 if (const auto *Attr = dyn_cast<LikelyAttr>(I)) { 342 if (Unlikely) { 343 S.Diag(Attr->getLocation(), diag::err_attributes_are_not_compatible) 344 << Attr << Unlikely << Attr->getRange(); 345 S.Diag(Unlikely->getLocation(), diag::note_conflicting_attribute) 346 << Unlikely->getRange(); 347 return; 348 } 349 Likely = Attr; 350 } else if (const auto *Attr = dyn_cast<UnlikelyAttr>(I)) { 351 if (Likely) { 352 S.Diag(Attr->getLocation(), diag::err_attributes_are_not_compatible) 353 << Attr << Likely << Attr->getRange(); 354 S.Diag(Likely->getLocation(), diag::note_conflicting_attribute) 355 << Likely->getRange(); 356 return; 357 } 358 Unlikely = Attr; 359 } 360 } 361 } 362 363 static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A, 364 SourceRange Range) { 365 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's 366 // useful for OpenCL 1.x too and doesn't require HW support. 367 // opencl_unroll_hint can have 0 arguments (compiler 368 // determines unrolling factor) or 1 argument (the unroll factor provided 369 // by the user). 370 unsigned UnrollFactor = 0; 371 if (A.getNumArgs() == 1) { 372 Expr *E = A.getArgAsExpr(0); 373 Optional<llvm::APSInt> ArgVal; 374 375 if (!(ArgVal = E->getIntegerConstantExpr(S.Context))) { 376 S.Diag(A.getLoc(), diag::err_attribute_argument_type) 377 << A << AANT_ArgumentIntegerConstant << E->getSourceRange(); 378 return nullptr; 379 } 380 381 int Val = ArgVal->getSExtValue(); 382 if (Val <= 0) { 383 S.Diag(A.getRange().getBegin(), 384 diag::err_attribute_requires_positive_integer) 385 << A << /* positive */ 0; 386 return nullptr; 387 } 388 UnrollFactor = static_cast<unsigned>(Val); 389 } 390 391 return ::new (S.Context) OpenCLUnrollHintAttr(S.Context, A, UnrollFactor); 392 } 393 394 static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A, 395 SourceRange Range) { 396 if (A.isInvalid() || A.getKind() == ParsedAttr::IgnoredAttribute) 397 return nullptr; 398 399 // Unknown attributes are automatically warned on. Target-specific attributes 400 // which do not apply to the current target architecture are treated as 401 // though they were unknown attributes. 402 const TargetInfo *Aux = S.Context.getAuxTargetInfo(); 403 if (A.getKind() == ParsedAttr::UnknownAttribute || 404 !(A.existsInTarget(S.Context.getTargetInfo()) || 405 (S.Context.getLangOpts().SYCLIsDevice && Aux && 406 A.existsInTarget(*Aux)))) { 407 S.Diag(A.getLoc(), A.isDeclspecAttribute() 408 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored 409 : (unsigned)diag::warn_unknown_attribute_ignored) 410 << A << A.getRange(); 411 return nullptr; 412 } 413 414 if (S.checkCommonAttributeFeatures(St, A)) 415 return nullptr; 416 417 switch (A.getKind()) { 418 case ParsedAttr::AT_FallThrough: 419 return handleFallThroughAttr(S, St, A, Range); 420 case ParsedAttr::AT_LoopHint: 421 return handleLoopHintAttr(S, St, A, Range); 422 case ParsedAttr::AT_OpenCLUnrollHint: 423 return handleOpenCLUnrollHint(S, St, A, Range); 424 case ParsedAttr::AT_Suppress: 425 return handleSuppressAttr(S, St, A, Range); 426 case ParsedAttr::AT_NoMerge: 427 return handleNoMergeAttr(S, St, A, Range); 428 case ParsedAttr::AT_Likely: 429 return handleLikely(S, St, A, Range); 430 case ParsedAttr::AT_Unlikely: 431 return handleUnlikely(S, St, A, Range); 432 default: 433 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a 434 // declaration attribute is not written on a statement, but this code is 435 // needed for attributes in Attr.td that do not list any subjects. 436 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt) 437 << A << St->getBeginLoc(); 438 return nullptr; 439 } 440 } 441 442 StmtResult Sema::ProcessStmtAttributes(Stmt *S, 443 const ParsedAttributesView &AttrList, 444 SourceRange Range) { 445 SmallVector<const Attr*, 8> Attrs; 446 for (const ParsedAttr &AL : AttrList) { 447 if (Attr *a = ProcessStmtAttribute(*this, S, AL, Range)) 448 Attrs.push_back(a); 449 } 450 451 CheckForIncompatibleAttributes(*this, Attrs); 452 453 if (Attrs.empty()) 454 return S; 455 456 return ActOnAttributedStmt(Range.getBegin(), Attrs, S); 457 } 458