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