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 void 214 CheckForIncompatibleAttributes(Sema &S, 215 const SmallVectorImpl<const Attr *> &Attrs) { 216 // There are 6 categories of loop hints attributes: vectorize, interleave, 217 // unroll, unroll_and_jam, pipeline and distribute. Except for distribute they 218 // come in two variants: a state form and a numeric form. The state form 219 // selectively defaults/enables/disables the transformation for the loop 220 // (for unroll, default indicates full unrolling rather than enabling the 221 // transformation). The numeric form form provides an integer hint (for 222 // example, unroll count) to the transformer. The following array accumulates 223 // the hints encountered while iterating through the attributes to check for 224 // compatibility. 225 struct { 226 const LoopHintAttr *StateAttr; 227 const LoopHintAttr *NumericAttr; 228 } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}, 229 {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}, 230 {nullptr, nullptr}}; 231 232 for (const auto *I : Attrs) { 233 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I); 234 235 // Skip non loop hint attributes 236 if (!LH) 237 continue; 238 239 LoopHintAttr::OptionType Option = LH->getOption(); 240 enum { 241 Vectorize, 242 Interleave, 243 Unroll, 244 UnrollAndJam, 245 Distribute, 246 Pipeline, 247 VectorizePredicate 248 } Category; 249 switch (Option) { 250 case LoopHintAttr::Vectorize: 251 case LoopHintAttr::VectorizeWidth: 252 Category = Vectorize; 253 break; 254 case LoopHintAttr::Interleave: 255 case LoopHintAttr::InterleaveCount: 256 Category = Interleave; 257 break; 258 case LoopHintAttr::Unroll: 259 case LoopHintAttr::UnrollCount: 260 Category = Unroll; 261 break; 262 case LoopHintAttr::UnrollAndJam: 263 case LoopHintAttr::UnrollAndJamCount: 264 Category = UnrollAndJam; 265 break; 266 case LoopHintAttr::Distribute: 267 // Perform the check for duplicated 'distribute' hints. 268 Category = Distribute; 269 break; 270 case LoopHintAttr::PipelineDisabled: 271 case LoopHintAttr::PipelineInitiationInterval: 272 Category = Pipeline; 273 break; 274 case LoopHintAttr::VectorizePredicate: 275 Category = VectorizePredicate; 276 break; 277 }; 278 279 assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0])); 280 auto &CategoryState = HintAttrs[Category]; 281 const LoopHintAttr *PrevAttr; 282 if (Option == LoopHintAttr::Vectorize || 283 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll || 284 Option == LoopHintAttr::UnrollAndJam || 285 Option == LoopHintAttr::VectorizePredicate || 286 Option == LoopHintAttr::PipelineDisabled || 287 Option == LoopHintAttr::Distribute) { 288 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable). 289 PrevAttr = CategoryState.StateAttr; 290 CategoryState.StateAttr = LH; 291 } else { 292 // Numeric hint. For example, vectorize_width(8). 293 PrevAttr = CategoryState.NumericAttr; 294 CategoryState.NumericAttr = LH; 295 } 296 297 PrintingPolicy Policy(S.Context.getLangOpts()); 298 SourceLocation OptionLoc = LH->getRange().getBegin(); 299 if (PrevAttr) 300 // Cannot specify same type of attribute twice. 301 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility) 302 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy) 303 << LH->getDiagnosticName(Policy); 304 305 if (CategoryState.StateAttr && CategoryState.NumericAttr && 306 (Category == Unroll || Category == UnrollAndJam || 307 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) { 308 // Disable hints are not compatible with numeric hints of the same 309 // category. As a special case, numeric unroll hints are also not 310 // compatible with enable or full form of the unroll pragma because these 311 // directives indicate full unrolling. 312 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility) 313 << /*Duplicate=*/false 314 << CategoryState.StateAttr->getDiagnosticName(Policy) 315 << CategoryState.NumericAttr->getDiagnosticName(Policy); 316 } 317 } 318 } 319 320 static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A, 321 SourceRange Range) { 322 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's 323 // useful for OpenCL 1.x too and doesn't require HW support. 324 // opencl_unroll_hint can have 0 arguments (compiler 325 // determines unrolling factor) or 1 argument (the unroll factor provided 326 // by the user). 327 328 unsigned NumArgs = A.getNumArgs(); 329 330 if (NumArgs > 1) { 331 S.Diag(A.getLoc(), diag::err_attribute_too_many_arguments) << A << 1; 332 return nullptr; 333 } 334 335 unsigned UnrollFactor = 0; 336 337 if (NumArgs == 1) { 338 Expr *E = A.getArgAsExpr(0); 339 Optional<llvm::APSInt> ArgVal; 340 341 if (!(ArgVal = E->getIntegerConstantExpr(S.Context))) { 342 S.Diag(A.getLoc(), diag::err_attribute_argument_type) 343 << A << AANT_ArgumentIntegerConstant << E->getSourceRange(); 344 return nullptr; 345 } 346 347 int Val = ArgVal->getSExtValue(); 348 349 if (Val <= 0) { 350 S.Diag(A.getRange().getBegin(), 351 diag::err_attribute_requires_positive_integer) 352 << A << /* positive */ 0; 353 return nullptr; 354 } 355 UnrollFactor = Val; 356 } 357 358 return OpenCLUnrollHintAttr::CreateImplicit(S.Context, UnrollFactor); 359 } 360 361 static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A, 362 SourceRange Range) { 363 switch (A.getKind()) { 364 case ParsedAttr::UnknownAttribute: 365 S.Diag(A.getLoc(), A.isDeclspecAttribute() 366 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored 367 : (unsigned)diag::warn_unknown_attribute_ignored) 368 << A; 369 return nullptr; 370 case ParsedAttr::AT_FallThrough: 371 return handleFallThroughAttr(S, St, A, Range); 372 case ParsedAttr::AT_LoopHint: 373 return handleLoopHintAttr(S, St, A, Range); 374 case ParsedAttr::AT_OpenCLUnrollHint: 375 return handleOpenCLUnrollHint(S, St, A, Range); 376 case ParsedAttr::AT_Suppress: 377 return handleSuppressAttr(S, St, A, Range); 378 case ParsedAttr::AT_NoMerge: 379 return handleNoMergeAttr(S, St, A, Range); 380 default: 381 // if we're here, then we parsed a known attribute, but didn't recognize 382 // it as a statement attribute => it is declaration attribute 383 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt) 384 << A << St->getBeginLoc(); 385 return nullptr; 386 } 387 } 388 389 StmtResult Sema::ProcessStmtAttributes(Stmt *S, 390 const ParsedAttributesView &AttrList, 391 SourceRange Range) { 392 SmallVector<const Attr*, 8> Attrs; 393 for (const ParsedAttr &AL : AttrList) { 394 if (Attr *a = ProcessStmtAttribute(*this, S, AL, Range)) 395 Attrs.push_back(a); 396 } 397 398 CheckForIncompatibleAttributes(*this, Attrs); 399 400 if (Attrs.empty()) 401 return S; 402 403 return ActOnAttributedStmt(Range.getBegin(), Attrs, S); 404 } 405