1 //===--- SemaDeclAttr.cpp - Declaration 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 decl-related attribute processing. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTMutationListener.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/DeclTemplate.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/Mangle.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/Type.h" 25 #include "clang/Basic/CharInfo.h" 26 #include "clang/Basic/DarwinSDKInfo.h" 27 #include "clang/Basic/SourceLocation.h" 28 #include "clang/Basic/SourceManager.h" 29 #include "clang/Basic/TargetBuiltins.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/DeclSpec.h" 33 #include "clang/Sema/DelayedDiagnostic.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedAttr.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/SemaInternal.h" 40 #include "llvm/ADT/Optional.h" 41 #include "llvm/ADT/STLExtras.h" 42 #include "llvm/ADT/StringExtras.h" 43 #include "llvm/IR/Assumptions.h" 44 #include "llvm/MC/MCSectionMachO.h" 45 #include "llvm/Support/Error.h" 46 #include "llvm/Support/MathExtras.h" 47 #include "llvm/Support/raw_ostream.h" 48 49 using namespace clang; 50 using namespace sema; 51 52 namespace AttributeLangSupport { 53 enum LANG { 54 C, 55 Cpp, 56 ObjC 57 }; 58 } // end namespace AttributeLangSupport 59 60 //===----------------------------------------------------------------------===// 61 // Helper functions 62 //===----------------------------------------------------------------------===// 63 64 /// isFunctionOrMethod - Return true if the given decl has function 65 /// type (function or function-typed variable) or an Objective-C 66 /// method. 67 static bool isFunctionOrMethod(const Decl *D) { 68 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D); 69 } 70 71 /// Return true if the given decl has function type (function or 72 /// function-typed variable) or an Objective-C method or a block. 73 static bool isFunctionOrMethodOrBlock(const Decl *D) { 74 return isFunctionOrMethod(D) || isa<BlockDecl>(D); 75 } 76 77 /// Return true if the given decl has a declarator that should have 78 /// been processed by Sema::GetTypeForDeclarator. 79 static bool hasDeclarator(const Decl *D) { 80 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl. 81 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) || 82 isa<ObjCPropertyDecl>(D); 83 } 84 85 /// hasFunctionProto - Return true if the given decl has a argument 86 /// information. This decl should have already passed 87 /// isFunctionOrMethod or isFunctionOrMethodOrBlock. 88 static bool hasFunctionProto(const Decl *D) { 89 if (const FunctionType *FnTy = D->getFunctionType()) 90 return isa<FunctionProtoType>(FnTy); 91 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D); 92 } 93 94 /// getFunctionOrMethodNumParams - Return number of function or method 95 /// parameters. It is an error to call this on a K&R function (use 96 /// hasFunctionProto first). 97 static unsigned getFunctionOrMethodNumParams(const Decl *D) { 98 if (const FunctionType *FnTy = D->getFunctionType()) 99 return cast<FunctionProtoType>(FnTy)->getNumParams(); 100 if (const auto *BD = dyn_cast<BlockDecl>(D)) 101 return BD->getNumParams(); 102 return cast<ObjCMethodDecl>(D)->param_size(); 103 } 104 105 static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D, 106 unsigned Idx) { 107 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 108 return FD->getParamDecl(Idx); 109 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 110 return MD->getParamDecl(Idx); 111 if (const auto *BD = dyn_cast<BlockDecl>(D)) 112 return BD->getParamDecl(Idx); 113 return nullptr; 114 } 115 116 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) { 117 if (const FunctionType *FnTy = D->getFunctionType()) 118 return cast<FunctionProtoType>(FnTy)->getParamType(Idx); 119 if (const auto *BD = dyn_cast<BlockDecl>(D)) 120 return BD->getParamDecl(Idx)->getType(); 121 122 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType(); 123 } 124 125 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) { 126 if (auto *PVD = getFunctionOrMethodParam(D, Idx)) 127 return PVD->getSourceRange(); 128 return SourceRange(); 129 } 130 131 static QualType getFunctionOrMethodResultType(const Decl *D) { 132 if (const FunctionType *FnTy = D->getFunctionType()) 133 return FnTy->getReturnType(); 134 return cast<ObjCMethodDecl>(D)->getReturnType(); 135 } 136 137 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) { 138 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 139 return FD->getReturnTypeSourceRange(); 140 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 141 return MD->getReturnTypeSourceRange(); 142 return SourceRange(); 143 } 144 145 static bool isFunctionOrMethodVariadic(const Decl *D) { 146 if (const FunctionType *FnTy = D->getFunctionType()) 147 return cast<FunctionProtoType>(FnTy)->isVariadic(); 148 if (const auto *BD = dyn_cast<BlockDecl>(D)) 149 return BD->isVariadic(); 150 return cast<ObjCMethodDecl>(D)->isVariadic(); 151 } 152 153 static bool isInstanceMethod(const Decl *D) { 154 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D)) 155 return MethodDecl->isInstance(); 156 return false; 157 } 158 159 static inline bool isNSStringType(QualType T, ASTContext &Ctx, 160 bool AllowNSAttributedString = false) { 161 const auto *PT = T->getAs<ObjCObjectPointerType>(); 162 if (!PT) 163 return false; 164 165 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface(); 166 if (!Cls) 167 return false; 168 169 IdentifierInfo* ClsName = Cls->getIdentifier(); 170 171 if (AllowNSAttributedString && 172 ClsName == &Ctx.Idents.get("NSAttributedString")) 173 return true; 174 // FIXME: Should we walk the chain of classes? 175 return ClsName == &Ctx.Idents.get("NSString") || 176 ClsName == &Ctx.Idents.get("NSMutableString"); 177 } 178 179 static inline bool isCFStringType(QualType T, ASTContext &Ctx) { 180 const auto *PT = T->getAs<PointerType>(); 181 if (!PT) 182 return false; 183 184 const auto *RT = PT->getPointeeType()->getAs<RecordType>(); 185 if (!RT) 186 return false; 187 188 const RecordDecl *RD = RT->getDecl(); 189 if (RD->getTagKind() != TTK_Struct) 190 return false; 191 192 return RD->getIdentifier() == &Ctx.Idents.get("__CFString"); 193 } 194 195 static unsigned getNumAttributeArgs(const ParsedAttr &AL) { 196 // FIXME: Include the type in the argument list. 197 return AL.getNumArgs() + AL.hasParsedType(); 198 } 199 200 /// A helper function to provide Attribute Location for the Attr types 201 /// AND the ParsedAttr. 202 template <typename AttrInfo> 203 static std::enable_if_t<std::is_base_of<Attr, AttrInfo>::value, SourceLocation> 204 getAttrLoc(const AttrInfo &AL) { 205 return AL.getLocation(); 206 } 207 static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); } 208 209 /// If Expr is a valid integer constant, get the value of the integer 210 /// expression and return success or failure. May output an error. 211 /// 212 /// Negative argument is implicitly converted to unsigned, unless 213 /// \p StrictlyUnsigned is true. 214 template <typename AttrInfo> 215 static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr, 216 uint32_t &Val, unsigned Idx = UINT_MAX, 217 bool StrictlyUnsigned = false) { 218 Optional<llvm::APSInt> I = llvm::APSInt(32); 219 if (Expr->isTypeDependent() || 220 !(I = Expr->getIntegerConstantExpr(S.Context))) { 221 if (Idx != UINT_MAX) 222 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type) 223 << &AI << Idx << AANT_ArgumentIntegerConstant 224 << Expr->getSourceRange(); 225 else 226 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type) 227 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange(); 228 return false; 229 } 230 231 if (!I->isIntN(32)) { 232 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) 233 << toString(*I, 10, false) << 32 << /* Unsigned */ 1; 234 return false; 235 } 236 237 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) { 238 S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer) 239 << &AI << /*non-negative*/ 1; 240 return false; 241 } 242 243 Val = (uint32_t)I->getZExtValue(); 244 return true; 245 } 246 247 /// Wrapper around checkUInt32Argument, with an extra check to be sure 248 /// that the result will fit into a regular (signed) int. All args have the same 249 /// purpose as they do in checkUInt32Argument. 250 template <typename AttrInfo> 251 static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr, 252 int &Val, unsigned Idx = UINT_MAX) { 253 uint32_t UVal; 254 if (!checkUInt32Argument(S, AI, Expr, UVal, Idx)) 255 return false; 256 257 if (UVal > (uint32_t)std::numeric_limits<int>::max()) { 258 llvm::APSInt I(32); // for toString 259 I = UVal; 260 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) 261 << toString(I, 10, false) << 32 << /* Unsigned */ 0; 262 return false; 263 } 264 265 Val = UVal; 266 return true; 267 } 268 269 /// Diagnose mutually exclusive attributes when present on a given 270 /// declaration. Returns true if diagnosed. 271 template <typename AttrTy> 272 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) { 273 if (const auto *A = D->getAttr<AttrTy>()) { 274 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A; 275 S.Diag(A->getLocation(), diag::note_conflicting_attribute); 276 return true; 277 } 278 return false; 279 } 280 281 template <typename AttrTy> 282 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) { 283 if (const auto *A = D->getAttr<AttrTy>()) { 284 S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL 285 << A; 286 S.Diag(A->getLocation(), diag::note_conflicting_attribute); 287 return true; 288 } 289 return false; 290 } 291 292 /// Check if IdxExpr is a valid parameter index for a function or 293 /// instance method D. May output an error. 294 /// 295 /// \returns true if IdxExpr is a valid index. 296 template <typename AttrInfo> 297 static bool checkFunctionOrMethodParameterIndex( 298 Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum, 299 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) { 300 assert(isFunctionOrMethodOrBlock(D)); 301 302 // In C++ the implicit 'this' function parameter also counts. 303 // Parameters are counted from one. 304 bool HP = hasFunctionProto(D); 305 bool HasImplicitThisParam = isInstanceMethod(D); 306 bool IV = HP && isFunctionOrMethodVariadic(D); 307 unsigned NumParams = 308 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam; 309 310 Optional<llvm::APSInt> IdxInt; 311 if (IdxExpr->isTypeDependent() || 312 !(IdxInt = IdxExpr->getIntegerConstantExpr(S.Context))) { 313 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type) 314 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant 315 << IdxExpr->getSourceRange(); 316 return false; 317 } 318 319 unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX); 320 if (IdxSource < 1 || (!IV && IdxSource > NumParams)) { 321 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds) 322 << &AI << AttrArgNum << IdxExpr->getSourceRange(); 323 return false; 324 } 325 if (HasImplicitThisParam && !CanIndexImplicitThis) { 326 if (IdxSource == 1) { 327 S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument) 328 << &AI << IdxExpr->getSourceRange(); 329 return false; 330 } 331 } 332 333 Idx = ParamIdx(IdxSource, D); 334 return true; 335 } 336 337 /// Check if the argument \p E is a ASCII string literal. If not emit an error 338 /// and return false, otherwise set \p Str to the value of the string literal 339 /// and return true. 340 bool Sema::checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, 341 const Expr *E, StringRef &Str, 342 SourceLocation *ArgLocation) { 343 const auto *Literal = dyn_cast<StringLiteral>(E->IgnoreParenCasts()); 344 if (ArgLocation) 345 *ArgLocation = E->getBeginLoc(); 346 347 if (!Literal || !Literal->isAscii()) { 348 Diag(E->getBeginLoc(), diag::err_attribute_argument_type) 349 << CI << AANT_ArgumentString; 350 return false; 351 } 352 353 Str = Literal->getString(); 354 return true; 355 } 356 357 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal. 358 /// If not emit an error and return false. If the argument is an identifier it 359 /// will emit an error with a fixit hint and treat it as if it was a string 360 /// literal. 361 bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum, 362 StringRef &Str, 363 SourceLocation *ArgLocation) { 364 // Look for identifiers. If we have one emit a hint to fix it to a literal. 365 if (AL.isArgIdent(ArgNum)) { 366 IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum); 367 Diag(Loc->Loc, diag::err_attribute_argument_type) 368 << AL << AANT_ArgumentString 369 << FixItHint::CreateInsertion(Loc->Loc, "\"") 370 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\""); 371 Str = Loc->Ident->getName(); 372 if (ArgLocation) 373 *ArgLocation = Loc->Loc; 374 return true; 375 } 376 377 // Now check for an actual string literal. 378 Expr *ArgExpr = AL.getArgAsExpr(ArgNum); 379 return checkStringLiteralArgumentAttr(AL, ArgExpr, Str, ArgLocation); 380 } 381 382 /// Applies the given attribute to the Decl without performing any 383 /// additional semantic checking. 384 template <typename AttrType> 385 static void handleSimpleAttribute(Sema &S, Decl *D, 386 const AttributeCommonInfo &CI) { 387 D->addAttr(::new (S.Context) AttrType(S.Context, CI)); 388 } 389 390 template <typename... DiagnosticArgs> 391 static const Sema::SemaDiagnosticBuilder& 392 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) { 393 return Bldr; 394 } 395 396 template <typename T, typename... DiagnosticArgs> 397 static const Sema::SemaDiagnosticBuilder& 398 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg, 399 DiagnosticArgs &&... ExtraArgs) { 400 return appendDiagnostics(Bldr << std::forward<T>(ExtraArg), 401 std::forward<DiagnosticArgs>(ExtraArgs)...); 402 } 403 404 /// Add an attribute @c AttrType to declaration @c D, provided that 405 /// @c PassesCheck is true. 406 /// Otherwise, emit diagnostic @c DiagID, passing in all parameters 407 /// specified in @c ExtraArgs. 408 template <typename AttrType, typename... DiagnosticArgs> 409 static void handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, 410 const AttributeCommonInfo &CI, 411 bool PassesCheck, unsigned DiagID, 412 DiagnosticArgs &&... ExtraArgs) { 413 if (!PassesCheck) { 414 Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID); 415 appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...); 416 return; 417 } 418 handleSimpleAttribute<AttrType>(S, D, CI); 419 } 420 421 /// Check if the passed-in expression is of type int or bool. 422 static bool isIntOrBool(Expr *Exp) { 423 QualType QT = Exp->getType(); 424 return QT->isBooleanType() || QT->isIntegerType(); 425 } 426 427 428 // Check to see if the type is a smart pointer of some kind. We assume 429 // it's a smart pointer if it defines both operator-> and operator*. 430 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) { 431 auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record, 432 OverloadedOperatorKind Op) { 433 DeclContextLookupResult Result = 434 Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op)); 435 return !Result.empty(); 436 }; 437 438 const RecordDecl *Record = RT->getDecl(); 439 bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star); 440 bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow); 441 if (foundStarOperator && foundArrowOperator) 442 return true; 443 444 const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record); 445 if (!CXXRecord) 446 return false; 447 448 for (auto BaseSpecifier : CXXRecord->bases()) { 449 if (!foundStarOperator) 450 foundStarOperator = IsOverloadedOperatorPresent( 451 BaseSpecifier.getType()->getAsRecordDecl(), OO_Star); 452 if (!foundArrowOperator) 453 foundArrowOperator = IsOverloadedOperatorPresent( 454 BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow); 455 } 456 457 if (foundStarOperator && foundArrowOperator) 458 return true; 459 460 return false; 461 } 462 463 /// Check if passed in Decl is a pointer type. 464 /// Note that this function may produce an error message. 465 /// \return true if the Decl is a pointer type; false otherwise 466 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D, 467 const ParsedAttr &AL) { 468 const auto *VD = cast<ValueDecl>(D); 469 QualType QT = VD->getType(); 470 if (QT->isAnyPointerType()) 471 return true; 472 473 if (const auto *RT = QT->getAs<RecordType>()) { 474 // If it's an incomplete type, it could be a smart pointer; skip it. 475 // (We don't want to force template instantiation if we can avoid it, 476 // since that would alter the order in which templates are instantiated.) 477 if (RT->isIncompleteType()) 478 return true; 479 480 if (threadSafetyCheckIsSmartPointer(S, RT)) 481 return true; 482 } 483 484 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT; 485 return false; 486 } 487 488 /// Checks that the passed in QualType either is of RecordType or points 489 /// to RecordType. Returns the relevant RecordType, null if it does not exit. 490 static const RecordType *getRecordType(QualType QT) { 491 if (const auto *RT = QT->getAs<RecordType>()) 492 return RT; 493 494 // Now check if we point to record type. 495 if (const auto *PT = QT->getAs<PointerType>()) 496 return PT->getPointeeType()->getAs<RecordType>(); 497 498 return nullptr; 499 } 500 501 template <typename AttrType> 502 static bool checkRecordDeclForAttr(const RecordDecl *RD) { 503 // Check if the record itself has the attribute. 504 if (RD->hasAttr<AttrType>()) 505 return true; 506 507 // Else check if any base classes have the attribute. 508 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) { 509 if (!CRD->forallBases([](const CXXRecordDecl *Base) { 510 return !Base->hasAttr<AttrType>(); 511 })) 512 return true; 513 } 514 return false; 515 } 516 517 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) { 518 const RecordType *RT = getRecordType(Ty); 519 520 if (!RT) 521 return false; 522 523 // Don't check for the capability if the class hasn't been defined yet. 524 if (RT->isIncompleteType()) 525 return true; 526 527 // Allow smart pointers to be used as capability objects. 528 // FIXME -- Check the type that the smart pointer points to. 529 if (threadSafetyCheckIsSmartPointer(S, RT)) 530 return true; 531 532 return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl()); 533 } 534 535 static bool checkTypedefTypeForCapability(QualType Ty) { 536 const auto *TD = Ty->getAs<TypedefType>(); 537 if (!TD) 538 return false; 539 540 TypedefNameDecl *TN = TD->getDecl(); 541 if (!TN) 542 return false; 543 544 return TN->hasAttr<CapabilityAttr>(); 545 } 546 547 static bool typeHasCapability(Sema &S, QualType Ty) { 548 if (checkTypedefTypeForCapability(Ty)) 549 return true; 550 551 if (checkRecordTypeForCapability(S, Ty)) 552 return true; 553 554 return false; 555 } 556 557 static bool isCapabilityExpr(Sema &S, const Expr *Ex) { 558 // Capability expressions are simple expressions involving the boolean logic 559 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once 560 // a DeclRefExpr is found, its type should be checked to determine whether it 561 // is a capability or not. 562 563 if (const auto *E = dyn_cast<CastExpr>(Ex)) 564 return isCapabilityExpr(S, E->getSubExpr()); 565 else if (const auto *E = dyn_cast<ParenExpr>(Ex)) 566 return isCapabilityExpr(S, E->getSubExpr()); 567 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) { 568 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf || 569 E->getOpcode() == UO_Deref) 570 return isCapabilityExpr(S, E->getSubExpr()); 571 return false; 572 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) { 573 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr) 574 return isCapabilityExpr(S, E->getLHS()) && 575 isCapabilityExpr(S, E->getRHS()); 576 return false; 577 } 578 579 return typeHasCapability(S, Ex->getType()); 580 } 581 582 /// Checks that all attribute arguments, starting from Sidx, resolve to 583 /// a capability object. 584 /// \param Sidx The attribute argument index to start checking with. 585 /// \param ParamIdxOk Whether an argument can be indexing into a function 586 /// parameter list. 587 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D, 588 const ParsedAttr &AL, 589 SmallVectorImpl<Expr *> &Args, 590 unsigned Sidx = 0, 591 bool ParamIdxOk = false) { 592 if (Sidx == AL.getNumArgs()) { 593 // If we don't have any capability arguments, the attribute implicitly 594 // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're 595 // a non-static method, and that the class is a (scoped) capability. 596 const auto *MD = dyn_cast<const CXXMethodDecl>(D); 597 if (MD && !MD->isStatic()) { 598 const CXXRecordDecl *RD = MD->getParent(); 599 // FIXME -- need to check this again on template instantiation 600 if (!checkRecordDeclForAttr<CapabilityAttr>(RD) && 601 !checkRecordDeclForAttr<ScopedLockableAttr>(RD)) 602 S.Diag(AL.getLoc(), 603 diag::warn_thread_attribute_not_on_capability_member) 604 << AL << MD->getParent(); 605 } else { 606 S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member) 607 << AL; 608 } 609 } 610 611 for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) { 612 Expr *ArgExp = AL.getArgAsExpr(Idx); 613 614 if (ArgExp->isTypeDependent()) { 615 // FIXME -- need to check this again on template instantiation 616 Args.push_back(ArgExp); 617 continue; 618 } 619 620 if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) { 621 if (StrLit->getLength() == 0 || 622 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) { 623 // Pass empty strings to the analyzer without warnings. 624 // Treat "*" as the universal lock. 625 Args.push_back(ArgExp); 626 continue; 627 } 628 629 // We allow constant strings to be used as a placeholder for expressions 630 // that are not valid C++ syntax, but warn that they are ignored. 631 S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL; 632 Args.push_back(ArgExp); 633 continue; 634 } 635 636 QualType ArgTy = ArgExp->getType(); 637 638 // A pointer to member expression of the form &MyClass::mu is treated 639 // specially -- we need to look at the type of the member. 640 if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp)) 641 if (UOp->getOpcode() == UO_AddrOf) 642 if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr())) 643 if (DRE->getDecl()->isCXXInstanceMember()) 644 ArgTy = DRE->getDecl()->getType(); 645 646 // First see if we can just cast to record type, or pointer to record type. 647 const RecordType *RT = getRecordType(ArgTy); 648 649 // Now check if we index into a record type function param. 650 if(!RT && ParamIdxOk) { 651 const auto *FD = dyn_cast<FunctionDecl>(D); 652 const auto *IL = dyn_cast<IntegerLiteral>(ArgExp); 653 if(FD && IL) { 654 unsigned int NumParams = FD->getNumParams(); 655 llvm::APInt ArgValue = IL->getValue(); 656 uint64_t ParamIdxFromOne = ArgValue.getZExtValue(); 657 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1; 658 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) { 659 S.Diag(AL.getLoc(), 660 diag::err_attribute_argument_out_of_bounds_extra_info) 661 << AL << Idx + 1 << NumParams; 662 continue; 663 } 664 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType(); 665 } 666 } 667 668 // If the type does not have a capability, see if the components of the 669 // expression have capabilities. This allows for writing C code where the 670 // capability may be on the type, and the expression is a capability 671 // boolean logic expression. Eg) requires_capability(A || B && !C) 672 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp)) 673 S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable) 674 << AL << ArgTy; 675 676 Args.push_back(ArgExp); 677 } 678 } 679 680 //===----------------------------------------------------------------------===// 681 // Attribute Implementations 682 //===----------------------------------------------------------------------===// 683 684 static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 685 if (!threadSafetyCheckIsPointer(S, D, AL)) 686 return; 687 688 D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL)); 689 } 690 691 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL, 692 Expr *&Arg) { 693 SmallVector<Expr *, 1> Args; 694 // check that all arguments are lockable objects 695 checkAttrArgsAreCapabilityObjs(S, D, AL, Args); 696 unsigned Size = Args.size(); 697 if (Size != 1) 698 return false; 699 700 Arg = Args[0]; 701 702 return true; 703 } 704 705 static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 706 Expr *Arg = nullptr; 707 if (!checkGuardedByAttrCommon(S, D, AL, Arg)) 708 return; 709 710 D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg)); 711 } 712 713 static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 714 Expr *Arg = nullptr; 715 if (!checkGuardedByAttrCommon(S, D, AL, Arg)) 716 return; 717 718 if (!threadSafetyCheckIsPointer(S, D, AL)) 719 return; 720 721 D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg)); 722 } 723 724 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL, 725 SmallVectorImpl<Expr *> &Args) { 726 if (!AL.checkAtLeastNumArgs(S, 1)) 727 return false; 728 729 // Check that this attribute only applies to lockable types. 730 QualType QT = cast<ValueDecl>(D)->getType(); 731 if (!QT->isDependentType() && !typeHasCapability(S, QT)) { 732 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL; 733 return false; 734 } 735 736 // Check that all arguments are lockable objects. 737 checkAttrArgsAreCapabilityObjs(S, D, AL, Args); 738 if (Args.empty()) 739 return false; 740 741 return true; 742 } 743 744 static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 745 SmallVector<Expr *, 1> Args; 746 if (!checkAcquireOrderAttrCommon(S, D, AL, Args)) 747 return; 748 749 Expr **StartArg = &Args[0]; 750 D->addAttr(::new (S.Context) 751 AcquiredAfterAttr(S.Context, AL, StartArg, Args.size())); 752 } 753 754 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 755 SmallVector<Expr *, 1> Args; 756 if (!checkAcquireOrderAttrCommon(S, D, AL, Args)) 757 return; 758 759 Expr **StartArg = &Args[0]; 760 D->addAttr(::new (S.Context) 761 AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size())); 762 } 763 764 static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL, 765 SmallVectorImpl<Expr *> &Args) { 766 // zero or more arguments ok 767 // check that all arguments are lockable objects 768 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true); 769 770 return true; 771 } 772 773 static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 774 SmallVector<Expr *, 1> Args; 775 if (!checkLockFunAttrCommon(S, D, AL, Args)) 776 return; 777 778 unsigned Size = Args.size(); 779 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 780 D->addAttr(::new (S.Context) 781 AssertSharedLockAttr(S.Context, AL, StartArg, Size)); 782 } 783 784 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D, 785 const ParsedAttr &AL) { 786 SmallVector<Expr *, 1> Args; 787 if (!checkLockFunAttrCommon(S, D, AL, Args)) 788 return; 789 790 unsigned Size = Args.size(); 791 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 792 D->addAttr(::new (S.Context) 793 AssertExclusiveLockAttr(S.Context, AL, StartArg, Size)); 794 } 795 796 /// Checks to be sure that the given parameter number is in bounds, and 797 /// is an integral type. Will emit appropriate diagnostics if this returns 798 /// false. 799 /// 800 /// AttrArgNo is used to actually retrieve the argument, so it's base-0. 801 template <typename AttrInfo> 802 static bool checkParamIsIntegerType(Sema &S, const Decl *D, const AttrInfo &AI, 803 unsigned AttrArgNo) { 804 assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument"); 805 Expr *AttrArg = AI.getArgAsExpr(AttrArgNo); 806 ParamIdx Idx; 807 if (!checkFunctionOrMethodParameterIndex(S, D, AI, AttrArgNo + 1, AttrArg, 808 Idx)) 809 return false; 810 811 QualType ParamTy = getFunctionOrMethodParamType(D, Idx.getASTIndex()); 812 if (!ParamTy->isIntegerType() && !ParamTy->isCharType()) { 813 SourceLocation SrcLoc = AttrArg->getBeginLoc(); 814 S.Diag(SrcLoc, diag::err_attribute_integers_only) 815 << AI << getFunctionOrMethodParamRange(D, Idx.getASTIndex()); 816 return false; 817 } 818 return true; 819 } 820 821 static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 822 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2)) 823 return; 824 825 assert(isFunctionOrMethod(D) && hasFunctionProto(D)); 826 827 QualType RetTy = getFunctionOrMethodResultType(D); 828 if (!RetTy->isPointerType()) { 829 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL; 830 return; 831 } 832 833 const Expr *SizeExpr = AL.getArgAsExpr(0); 834 int SizeArgNoVal; 835 // Parameter indices are 1-indexed, hence Index=1 836 if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1)) 837 return; 838 if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/0)) 839 return; 840 ParamIdx SizeArgNo(SizeArgNoVal, D); 841 842 ParamIdx NumberArgNo; 843 if (AL.getNumArgs() == 2) { 844 const Expr *NumberExpr = AL.getArgAsExpr(1); 845 int Val; 846 // Parameter indices are 1-based, hence Index=2 847 if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2)) 848 return; 849 if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/1)) 850 return; 851 NumberArgNo = ParamIdx(Val, D); 852 } 853 854 D->addAttr(::new (S.Context) 855 AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo)); 856 } 857 858 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL, 859 SmallVectorImpl<Expr *> &Args) { 860 if (!AL.checkAtLeastNumArgs(S, 1)) 861 return false; 862 863 if (!isIntOrBool(AL.getArgAsExpr(0))) { 864 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 865 << AL << 1 << AANT_ArgumentIntOrBool; 866 return false; 867 } 868 869 // check that all arguments are lockable objects 870 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1); 871 872 return true; 873 } 874 875 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D, 876 const ParsedAttr &AL) { 877 SmallVector<Expr*, 2> Args; 878 if (!checkTryLockFunAttrCommon(S, D, AL, Args)) 879 return; 880 881 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr( 882 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size())); 883 } 884 885 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D, 886 const ParsedAttr &AL) { 887 SmallVector<Expr*, 2> Args; 888 if (!checkTryLockFunAttrCommon(S, D, AL, Args)) 889 return; 890 891 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr( 892 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size())); 893 } 894 895 static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 896 // check that the argument is lockable object 897 SmallVector<Expr*, 1> Args; 898 checkAttrArgsAreCapabilityObjs(S, D, AL, Args); 899 unsigned Size = Args.size(); 900 if (Size == 0) 901 return; 902 903 D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0])); 904 } 905 906 static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 907 if (!AL.checkAtLeastNumArgs(S, 1)) 908 return; 909 910 // check that all arguments are lockable objects 911 SmallVector<Expr*, 1> Args; 912 checkAttrArgsAreCapabilityObjs(S, D, AL, Args); 913 unsigned Size = Args.size(); 914 if (Size == 0) 915 return; 916 Expr **StartArg = &Args[0]; 917 918 D->addAttr(::new (S.Context) 919 LocksExcludedAttr(S.Context, AL, StartArg, Size)); 920 } 921 922 static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL, 923 Expr *&Cond, StringRef &Msg) { 924 Cond = AL.getArgAsExpr(0); 925 if (!Cond->isTypeDependent()) { 926 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); 927 if (Converted.isInvalid()) 928 return false; 929 Cond = Converted.get(); 930 } 931 932 if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg)) 933 return false; 934 935 if (Msg.empty()) 936 Msg = "<no message provided>"; 937 938 SmallVector<PartialDiagnosticAt, 8> Diags; 939 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() && 940 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D), 941 Diags)) { 942 S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL; 943 for (const PartialDiagnosticAt &PDiag : Diags) 944 S.Diag(PDiag.first, PDiag.second); 945 return false; 946 } 947 return true; 948 } 949 950 static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 951 S.Diag(AL.getLoc(), diag::ext_clang_enable_if); 952 953 Expr *Cond; 954 StringRef Msg; 955 if (checkFunctionConditionAttr(S, D, AL, Cond, Msg)) 956 D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg)); 957 } 958 959 static void handleErrorAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 960 StringRef NewUserDiagnostic; 961 if (!S.checkStringLiteralArgumentAttr(AL, 0, NewUserDiagnostic)) 962 return; 963 if (ErrorAttr *EA = S.mergeErrorAttr(D, AL, NewUserDiagnostic)) 964 D->addAttr(EA); 965 } 966 967 namespace { 968 /// Determines if a given Expr references any of the given function's 969 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable). 970 class ArgumentDependenceChecker 971 : public RecursiveASTVisitor<ArgumentDependenceChecker> { 972 #ifndef NDEBUG 973 const CXXRecordDecl *ClassType; 974 #endif 975 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms; 976 bool Result; 977 978 public: 979 ArgumentDependenceChecker(const FunctionDecl *FD) { 980 #ifndef NDEBUG 981 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 982 ClassType = MD->getParent(); 983 else 984 ClassType = nullptr; 985 #endif 986 Parms.insert(FD->param_begin(), FD->param_end()); 987 } 988 989 bool referencesArgs(Expr *E) { 990 Result = false; 991 TraverseStmt(E); 992 return Result; 993 } 994 995 bool VisitCXXThisExpr(CXXThisExpr *E) { 996 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType && 997 "`this` doesn't refer to the enclosing class?"); 998 Result = true; 999 return false; 1000 } 1001 1002 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 1003 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 1004 if (Parms.count(PVD)) { 1005 Result = true; 1006 return false; 1007 } 1008 return true; 1009 } 1010 }; 1011 } 1012 1013 static void handleDiagnoseAsBuiltinAttr(Sema &S, Decl *D, 1014 const ParsedAttr &AL) { 1015 const auto *DeclFD = cast<FunctionDecl>(D); 1016 1017 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclFD)) 1018 if (!MethodDecl->isStatic()) { 1019 S.Diag(AL.getLoc(), diag::err_attribute_no_member_function) << AL; 1020 return; 1021 } 1022 1023 auto DiagnoseType = [&](unsigned Index, AttributeArgumentNType T) { 1024 SourceLocation Loc = [&]() { 1025 auto Union = AL.getArg(Index - 1); 1026 if (Union.is<Expr *>()) 1027 return Union.get<Expr *>()->getBeginLoc(); 1028 return Union.get<IdentifierLoc *>()->Loc; 1029 }(); 1030 1031 S.Diag(Loc, diag::err_attribute_argument_n_type) << AL << Index << T; 1032 }; 1033 1034 FunctionDecl *AttrFD = [&]() -> FunctionDecl * { 1035 if (!AL.isArgExpr(0)) 1036 return nullptr; 1037 auto *F = dyn_cast_or_null<DeclRefExpr>(AL.getArgAsExpr(0)); 1038 if (!F) 1039 return nullptr; 1040 return dyn_cast_or_null<FunctionDecl>(F->getFoundDecl()); 1041 }(); 1042 1043 if (!AttrFD || !AttrFD->getBuiltinID(true)) { 1044 DiagnoseType(1, AANT_ArgumentBuiltinFunction); 1045 return; 1046 } 1047 1048 if (AttrFD->getNumParams() != AL.getNumArgs() - 1) { 1049 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments_for) 1050 << AL << AttrFD << AttrFD->getNumParams(); 1051 return; 1052 } 1053 1054 SmallVector<unsigned, 8> Indices; 1055 1056 for (unsigned I = 1; I < AL.getNumArgs(); ++I) { 1057 if (!AL.isArgExpr(I)) { 1058 DiagnoseType(I + 1, AANT_ArgumentIntegerConstant); 1059 return; 1060 } 1061 1062 const Expr *IndexExpr = AL.getArgAsExpr(I); 1063 uint32_t Index; 1064 1065 if (!checkUInt32Argument(S, AL, IndexExpr, Index, I + 1, false)) 1066 return; 1067 1068 if (Index > DeclFD->getNumParams()) { 1069 S.Diag(AL.getLoc(), diag::err_attribute_bounds_for_function) 1070 << AL << Index << DeclFD << DeclFD->getNumParams(); 1071 return; 1072 } 1073 1074 QualType T1 = AttrFD->getParamDecl(I - 1)->getType(); 1075 QualType T2 = DeclFD->getParamDecl(Index - 1)->getType(); 1076 1077 if (T1.getCanonicalType().getUnqualifiedType() != 1078 T2.getCanonicalType().getUnqualifiedType()) { 1079 S.Diag(IndexExpr->getBeginLoc(), diag::err_attribute_parameter_types) 1080 << AL << Index << DeclFD << T2 << I << AttrFD << T1; 1081 return; 1082 } 1083 1084 Indices.push_back(Index - 1); 1085 } 1086 1087 D->addAttr(::new (S.Context) DiagnoseAsBuiltinAttr( 1088 S.Context, AL, AttrFD, Indices.data(), Indices.size())); 1089 } 1090 1091 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1092 S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if); 1093 1094 Expr *Cond; 1095 StringRef Msg; 1096 if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg)) 1097 return; 1098 1099 StringRef DiagTypeStr; 1100 if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr)) 1101 return; 1102 1103 DiagnoseIfAttr::DiagnosticType DiagType; 1104 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) { 1105 S.Diag(AL.getArgAsExpr(2)->getBeginLoc(), 1106 diag::err_diagnose_if_invalid_diagnostic_type); 1107 return; 1108 } 1109 1110 bool ArgDependent = false; 1111 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 1112 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond); 1113 D->addAttr(::new (S.Context) DiagnoseIfAttr( 1114 S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D))); 1115 } 1116 1117 static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1118 static constexpr const StringRef kWildcard = "*"; 1119 1120 llvm::SmallVector<StringRef, 16> Names; 1121 bool HasWildcard = false; 1122 1123 const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) { 1124 if (Name == kWildcard) 1125 HasWildcard = true; 1126 Names.push_back(Name); 1127 }; 1128 1129 // Add previously defined attributes. 1130 if (const auto *NBA = D->getAttr<NoBuiltinAttr>()) 1131 for (StringRef BuiltinName : NBA->builtinNames()) 1132 AddBuiltinName(BuiltinName); 1133 1134 // Add current attributes. 1135 if (AL.getNumArgs() == 0) 1136 AddBuiltinName(kWildcard); 1137 else 1138 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 1139 StringRef BuiltinName; 1140 SourceLocation LiteralLoc; 1141 if (!S.checkStringLiteralArgumentAttr(AL, I, BuiltinName, &LiteralLoc)) 1142 return; 1143 1144 if (Builtin::Context::isBuiltinFunc(BuiltinName)) 1145 AddBuiltinName(BuiltinName); 1146 else 1147 S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name) 1148 << BuiltinName << AL; 1149 } 1150 1151 // Repeating the same attribute is fine. 1152 llvm::sort(Names); 1153 Names.erase(std::unique(Names.begin(), Names.end()), Names.end()); 1154 1155 // Empty no_builtin must be on its own. 1156 if (HasWildcard && Names.size() > 1) 1157 S.Diag(D->getLocation(), 1158 diag::err_attribute_no_builtin_wildcard_or_builtin_name) 1159 << AL; 1160 1161 if (D->hasAttr<NoBuiltinAttr>()) 1162 D->dropAttr<NoBuiltinAttr>(); 1163 D->addAttr(::new (S.Context) 1164 NoBuiltinAttr(S.Context, AL, Names.data(), Names.size())); 1165 } 1166 1167 static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1168 if (D->hasAttr<PassObjectSizeAttr>()) { 1169 S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL; 1170 return; 1171 } 1172 1173 Expr *E = AL.getArgAsExpr(0); 1174 uint32_t Type; 1175 if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1)) 1176 return; 1177 1178 // pass_object_size's argument is passed in as the second argument of 1179 // __builtin_object_size. So, it has the same constraints as that second 1180 // argument; namely, it must be in the range [0, 3]. 1181 if (Type > 3) { 1182 S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range) 1183 << AL << 0 << 3 << E->getSourceRange(); 1184 return; 1185 } 1186 1187 // pass_object_size is only supported on constant pointer parameters; as a 1188 // kindness to users, we allow the parameter to be non-const for declarations. 1189 // At this point, we have no clue if `D` belongs to a function declaration or 1190 // definition, so we defer the constness check until later. 1191 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) { 1192 S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1; 1193 return; 1194 } 1195 1196 D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type)); 1197 } 1198 1199 static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1200 ConsumableAttr::ConsumedState DefaultState; 1201 1202 if (AL.isArgIdent(0)) { 1203 IdentifierLoc *IL = AL.getArgAsIdent(0); 1204 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(), 1205 DefaultState)) { 1206 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL 1207 << IL->Ident; 1208 return; 1209 } 1210 } else { 1211 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 1212 << AL << AANT_ArgumentIdentifier; 1213 return; 1214 } 1215 1216 D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState)); 1217 } 1218 1219 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD, 1220 const ParsedAttr &AL) { 1221 QualType ThisType = MD->getThisType()->getPointeeType(); 1222 1223 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) { 1224 if (!RD->hasAttr<ConsumableAttr>()) { 1225 S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD; 1226 1227 return false; 1228 } 1229 } 1230 1231 return true; 1232 } 1233 1234 static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1235 if (!AL.checkAtLeastNumArgs(S, 1)) 1236 return; 1237 1238 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL)) 1239 return; 1240 1241 SmallVector<CallableWhenAttr::ConsumedState, 3> States; 1242 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) { 1243 CallableWhenAttr::ConsumedState CallableState; 1244 1245 StringRef StateString; 1246 SourceLocation Loc; 1247 if (AL.isArgIdent(ArgIndex)) { 1248 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex); 1249 StateString = Ident->Ident->getName(); 1250 Loc = Ident->Loc; 1251 } else { 1252 if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc)) 1253 return; 1254 } 1255 1256 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString, 1257 CallableState)) { 1258 S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString; 1259 return; 1260 } 1261 1262 States.push_back(CallableState); 1263 } 1264 1265 D->addAttr(::new (S.Context) 1266 CallableWhenAttr(S.Context, AL, States.data(), States.size())); 1267 } 1268 1269 static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1270 ParamTypestateAttr::ConsumedState ParamState; 1271 1272 if (AL.isArgIdent(0)) { 1273 IdentifierLoc *Ident = AL.getArgAsIdent(0); 1274 StringRef StateString = Ident->Ident->getName(); 1275 1276 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString, 1277 ParamState)) { 1278 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 1279 << AL << StateString; 1280 return; 1281 } 1282 } else { 1283 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 1284 << AL << AANT_ArgumentIdentifier; 1285 return; 1286 } 1287 1288 // FIXME: This check is currently being done in the analysis. It can be 1289 // enabled here only after the parser propagates attributes at 1290 // template specialization definition, not declaration. 1291 //QualType ReturnType = cast<ParmVarDecl>(D)->getType(); 1292 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 1293 // 1294 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 1295 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) << 1296 // ReturnType.getAsString(); 1297 // return; 1298 //} 1299 1300 D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState)); 1301 } 1302 1303 static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1304 ReturnTypestateAttr::ConsumedState ReturnState; 1305 1306 if (AL.isArgIdent(0)) { 1307 IdentifierLoc *IL = AL.getArgAsIdent(0); 1308 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(), 1309 ReturnState)) { 1310 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL 1311 << IL->Ident; 1312 return; 1313 } 1314 } else { 1315 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 1316 << AL << AANT_ArgumentIdentifier; 1317 return; 1318 } 1319 1320 // FIXME: This check is currently being done in the analysis. It can be 1321 // enabled here only after the parser propagates attributes at 1322 // template specialization definition, not declaration. 1323 //QualType ReturnType; 1324 // 1325 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) { 1326 // ReturnType = Param->getType(); 1327 // 1328 //} else if (const CXXConstructorDecl *Constructor = 1329 // dyn_cast<CXXConstructorDecl>(D)) { 1330 // ReturnType = Constructor->getThisType()->getPointeeType(); 1331 // 1332 //} else { 1333 // 1334 // ReturnType = cast<FunctionDecl>(D)->getCallResultType(); 1335 //} 1336 // 1337 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 1338 // 1339 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 1340 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << 1341 // ReturnType.getAsString(); 1342 // return; 1343 //} 1344 1345 D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState)); 1346 } 1347 1348 static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1349 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL)) 1350 return; 1351 1352 SetTypestateAttr::ConsumedState NewState; 1353 if (AL.isArgIdent(0)) { 1354 IdentifierLoc *Ident = AL.getArgAsIdent(0); 1355 StringRef Param = Ident->Ident->getName(); 1356 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) { 1357 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL 1358 << Param; 1359 return; 1360 } 1361 } else { 1362 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 1363 << AL << AANT_ArgumentIdentifier; 1364 return; 1365 } 1366 1367 D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState)); 1368 } 1369 1370 static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1371 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL)) 1372 return; 1373 1374 TestTypestateAttr::ConsumedState TestState; 1375 if (AL.isArgIdent(0)) { 1376 IdentifierLoc *Ident = AL.getArgAsIdent(0); 1377 StringRef Param = Ident->Ident->getName(); 1378 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) { 1379 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL 1380 << Param; 1381 return; 1382 } 1383 } else { 1384 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 1385 << AL << AANT_ArgumentIdentifier; 1386 return; 1387 } 1388 1389 D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState)); 1390 } 1391 1392 static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1393 // Remember this typedef decl, we will need it later for diagnostics. 1394 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D)); 1395 } 1396 1397 static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1398 if (auto *TD = dyn_cast<TagDecl>(D)) 1399 TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL)); 1400 else if (auto *FD = dyn_cast<FieldDecl>(D)) { 1401 bool BitfieldByteAligned = (!FD->getType()->isDependentType() && 1402 !FD->getType()->isIncompleteType() && 1403 FD->isBitField() && 1404 S.Context.getTypeAlign(FD->getType()) <= 8); 1405 1406 if (S.getASTContext().getTargetInfo().getTriple().isPS4()) { 1407 if (BitfieldByteAligned) 1408 // The PS4 target needs to maintain ABI backwards compatibility. 1409 S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type) 1410 << AL << FD->getType(); 1411 else 1412 FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL)); 1413 } else { 1414 // Report warning about changed offset in the newer compiler versions. 1415 if (BitfieldByteAligned) 1416 S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield); 1417 1418 FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL)); 1419 } 1420 1421 } else 1422 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL; 1423 } 1424 1425 static void handlePreferredName(Sema &S, Decl *D, const ParsedAttr &AL) { 1426 auto *RD = cast<CXXRecordDecl>(D); 1427 ClassTemplateDecl *CTD = RD->getDescribedClassTemplate(); 1428 assert(CTD && "attribute does not appertain to this declaration"); 1429 1430 ParsedType PT = AL.getTypeArg(); 1431 TypeSourceInfo *TSI = nullptr; 1432 QualType T = S.GetTypeFromParser(PT, &TSI); 1433 if (!TSI) 1434 TSI = S.Context.getTrivialTypeSourceInfo(T, AL.getLoc()); 1435 1436 if (!T.hasQualifiers() && T->isTypedefNameType()) { 1437 // Find the template name, if this type names a template specialization. 1438 const TemplateDecl *Template = nullptr; 1439 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1440 T->getAsCXXRecordDecl())) { 1441 Template = CTSD->getSpecializedTemplate(); 1442 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) { 1443 while (TST && TST->isTypeAlias()) 1444 TST = TST->getAliasedType()->getAs<TemplateSpecializationType>(); 1445 if (TST) 1446 Template = TST->getTemplateName().getAsTemplateDecl(); 1447 } 1448 1449 if (Template && declaresSameEntity(Template, CTD)) { 1450 D->addAttr(::new (S.Context) PreferredNameAttr(S.Context, AL, TSI)); 1451 return; 1452 } 1453 } 1454 1455 S.Diag(AL.getLoc(), diag::err_attribute_preferred_name_arg_invalid) 1456 << T << CTD; 1457 if (const auto *TT = T->getAs<TypedefType>()) 1458 S.Diag(TT->getDecl()->getLocation(), diag::note_entity_declared_at) 1459 << TT->getDecl(); 1460 } 1461 1462 static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) { 1463 // The IBOutlet/IBOutletCollection attributes only apply to instance 1464 // variables or properties of Objective-C classes. The outlet must also 1465 // have an object reference type. 1466 if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) { 1467 if (!VD->getType()->getAs<ObjCObjectPointerType>()) { 1468 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type) 1469 << AL << VD->getType() << 0; 1470 return false; 1471 } 1472 } 1473 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) { 1474 if (!PD->getType()->getAs<ObjCObjectPointerType>()) { 1475 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type) 1476 << AL << PD->getType() << 1; 1477 return false; 1478 } 1479 } 1480 else { 1481 S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL; 1482 return false; 1483 } 1484 1485 return true; 1486 } 1487 1488 static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) { 1489 if (!checkIBOutletCommon(S, D, AL)) 1490 return; 1491 1492 D->addAttr(::new (S.Context) IBOutletAttr(S.Context, AL)); 1493 } 1494 1495 static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) { 1496 1497 // The iboutletcollection attribute can have zero or one arguments. 1498 if (AL.getNumArgs() > 1) { 1499 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; 1500 return; 1501 } 1502 1503 if (!checkIBOutletCommon(S, D, AL)) 1504 return; 1505 1506 ParsedType PT; 1507 1508 if (AL.hasParsedType()) 1509 PT = AL.getTypeArg(); 1510 else { 1511 PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(), 1512 S.getScopeForContext(D->getDeclContext()->getParent())); 1513 if (!PT) { 1514 S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject"; 1515 return; 1516 } 1517 } 1518 1519 TypeSourceInfo *QTLoc = nullptr; 1520 QualType QT = S.GetTypeFromParser(PT, &QTLoc); 1521 if (!QTLoc) 1522 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc()); 1523 1524 // Diagnose use of non-object type in iboutletcollection attribute. 1525 // FIXME. Gnu attribute extension ignores use of builtin types in 1526 // attributes. So, __attribute__((iboutletcollection(char))) will be 1527 // treated as __attribute__((iboutletcollection())). 1528 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) { 1529 S.Diag(AL.getLoc(), 1530 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype 1531 : diag::err_iboutletcollection_type) << QT; 1532 return; 1533 } 1534 1535 D->addAttr(::new (S.Context) IBOutletCollectionAttr(S.Context, AL, QTLoc)); 1536 } 1537 1538 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) { 1539 if (RefOkay) { 1540 if (T->isReferenceType()) 1541 return true; 1542 } else { 1543 T = T.getNonReferenceType(); 1544 } 1545 1546 // The nonnull attribute, and other similar attributes, can be applied to a 1547 // transparent union that contains a pointer type. 1548 if (const RecordType *UT = T->getAsUnionType()) { 1549 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) { 1550 RecordDecl *UD = UT->getDecl(); 1551 for (const auto *I : UD->fields()) { 1552 QualType QT = I->getType(); 1553 if (QT->isAnyPointerType() || QT->isBlockPointerType()) 1554 return true; 1555 } 1556 } 1557 } 1558 1559 return T->isAnyPointerType() || T->isBlockPointerType(); 1560 } 1561 1562 static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL, 1563 SourceRange AttrParmRange, 1564 SourceRange TypeRange, 1565 bool isReturnValue = false) { 1566 if (!S.isValidPointerAttrType(T)) { 1567 if (isReturnValue) 1568 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) 1569 << AL << AttrParmRange << TypeRange; 1570 else 1571 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only) 1572 << AL << AttrParmRange << TypeRange << 0; 1573 return false; 1574 } 1575 return true; 1576 } 1577 1578 static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1579 SmallVector<ParamIdx, 8> NonNullArgs; 1580 for (unsigned I = 0; I < AL.getNumArgs(); ++I) { 1581 Expr *Ex = AL.getArgAsExpr(I); 1582 ParamIdx Idx; 1583 if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx)) 1584 return; 1585 1586 // Is the function argument a pointer type? 1587 if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) && 1588 !attrNonNullArgCheck( 1589 S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL, 1590 Ex->getSourceRange(), 1591 getFunctionOrMethodParamRange(D, Idx.getASTIndex()))) 1592 continue; 1593 1594 NonNullArgs.push_back(Idx); 1595 } 1596 1597 // If no arguments were specified to __attribute__((nonnull)) then all pointer 1598 // arguments have a nonnull attribute; warn if there aren't any. Skip this 1599 // check if the attribute came from a macro expansion or a template 1600 // instantiation. 1601 if (NonNullArgs.empty() && AL.getLoc().isFileID() && 1602 !S.inTemplateInstantiation()) { 1603 bool AnyPointers = isFunctionOrMethodVariadic(D); 1604 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); 1605 I != E && !AnyPointers; ++I) { 1606 QualType T = getFunctionOrMethodParamType(D, I); 1607 if (T->isDependentType() || S.isValidPointerAttrType(T)) 1608 AnyPointers = true; 1609 } 1610 1611 if (!AnyPointers) 1612 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers); 1613 } 1614 1615 ParamIdx *Start = NonNullArgs.data(); 1616 unsigned Size = NonNullArgs.size(); 1617 llvm::array_pod_sort(Start, Start + Size); 1618 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size)); 1619 } 1620 1621 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D, 1622 const ParsedAttr &AL) { 1623 if (AL.getNumArgs() > 0) { 1624 if (D->getFunctionType()) { 1625 handleNonNullAttr(S, D, AL); 1626 } else { 1627 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args) 1628 << D->getSourceRange(); 1629 } 1630 return; 1631 } 1632 1633 // Is the argument a pointer type? 1634 if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(), 1635 D->getSourceRange())) 1636 return; 1637 1638 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0)); 1639 } 1640 1641 static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1642 QualType ResultType = getFunctionOrMethodResultType(D); 1643 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1644 if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR, 1645 /* isReturnValue */ true)) 1646 return; 1647 1648 D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL)); 1649 } 1650 1651 static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1652 if (D->isInvalidDecl()) 1653 return; 1654 1655 // noescape only applies to pointer types. 1656 QualType T = cast<ParmVarDecl>(D)->getType(); 1657 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) { 1658 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only) 1659 << AL << AL.getRange() << 0; 1660 return; 1661 } 1662 1663 D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL)); 1664 } 1665 1666 static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1667 Expr *E = AL.getArgAsExpr(0), 1668 *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr; 1669 S.AddAssumeAlignedAttr(D, AL, E, OE); 1670 } 1671 1672 static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1673 S.AddAllocAlignAttr(D, AL, AL.getArgAsExpr(0)); 1674 } 1675 1676 void Sema::AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 1677 Expr *OE) { 1678 QualType ResultType = getFunctionOrMethodResultType(D); 1679 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1680 1681 AssumeAlignedAttr TmpAttr(Context, CI, E, OE); 1682 SourceLocation AttrLoc = TmpAttr.getLocation(); 1683 1684 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) { 1685 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) 1686 << &TmpAttr << TmpAttr.getRange() << SR; 1687 return; 1688 } 1689 1690 if (!E->isValueDependent()) { 1691 Optional<llvm::APSInt> I = llvm::APSInt(64); 1692 if (!(I = E->getIntegerConstantExpr(Context))) { 1693 if (OE) 1694 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1695 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant 1696 << E->getSourceRange(); 1697 else 1698 Diag(AttrLoc, diag::err_attribute_argument_type) 1699 << &TmpAttr << AANT_ArgumentIntegerConstant 1700 << E->getSourceRange(); 1701 return; 1702 } 1703 1704 if (!I->isPowerOf2()) { 1705 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 1706 << E->getSourceRange(); 1707 return; 1708 } 1709 1710 if (*I > Sema::MaximumAlignment) 1711 Diag(CI.getLoc(), diag::warn_assume_aligned_too_great) 1712 << CI.getRange() << Sema::MaximumAlignment; 1713 } 1714 1715 if (OE && !OE->isValueDependent() && !OE->isIntegerConstantExpr(Context)) { 1716 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1717 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant 1718 << OE->getSourceRange(); 1719 return; 1720 } 1721 1722 D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE)); 1723 } 1724 1725 void Sema::AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, 1726 Expr *ParamExpr) { 1727 QualType ResultType = getFunctionOrMethodResultType(D); 1728 1729 AllocAlignAttr TmpAttr(Context, CI, ParamIdx()); 1730 SourceLocation AttrLoc = CI.getLoc(); 1731 1732 if (!ResultType->isDependentType() && 1733 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) { 1734 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) 1735 << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D); 1736 return; 1737 } 1738 1739 ParamIdx Idx; 1740 const auto *FuncDecl = cast<FunctionDecl>(D); 1741 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr, 1742 /*AttrArgNum=*/1, ParamExpr, Idx)) 1743 return; 1744 1745 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex()); 1746 if (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 1747 !Ty->isAlignValT()) { 1748 Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only) 1749 << &TmpAttr 1750 << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange(); 1751 return; 1752 } 1753 1754 D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx)); 1755 } 1756 1757 /// Check if \p AssumptionStr is a known assumption and warn if not. 1758 static void checkAssumptionAttr(Sema &S, SourceLocation Loc, 1759 StringRef AssumptionStr) { 1760 if (llvm::KnownAssumptionStrings.count(AssumptionStr)) 1761 return; 1762 1763 unsigned BestEditDistance = 3; 1764 StringRef Suggestion; 1765 for (const auto &KnownAssumptionIt : llvm::KnownAssumptionStrings) { 1766 unsigned EditDistance = 1767 AssumptionStr.edit_distance(KnownAssumptionIt.getKey()); 1768 if (EditDistance < BestEditDistance) { 1769 Suggestion = KnownAssumptionIt.getKey(); 1770 BestEditDistance = EditDistance; 1771 } 1772 } 1773 1774 if (!Suggestion.empty()) 1775 S.Diag(Loc, diag::warn_assume_attribute_string_unknown_suggested) 1776 << AssumptionStr << Suggestion; 1777 else 1778 S.Diag(Loc, diag::warn_assume_attribute_string_unknown) << AssumptionStr; 1779 } 1780 1781 static void handleAssumumptionAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1782 // Handle the case where the attribute has a text message. 1783 StringRef Str; 1784 SourceLocation AttrStrLoc; 1785 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &AttrStrLoc)) 1786 return; 1787 1788 checkAssumptionAttr(S, AttrStrLoc, Str); 1789 1790 D->addAttr(::new (S.Context) AssumptionAttr(S.Context, AL, Str)); 1791 } 1792 1793 /// Normalize the attribute, __foo__ becomes foo. 1794 /// Returns true if normalization was applied. 1795 static bool normalizeName(StringRef &AttrName) { 1796 if (AttrName.size() > 4 && AttrName.startswith("__") && 1797 AttrName.endswith("__")) { 1798 AttrName = AttrName.drop_front(2).drop_back(2); 1799 return true; 1800 } 1801 return false; 1802 } 1803 1804 static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1805 // This attribute must be applied to a function declaration. The first 1806 // argument to the attribute must be an identifier, the name of the resource, 1807 // for example: malloc. The following arguments must be argument indexes, the 1808 // arguments must be of integer type for Returns, otherwise of pointer type. 1809 // The difference between Holds and Takes is that a pointer may still be used 1810 // after being held. free() should be __attribute((ownership_takes)), whereas 1811 // a list append function may well be __attribute((ownership_holds)). 1812 1813 if (!AL.isArgIdent(0)) { 1814 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 1815 << AL << 1 << AANT_ArgumentIdentifier; 1816 return; 1817 } 1818 1819 // Figure out our Kind. 1820 OwnershipAttr::OwnershipKind K = 1821 OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind(); 1822 1823 // Check arguments. 1824 switch (K) { 1825 case OwnershipAttr::Takes: 1826 case OwnershipAttr::Holds: 1827 if (AL.getNumArgs() < 2) { 1828 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2; 1829 return; 1830 } 1831 break; 1832 case OwnershipAttr::Returns: 1833 if (AL.getNumArgs() > 2) { 1834 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1; 1835 return; 1836 } 1837 break; 1838 } 1839 1840 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident; 1841 1842 StringRef ModuleName = Module->getName(); 1843 if (normalizeName(ModuleName)) { 1844 Module = &S.PP.getIdentifierTable().get(ModuleName); 1845 } 1846 1847 SmallVector<ParamIdx, 8> OwnershipArgs; 1848 for (unsigned i = 1; i < AL.getNumArgs(); ++i) { 1849 Expr *Ex = AL.getArgAsExpr(i); 1850 ParamIdx Idx; 1851 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx)) 1852 return; 1853 1854 // Is the function argument a pointer type? 1855 QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex()); 1856 int Err = -1; // No error 1857 switch (K) { 1858 case OwnershipAttr::Takes: 1859 case OwnershipAttr::Holds: 1860 if (!T->isAnyPointerType() && !T->isBlockPointerType()) 1861 Err = 0; 1862 break; 1863 case OwnershipAttr::Returns: 1864 if (!T->isIntegerType()) 1865 Err = 1; 1866 break; 1867 } 1868 if (-1 != Err) { 1869 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err 1870 << Ex->getSourceRange(); 1871 return; 1872 } 1873 1874 // Check we don't have a conflict with another ownership attribute. 1875 for (const auto *I : D->specific_attrs<OwnershipAttr>()) { 1876 // Cannot have two ownership attributes of different kinds for the same 1877 // index. 1878 if (I->getOwnKind() != K && I->args_end() != 1879 std::find(I->args_begin(), I->args_end(), Idx)) { 1880 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I; 1881 return; 1882 } else if (K == OwnershipAttr::Returns && 1883 I->getOwnKind() == OwnershipAttr::Returns) { 1884 // A returns attribute conflicts with any other returns attribute using 1885 // a different index. 1886 if (!llvm::is_contained(I->args(), Idx)) { 1887 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch) 1888 << I->args_begin()->getSourceIndex(); 1889 if (I->args_size()) 1890 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch) 1891 << Idx.getSourceIndex() << Ex->getSourceRange(); 1892 return; 1893 } 1894 } 1895 } 1896 OwnershipArgs.push_back(Idx); 1897 } 1898 1899 ParamIdx *Start = OwnershipArgs.data(); 1900 unsigned Size = OwnershipArgs.size(); 1901 llvm::array_pod_sort(Start, Start + Size); 1902 D->addAttr(::new (S.Context) 1903 OwnershipAttr(S.Context, AL, Module, Start, Size)); 1904 } 1905 1906 static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1907 // Check the attribute arguments. 1908 if (AL.getNumArgs() > 1) { 1909 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; 1910 return; 1911 } 1912 1913 // gcc rejects 1914 // class c { 1915 // static int a __attribute__((weakref ("v2"))); 1916 // static int b() __attribute__((weakref ("f3"))); 1917 // }; 1918 // and ignores the attributes of 1919 // void f(void) { 1920 // static int a __attribute__((weakref ("v2"))); 1921 // } 1922 // we reject them 1923 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext(); 1924 if (!Ctx->isFileContext()) { 1925 S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context) 1926 << cast<NamedDecl>(D); 1927 return; 1928 } 1929 1930 // The GCC manual says 1931 // 1932 // At present, a declaration to which `weakref' is attached can only 1933 // be `static'. 1934 // 1935 // It also says 1936 // 1937 // Without a TARGET, 1938 // given as an argument to `weakref' or to `alias', `weakref' is 1939 // equivalent to `weak'. 1940 // 1941 // gcc 4.4.1 will accept 1942 // int a7 __attribute__((weakref)); 1943 // as 1944 // int a7 __attribute__((weak)); 1945 // This looks like a bug in gcc. We reject that for now. We should revisit 1946 // it if this behaviour is actually used. 1947 1948 // GCC rejects 1949 // static ((alias ("y"), weakref)). 1950 // Should we? How to check that weakref is before or after alias? 1951 1952 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead 1953 // of transforming it into an AliasAttr. The WeakRefAttr never uses the 1954 // StringRef parameter it was given anyway. 1955 StringRef Str; 1956 if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str)) 1957 // GCC will accept anything as the argument of weakref. Should we 1958 // check for an existing decl? 1959 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str)); 1960 1961 D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL)); 1962 } 1963 1964 static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1965 StringRef Str; 1966 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 1967 return; 1968 1969 // Aliases should be on declarations, not definitions. 1970 const auto *FD = cast<FunctionDecl>(D); 1971 if (FD->isThisDeclarationADefinition()) { 1972 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1; 1973 return; 1974 } 1975 1976 D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str)); 1977 } 1978 1979 static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 1980 StringRef Str; 1981 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 1982 return; 1983 1984 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 1985 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin); 1986 return; 1987 } 1988 if (S.Context.getTargetInfo().getTriple().isNVPTX()) { 1989 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx); 1990 } 1991 1992 // Aliases should be on declarations, not definitions. 1993 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 1994 if (FD->isThisDeclarationADefinition()) { 1995 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0; 1996 return; 1997 } 1998 } else { 1999 const auto *VD = cast<VarDecl>(D); 2000 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) { 2001 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0; 2002 return; 2003 } 2004 } 2005 2006 // Mark target used to prevent unneeded-internal-declaration warnings. 2007 if (!S.LangOpts.CPlusPlus) { 2008 // FIXME: demangle Str for C++, as the attribute refers to the mangled 2009 // linkage name, not the pre-mangled identifier. 2010 const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc()); 2011 LookupResult LR(S, target, Sema::LookupOrdinaryName); 2012 if (S.LookupQualifiedName(LR, S.getCurLexicalContext())) 2013 for (NamedDecl *ND : LR) 2014 ND->markUsed(S.Context); 2015 } 2016 2017 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str)); 2018 } 2019 2020 static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2021 StringRef Model; 2022 SourceLocation LiteralLoc; 2023 // Check that it is a string. 2024 if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc)) 2025 return; 2026 2027 // Check that the value. 2028 if (Model != "global-dynamic" && Model != "local-dynamic" 2029 && Model != "initial-exec" && Model != "local-exec") { 2030 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg); 2031 return; 2032 } 2033 2034 if (S.Context.getTargetInfo().getTriple().isOSAIX() && 2035 Model != "global-dynamic") { 2036 S.Diag(LiteralLoc, diag::err_aix_attr_unsupported_tls_model) << Model; 2037 return; 2038 } 2039 2040 D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model)); 2041 } 2042 2043 static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2044 QualType ResultType = getFunctionOrMethodResultType(D); 2045 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) { 2046 D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL)); 2047 return; 2048 } 2049 2050 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) 2051 << AL << getFunctionOrMethodResultSourceRange(D); 2052 } 2053 2054 static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2055 // Ensure we don't combine these with themselves, since that causes some 2056 // confusing behavior. 2057 if (AL.getParsedKind() == ParsedAttr::AT_CPUDispatch) { 2058 if (checkAttrMutualExclusion<CPUSpecificAttr>(S, D, AL)) 2059 return; 2060 2061 if (const auto *Other = D->getAttr<CPUDispatchAttr>()) { 2062 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL; 2063 S.Diag(Other->getLocation(), diag::note_conflicting_attribute); 2064 return; 2065 } 2066 } else if (AL.getParsedKind() == ParsedAttr::AT_CPUSpecific) { 2067 if (checkAttrMutualExclusion<CPUDispatchAttr>(S, D, AL)) 2068 return; 2069 2070 if (const auto *Other = D->getAttr<CPUSpecificAttr>()) { 2071 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL; 2072 S.Diag(Other->getLocation(), diag::note_conflicting_attribute); 2073 return; 2074 } 2075 } 2076 2077 FunctionDecl *FD = cast<FunctionDecl>(D); 2078 2079 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 2080 if (MD->getParent()->isLambda()) { 2081 S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL; 2082 return; 2083 } 2084 } 2085 2086 if (!AL.checkAtLeastNumArgs(S, 1)) 2087 return; 2088 2089 SmallVector<IdentifierInfo *, 8> CPUs; 2090 for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) { 2091 if (!AL.isArgIdent(ArgNo)) { 2092 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 2093 << AL << AANT_ArgumentIdentifier; 2094 return; 2095 } 2096 2097 IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo); 2098 StringRef CPUName = CPUArg->Ident->getName().trim(); 2099 2100 if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName)) { 2101 S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value) 2102 << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch); 2103 return; 2104 } 2105 2106 const TargetInfo &Target = S.Context.getTargetInfo(); 2107 if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) { 2108 return Target.CPUSpecificManglingCharacter(CPUName) == 2109 Target.CPUSpecificManglingCharacter(Cur->getName()); 2110 })) { 2111 S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries); 2112 return; 2113 } 2114 CPUs.push_back(CPUArg->Ident); 2115 } 2116 2117 FD->setIsMultiVersion(true); 2118 if (AL.getKind() == ParsedAttr::AT_CPUSpecific) 2119 D->addAttr(::new (S.Context) 2120 CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size())); 2121 else 2122 D->addAttr(::new (S.Context) 2123 CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size())); 2124 } 2125 2126 static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2127 if (S.LangOpts.CPlusPlus) { 2128 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang) 2129 << AL << AttributeLangSupport::Cpp; 2130 return; 2131 } 2132 2133 D->addAttr(::new (S.Context) CommonAttr(S.Context, AL)); 2134 } 2135 2136 static void handleCmseNSEntryAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2137 if (S.LangOpts.CPlusPlus && !D->getDeclContext()->isExternCContext()) { 2138 S.Diag(AL.getLoc(), diag::err_attribute_not_clinkage) << AL; 2139 return; 2140 } 2141 2142 const auto *FD = cast<FunctionDecl>(D); 2143 if (!FD->isExternallyVisible()) { 2144 S.Diag(AL.getLoc(), diag::warn_attribute_cmse_entry_static); 2145 return; 2146 } 2147 2148 D->addAttr(::new (S.Context) CmseNSEntryAttr(S.Context, AL)); 2149 } 2150 2151 static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2152 if (AL.isDeclspecAttribute()) { 2153 const auto &Triple = S.getASTContext().getTargetInfo().getTriple(); 2154 const auto &Arch = Triple.getArch(); 2155 if (Arch != llvm::Triple::x86 && 2156 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) { 2157 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch) 2158 << AL << Triple.getArchName(); 2159 return; 2160 } 2161 } 2162 2163 D->addAttr(::new (S.Context) NakedAttr(S.Context, AL)); 2164 } 2165 2166 static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) { 2167 if (hasDeclarator(D)) return; 2168 2169 if (!isa<ObjCMethodDecl>(D)) { 2170 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type) 2171 << Attrs << ExpectedFunctionOrMethod; 2172 return; 2173 } 2174 2175 D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs)); 2176 } 2177 2178 static void handleStandardNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &A) { 2179 // The [[_Noreturn]] spelling is deprecated in C2x, so if that was used, 2180 // issue an appropriate diagnostic. 2181 if (!S.getLangOpts().CPlusPlus && 2182 A.getSemanticSpelling() == CXX11NoReturnAttr::C2x_Noreturn) 2183 S.Diag(A.getLoc(), diag::warn_deprecated_noreturn_spelling) << A.getRange(); 2184 2185 D->addAttr(::new (S.Context) CXX11NoReturnAttr(S.Context, A)); 2186 } 2187 2188 static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) { 2189 if (!S.getLangOpts().CFProtectionBranch) 2190 S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored); 2191 else 2192 handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs); 2193 } 2194 2195 bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) { 2196 if (!Attrs.checkExactlyNumArgs(*this, 0)) { 2197 Attrs.setInvalid(); 2198 return true; 2199 } 2200 2201 return false; 2202 } 2203 2204 bool Sema::CheckAttrTarget(const ParsedAttr &AL) { 2205 // Check whether the attribute is valid on the current target. 2206 if (!AL.existsInTarget(Context.getTargetInfo())) { 2207 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) 2208 << AL << AL.getRange(); 2209 AL.setInvalid(); 2210 return true; 2211 } 2212 2213 return false; 2214 } 2215 2216 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2217 2218 // The checking path for 'noreturn' and 'analyzer_noreturn' are different 2219 // because 'analyzer_noreturn' does not impact the type. 2220 if (!isFunctionOrMethodOrBlock(D)) { 2221 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2222 if (!VD || (!VD->getType()->isBlockPointerType() && 2223 !VD->getType()->isFunctionPointerType())) { 2224 S.Diag(AL.getLoc(), AL.isStandardAttributeSyntax() 2225 ? diag::err_attribute_wrong_decl_type 2226 : diag::warn_attribute_wrong_decl_type) 2227 << AL << ExpectedFunctionMethodOrBlock; 2228 return; 2229 } 2230 } 2231 2232 D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL)); 2233 } 2234 2235 // PS3 PPU-specific. 2236 static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2237 /* 2238 Returning a Vector Class in Registers 2239 2240 According to the PPU ABI specifications, a class with a single member of 2241 vector type is returned in memory when used as the return value of a 2242 function. 2243 This results in inefficient code when implementing vector classes. To return 2244 the value in a single vector register, add the vecreturn attribute to the 2245 class definition. This attribute is also applicable to struct types. 2246 2247 Example: 2248 2249 struct Vector 2250 { 2251 __vector float xyzw; 2252 } __attribute__((vecreturn)); 2253 2254 Vector Add(Vector lhs, Vector rhs) 2255 { 2256 Vector result; 2257 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw); 2258 return result; // This will be returned in a register 2259 } 2260 */ 2261 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) { 2262 S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A; 2263 return; 2264 } 2265 2266 const auto *R = cast<RecordDecl>(D); 2267 int count = 0; 2268 2269 if (!isa<CXXRecordDecl>(R)) { 2270 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 2271 return; 2272 } 2273 2274 if (!cast<CXXRecordDecl>(R)->isPOD()) { 2275 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record); 2276 return; 2277 } 2278 2279 for (const auto *I : R->fields()) { 2280 if ((count == 1) || !I->getType()->isVectorType()) { 2281 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 2282 return; 2283 } 2284 count++; 2285 } 2286 2287 D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL)); 2288 } 2289 2290 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D, 2291 const ParsedAttr &AL) { 2292 if (isa<ParmVarDecl>(D)) { 2293 // [[carries_dependency]] can only be applied to a parameter if it is a 2294 // parameter of a function declaration or lambda. 2295 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) { 2296 S.Diag(AL.getLoc(), 2297 diag::err_carries_dependency_param_not_function_decl); 2298 return; 2299 } 2300 } 2301 2302 D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL)); 2303 } 2304 2305 static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2306 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName(); 2307 2308 // If this is spelled as the standard C++17 attribute, but not in C++17, warn 2309 // about using it as an extension. 2310 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr) 2311 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL; 2312 2313 D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL)); 2314 } 2315 2316 static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2317 uint32_t priority = ConstructorAttr::DefaultPriority; 2318 if (AL.getNumArgs() && 2319 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)) 2320 return; 2321 2322 D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority)); 2323 } 2324 2325 static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2326 uint32_t priority = DestructorAttr::DefaultPriority; 2327 if (AL.getNumArgs() && 2328 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)) 2329 return; 2330 2331 D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority)); 2332 } 2333 2334 template <typename AttrTy> 2335 static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) { 2336 // Handle the case where the attribute has a text message. 2337 StringRef Str; 2338 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str)) 2339 return; 2340 2341 D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str)); 2342 } 2343 2344 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D, 2345 const ParsedAttr &AL) { 2346 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) { 2347 S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition) 2348 << AL << AL.getRange(); 2349 return; 2350 } 2351 2352 D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL)); 2353 } 2354 2355 static bool checkAvailabilityAttr(Sema &S, SourceRange Range, 2356 IdentifierInfo *Platform, 2357 VersionTuple Introduced, 2358 VersionTuple Deprecated, 2359 VersionTuple Obsoleted) { 2360 StringRef PlatformName 2361 = AvailabilityAttr::getPrettyPlatformName(Platform->getName()); 2362 if (PlatformName.empty()) 2363 PlatformName = Platform->getName(); 2364 2365 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all 2366 // of these steps are needed). 2367 if (!Introduced.empty() && !Deprecated.empty() && 2368 !(Introduced <= Deprecated)) { 2369 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 2370 << 1 << PlatformName << Deprecated.getAsString() 2371 << 0 << Introduced.getAsString(); 2372 return true; 2373 } 2374 2375 if (!Introduced.empty() && !Obsoleted.empty() && 2376 !(Introduced <= Obsoleted)) { 2377 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 2378 << 2 << PlatformName << Obsoleted.getAsString() 2379 << 0 << Introduced.getAsString(); 2380 return true; 2381 } 2382 2383 if (!Deprecated.empty() && !Obsoleted.empty() && 2384 !(Deprecated <= Obsoleted)) { 2385 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 2386 << 2 << PlatformName << Obsoleted.getAsString() 2387 << 1 << Deprecated.getAsString(); 2388 return true; 2389 } 2390 2391 return false; 2392 } 2393 2394 /// Check whether the two versions match. 2395 /// 2396 /// If either version tuple is empty, then they are assumed to match. If 2397 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y. 2398 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y, 2399 bool BeforeIsOkay) { 2400 if (X.empty() || Y.empty()) 2401 return true; 2402 2403 if (X == Y) 2404 return true; 2405 2406 if (BeforeIsOkay && X < Y) 2407 return true; 2408 2409 return false; 2410 } 2411 2412 AvailabilityAttr *Sema::mergeAvailabilityAttr( 2413 NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, 2414 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, 2415 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, 2416 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, 2417 int Priority) { 2418 VersionTuple MergedIntroduced = Introduced; 2419 VersionTuple MergedDeprecated = Deprecated; 2420 VersionTuple MergedObsoleted = Obsoleted; 2421 bool FoundAny = false; 2422 bool OverrideOrImpl = false; 2423 switch (AMK) { 2424 case AMK_None: 2425 case AMK_Redeclaration: 2426 OverrideOrImpl = false; 2427 break; 2428 2429 case AMK_Override: 2430 case AMK_ProtocolImplementation: 2431 case AMK_OptionalProtocolImplementation: 2432 OverrideOrImpl = true; 2433 break; 2434 } 2435 2436 if (D->hasAttrs()) { 2437 AttrVec &Attrs = D->getAttrs(); 2438 for (unsigned i = 0, e = Attrs.size(); i != e;) { 2439 const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]); 2440 if (!OldAA) { 2441 ++i; 2442 continue; 2443 } 2444 2445 IdentifierInfo *OldPlatform = OldAA->getPlatform(); 2446 if (OldPlatform != Platform) { 2447 ++i; 2448 continue; 2449 } 2450 2451 // If there is an existing availability attribute for this platform that 2452 // has a lower priority use the existing one and discard the new 2453 // attribute. 2454 if (OldAA->getPriority() < Priority) 2455 return nullptr; 2456 2457 // If there is an existing attribute for this platform that has a higher 2458 // priority than the new attribute then erase the old one and continue 2459 // processing the attributes. 2460 if (OldAA->getPriority() > Priority) { 2461 Attrs.erase(Attrs.begin() + i); 2462 --e; 2463 continue; 2464 } 2465 2466 FoundAny = true; 2467 VersionTuple OldIntroduced = OldAA->getIntroduced(); 2468 VersionTuple OldDeprecated = OldAA->getDeprecated(); 2469 VersionTuple OldObsoleted = OldAA->getObsoleted(); 2470 bool OldIsUnavailable = OldAA->getUnavailable(); 2471 2472 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) || 2473 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) || 2474 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) || 2475 !(OldIsUnavailable == IsUnavailable || 2476 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) { 2477 if (OverrideOrImpl) { 2478 int Which = -1; 2479 VersionTuple FirstVersion; 2480 VersionTuple SecondVersion; 2481 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) { 2482 Which = 0; 2483 FirstVersion = OldIntroduced; 2484 SecondVersion = Introduced; 2485 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) { 2486 Which = 1; 2487 FirstVersion = Deprecated; 2488 SecondVersion = OldDeprecated; 2489 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) { 2490 Which = 2; 2491 FirstVersion = Obsoleted; 2492 SecondVersion = OldObsoleted; 2493 } 2494 2495 if (Which == -1) { 2496 Diag(OldAA->getLocation(), 2497 diag::warn_mismatched_availability_override_unavail) 2498 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 2499 << (AMK == AMK_Override); 2500 } else if (Which != 1 && AMK == AMK_OptionalProtocolImplementation) { 2501 // Allow different 'introduced' / 'obsoleted' availability versions 2502 // on a method that implements an optional protocol requirement. It 2503 // makes less sense to allow this for 'deprecated' as the user can't 2504 // see if the method is 'deprecated' as 'respondsToSelector' will 2505 // still return true when the method is deprecated. 2506 ++i; 2507 continue; 2508 } else { 2509 Diag(OldAA->getLocation(), 2510 diag::warn_mismatched_availability_override) 2511 << Which 2512 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 2513 << FirstVersion.getAsString() << SecondVersion.getAsString() 2514 << (AMK == AMK_Override); 2515 } 2516 if (AMK == AMK_Override) 2517 Diag(CI.getLoc(), diag::note_overridden_method); 2518 else 2519 Diag(CI.getLoc(), diag::note_protocol_method); 2520 } else { 2521 Diag(OldAA->getLocation(), diag::warn_mismatched_availability); 2522 Diag(CI.getLoc(), diag::note_previous_attribute); 2523 } 2524 2525 Attrs.erase(Attrs.begin() + i); 2526 --e; 2527 continue; 2528 } 2529 2530 VersionTuple MergedIntroduced2 = MergedIntroduced; 2531 VersionTuple MergedDeprecated2 = MergedDeprecated; 2532 VersionTuple MergedObsoleted2 = MergedObsoleted; 2533 2534 if (MergedIntroduced2.empty()) 2535 MergedIntroduced2 = OldIntroduced; 2536 if (MergedDeprecated2.empty()) 2537 MergedDeprecated2 = OldDeprecated; 2538 if (MergedObsoleted2.empty()) 2539 MergedObsoleted2 = OldObsoleted; 2540 2541 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform, 2542 MergedIntroduced2, MergedDeprecated2, 2543 MergedObsoleted2)) { 2544 Attrs.erase(Attrs.begin() + i); 2545 --e; 2546 continue; 2547 } 2548 2549 MergedIntroduced = MergedIntroduced2; 2550 MergedDeprecated = MergedDeprecated2; 2551 MergedObsoleted = MergedObsoleted2; 2552 ++i; 2553 } 2554 } 2555 2556 if (FoundAny && 2557 MergedIntroduced == Introduced && 2558 MergedDeprecated == Deprecated && 2559 MergedObsoleted == Obsoleted) 2560 return nullptr; 2561 2562 // Only create a new attribute if !OverrideOrImpl, but we want to do 2563 // the checking. 2564 if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced, 2565 MergedDeprecated, MergedObsoleted) && 2566 !OverrideOrImpl) { 2567 auto *Avail = ::new (Context) AvailabilityAttr( 2568 Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable, 2569 Message, IsStrict, Replacement, Priority); 2570 Avail->setImplicit(Implicit); 2571 return Avail; 2572 } 2573 return nullptr; 2574 } 2575 2576 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2577 if (isa<UsingDecl, UnresolvedUsingTypenameDecl, UnresolvedUsingValueDecl>( 2578 D)) { 2579 S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using) 2580 << AL; 2581 return; 2582 } 2583 2584 if (!AL.checkExactlyNumArgs(S, 1)) 2585 return; 2586 IdentifierLoc *Platform = AL.getArgAsIdent(0); 2587 2588 IdentifierInfo *II = Platform->Ident; 2589 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty()) 2590 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform) 2591 << Platform->Ident; 2592 2593 auto *ND = dyn_cast<NamedDecl>(D); 2594 if (!ND) // We warned about this already, so just return. 2595 return; 2596 2597 AvailabilityChange Introduced = AL.getAvailabilityIntroduced(); 2598 AvailabilityChange Deprecated = AL.getAvailabilityDeprecated(); 2599 AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted(); 2600 bool IsUnavailable = AL.getUnavailableLoc().isValid(); 2601 bool IsStrict = AL.getStrictLoc().isValid(); 2602 StringRef Str; 2603 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr())) 2604 Str = SE->getString(); 2605 StringRef Replacement; 2606 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr())) 2607 Replacement = SE->getString(); 2608 2609 if (II->isStr("swift")) { 2610 if (Introduced.isValid() || Obsoleted.isValid() || 2611 (!IsUnavailable && !Deprecated.isValid())) { 2612 S.Diag(AL.getLoc(), 2613 diag::warn_availability_swift_unavailable_deprecated_only); 2614 return; 2615 } 2616 } 2617 2618 if (II->isStr("fuchsia")) { 2619 Optional<unsigned> Min, Sub; 2620 if ((Min = Introduced.Version.getMinor()) || 2621 (Sub = Introduced.Version.getSubminor())) { 2622 S.Diag(AL.getLoc(), diag::warn_availability_fuchsia_unavailable_minor); 2623 return; 2624 } 2625 } 2626 2627 int PriorityModifier = AL.isPragmaClangAttribute() 2628 ? Sema::AP_PragmaClangAttribute 2629 : Sema::AP_Explicit; 2630 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2631 ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version, 2632 Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement, 2633 Sema::AMK_None, PriorityModifier); 2634 if (NewAttr) 2635 D->addAttr(NewAttr); 2636 2637 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning 2638 // matches before the start of the watchOS platform. 2639 if (S.Context.getTargetInfo().getTriple().isWatchOS()) { 2640 IdentifierInfo *NewII = nullptr; 2641 if (II->getName() == "ios") 2642 NewII = &S.Context.Idents.get("watchos"); 2643 else if (II->getName() == "ios_app_extension") 2644 NewII = &S.Context.Idents.get("watchos_app_extension"); 2645 2646 if (NewII) { 2647 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking(); 2648 const auto *IOSToWatchOSMapping = 2649 SDKInfo ? SDKInfo->getVersionMapping( 2650 DarwinSDKInfo::OSEnvPair::iOStoWatchOSPair()) 2651 : nullptr; 2652 2653 auto adjustWatchOSVersion = 2654 [IOSToWatchOSMapping](VersionTuple Version) -> VersionTuple { 2655 if (Version.empty()) 2656 return Version; 2657 auto MinimumWatchOSVersion = VersionTuple(2, 0); 2658 2659 if (IOSToWatchOSMapping) { 2660 if (auto MappedVersion = IOSToWatchOSMapping->map( 2661 Version, MinimumWatchOSVersion, None)) { 2662 return MappedVersion.getValue(); 2663 } 2664 } 2665 2666 auto Major = Version.getMajor(); 2667 auto NewMajor = Major >= 9 ? Major - 7 : 0; 2668 if (NewMajor >= 2) { 2669 if (Version.getMinor().hasValue()) { 2670 if (Version.getSubminor().hasValue()) 2671 return VersionTuple(NewMajor, Version.getMinor().getValue(), 2672 Version.getSubminor().getValue()); 2673 else 2674 return VersionTuple(NewMajor, Version.getMinor().getValue()); 2675 } 2676 return VersionTuple(NewMajor); 2677 } 2678 2679 return MinimumWatchOSVersion; 2680 }; 2681 2682 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version); 2683 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version); 2684 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version); 2685 2686 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2687 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated, 2688 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement, 2689 Sema::AMK_None, 2690 PriorityModifier + Sema::AP_InferredFromOtherPlatform); 2691 if (NewAttr) 2692 D->addAttr(NewAttr); 2693 } 2694 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) { 2695 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning 2696 // matches before the start of the tvOS platform. 2697 IdentifierInfo *NewII = nullptr; 2698 if (II->getName() == "ios") 2699 NewII = &S.Context.Idents.get("tvos"); 2700 else if (II->getName() == "ios_app_extension") 2701 NewII = &S.Context.Idents.get("tvos_app_extension"); 2702 2703 if (NewII) { 2704 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking(); 2705 const auto *IOSToTvOSMapping = 2706 SDKInfo ? SDKInfo->getVersionMapping( 2707 DarwinSDKInfo::OSEnvPair::iOStoTvOSPair()) 2708 : nullptr; 2709 2710 auto AdjustTvOSVersion = 2711 [IOSToTvOSMapping](VersionTuple Version) -> VersionTuple { 2712 if (Version.empty()) 2713 return Version; 2714 2715 if (IOSToTvOSMapping) { 2716 if (auto MappedVersion = 2717 IOSToTvOSMapping->map(Version, VersionTuple(0, 0), None)) { 2718 return MappedVersion.getValue(); 2719 } 2720 } 2721 return Version; 2722 }; 2723 2724 auto NewIntroduced = AdjustTvOSVersion(Introduced.Version); 2725 auto NewDeprecated = AdjustTvOSVersion(Deprecated.Version); 2726 auto NewObsoleted = AdjustTvOSVersion(Obsoleted.Version); 2727 2728 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2729 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated, 2730 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement, 2731 Sema::AMK_None, 2732 PriorityModifier + Sema::AP_InferredFromOtherPlatform); 2733 if (NewAttr) 2734 D->addAttr(NewAttr); 2735 } 2736 } else if (S.Context.getTargetInfo().getTriple().getOS() == 2737 llvm::Triple::IOS && 2738 S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) { 2739 auto GetSDKInfo = [&]() { 2740 return S.getDarwinSDKInfoForAvailabilityChecking(AL.getRange().getBegin(), 2741 "macOS"); 2742 }; 2743 2744 // Transcribe "ios" to "maccatalyst" (and add a new attribute). 2745 IdentifierInfo *NewII = nullptr; 2746 if (II->getName() == "ios") 2747 NewII = &S.Context.Idents.get("maccatalyst"); 2748 else if (II->getName() == "ios_app_extension") 2749 NewII = &S.Context.Idents.get("maccatalyst_app_extension"); 2750 if (NewII) { 2751 auto MinMacCatalystVersion = [](const VersionTuple &V) { 2752 if (V.empty()) 2753 return V; 2754 if (V.getMajor() < 13 || 2755 (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1)) 2756 return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1. 2757 return V; 2758 }; 2759 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2760 ND, AL.getRange(), NewII, true /*Implicit*/, 2761 MinMacCatalystVersion(Introduced.Version), 2762 MinMacCatalystVersion(Deprecated.Version), 2763 MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str, 2764 IsStrict, Replacement, Sema::AMK_None, 2765 PriorityModifier + Sema::AP_InferredFromOtherPlatform); 2766 if (NewAttr) 2767 D->addAttr(NewAttr); 2768 } else if (II->getName() == "macos" && GetSDKInfo() && 2769 (!Introduced.Version.empty() || !Deprecated.Version.empty() || 2770 !Obsoleted.Version.empty())) { 2771 if (const auto *MacOStoMacCatalystMapping = 2772 GetSDKInfo()->getVersionMapping( 2773 DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) { 2774 // Infer Mac Catalyst availability from the macOS availability attribute 2775 // if it has versioned availability. Don't infer 'unavailable'. This 2776 // inferred availability has lower priority than the other availability 2777 // attributes that are inferred from 'ios'. 2778 NewII = &S.Context.Idents.get("maccatalyst"); 2779 auto RemapMacOSVersion = 2780 [&](const VersionTuple &V) -> Optional<VersionTuple> { 2781 if (V.empty()) 2782 return None; 2783 // API_TO_BE_DEPRECATED is 100000. 2784 if (V.getMajor() == 100000) 2785 return VersionTuple(100000); 2786 // The minimum iosmac version is 13.1 2787 return MacOStoMacCatalystMapping->map(V, VersionTuple(13, 1), None); 2788 }; 2789 Optional<VersionTuple> NewIntroduced = 2790 RemapMacOSVersion(Introduced.Version), 2791 NewDeprecated = 2792 RemapMacOSVersion(Deprecated.Version), 2793 NewObsoleted = 2794 RemapMacOSVersion(Obsoleted.Version); 2795 if (NewIntroduced || NewDeprecated || NewObsoleted) { 2796 auto VersionOrEmptyVersion = 2797 [](const Optional<VersionTuple> &V) -> VersionTuple { 2798 return V ? *V : VersionTuple(); 2799 }; 2800 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2801 ND, AL.getRange(), NewII, true /*Implicit*/, 2802 VersionOrEmptyVersion(NewIntroduced), 2803 VersionOrEmptyVersion(NewDeprecated), 2804 VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str, 2805 IsStrict, Replacement, Sema::AMK_None, 2806 PriorityModifier + Sema::AP_InferredFromOtherPlatform + 2807 Sema::AP_InferredFromOtherPlatform); 2808 if (NewAttr) 2809 D->addAttr(NewAttr); 2810 } 2811 } 2812 } 2813 } 2814 } 2815 2816 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D, 2817 const ParsedAttr &AL) { 2818 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 3)) 2819 return; 2820 2821 StringRef Language; 2822 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0))) 2823 Language = SE->getString(); 2824 StringRef DefinedIn; 2825 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1))) 2826 DefinedIn = SE->getString(); 2827 bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr; 2828 2829 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr( 2830 S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration)); 2831 } 2832 2833 template <class T> 2834 static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI, 2835 typename T::VisibilityType value) { 2836 T *existingAttr = D->getAttr<T>(); 2837 if (existingAttr) { 2838 typename T::VisibilityType existingValue = existingAttr->getVisibility(); 2839 if (existingValue == value) 2840 return nullptr; 2841 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility); 2842 S.Diag(CI.getLoc(), diag::note_previous_attribute); 2843 D->dropAttr<T>(); 2844 } 2845 return ::new (S.Context) T(S.Context, CI, value); 2846 } 2847 2848 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, 2849 const AttributeCommonInfo &CI, 2850 VisibilityAttr::VisibilityType Vis) { 2851 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis); 2852 } 2853 2854 TypeVisibilityAttr * 2855 Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 2856 TypeVisibilityAttr::VisibilityType Vis) { 2857 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis); 2858 } 2859 2860 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL, 2861 bool isTypeVisibility) { 2862 // Visibility attributes don't mean anything on a typedef. 2863 if (isa<TypedefNameDecl>(D)) { 2864 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL; 2865 return; 2866 } 2867 2868 // 'type_visibility' can only go on a type or namespace. 2869 if (isTypeVisibility && 2870 !(isa<TagDecl>(D) || 2871 isa<ObjCInterfaceDecl>(D) || 2872 isa<NamespaceDecl>(D))) { 2873 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type) 2874 << AL << ExpectedTypeOrNamespace; 2875 return; 2876 } 2877 2878 // Check that the argument is a string literal. 2879 StringRef TypeStr; 2880 SourceLocation LiteralLoc; 2881 if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc)) 2882 return; 2883 2884 VisibilityAttr::VisibilityType type; 2885 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) { 2886 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL 2887 << TypeStr; 2888 return; 2889 } 2890 2891 // Complain about attempts to use protected visibility on targets 2892 // (like Darwin) that don't support it. 2893 if (type == VisibilityAttr::Protected && 2894 !S.Context.getTargetInfo().hasProtectedVisibility()) { 2895 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility); 2896 type = VisibilityAttr::Default; 2897 } 2898 2899 Attr *newAttr; 2900 if (isTypeVisibility) { 2901 newAttr = S.mergeTypeVisibilityAttr( 2902 D, AL, (TypeVisibilityAttr::VisibilityType)type); 2903 } else { 2904 newAttr = S.mergeVisibilityAttr(D, AL, type); 2905 } 2906 if (newAttr) 2907 D->addAttr(newAttr); 2908 } 2909 2910 static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2911 // objc_direct cannot be set on methods declared in the context of a protocol 2912 if (isa<ObjCProtocolDecl>(D->getDeclContext())) { 2913 S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false; 2914 return; 2915 } 2916 2917 if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) { 2918 handleSimpleAttribute<ObjCDirectAttr>(S, D, AL); 2919 } else { 2920 S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL; 2921 } 2922 } 2923 2924 static void handleObjCDirectMembersAttr(Sema &S, Decl *D, 2925 const ParsedAttr &AL) { 2926 if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) { 2927 handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL); 2928 } else { 2929 S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL; 2930 } 2931 } 2932 2933 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2934 const auto *M = cast<ObjCMethodDecl>(D); 2935 if (!AL.isArgIdent(0)) { 2936 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 2937 << AL << 1 << AANT_ArgumentIdentifier; 2938 return; 2939 } 2940 2941 IdentifierLoc *IL = AL.getArgAsIdent(0); 2942 ObjCMethodFamilyAttr::FamilyKind F; 2943 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) { 2944 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident; 2945 return; 2946 } 2947 2948 if (F == ObjCMethodFamilyAttr::OMF_init && 2949 !M->getReturnType()->isObjCObjectPointerType()) { 2950 S.Diag(M->getLocation(), diag::err_init_method_bad_return_type) 2951 << M->getReturnType(); 2952 // Ignore the attribute. 2953 return; 2954 } 2955 2956 D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F)); 2957 } 2958 2959 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) { 2960 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2961 QualType T = TD->getUnderlyingType(); 2962 if (!T->isCARCBridgableType()) { 2963 S.Diag(TD->getLocation(), diag::err_nsobject_attribute); 2964 return; 2965 } 2966 } 2967 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) { 2968 QualType T = PD->getType(); 2969 if (!T->isCARCBridgableType()) { 2970 S.Diag(PD->getLocation(), diag::err_nsobject_attribute); 2971 return; 2972 } 2973 } 2974 else { 2975 // It is okay to include this attribute on properties, e.g.: 2976 // 2977 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); 2978 // 2979 // In this case it follows tradition and suppresses an error in the above 2980 // case. 2981 S.Diag(D->getLocation(), diag::warn_nsobject_attribute); 2982 } 2983 D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL)); 2984 } 2985 2986 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) { 2987 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2988 QualType T = TD->getUnderlyingType(); 2989 if (!T->isObjCObjectPointerType()) { 2990 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute); 2991 return; 2992 } 2993 } else { 2994 S.Diag(D->getLocation(), diag::warn_independentclass_attribute); 2995 return; 2996 } 2997 D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL)); 2998 } 2999 3000 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3001 if (!AL.isArgIdent(0)) { 3002 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 3003 << AL << 1 << AANT_ArgumentIdentifier; 3004 return; 3005 } 3006 3007 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 3008 BlocksAttr::BlockType type; 3009 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) { 3010 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; 3011 return; 3012 } 3013 3014 D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type)); 3015 } 3016 3017 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3018 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel; 3019 if (AL.getNumArgs() > 0) { 3020 Expr *E = AL.getArgAsExpr(0); 3021 Optional<llvm::APSInt> Idx = llvm::APSInt(32); 3022 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) { 3023 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 3024 << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange(); 3025 return; 3026 } 3027 3028 if (Idx->isSigned() && Idx->isNegative()) { 3029 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero) 3030 << E->getSourceRange(); 3031 return; 3032 } 3033 3034 sentinel = Idx->getZExtValue(); 3035 } 3036 3037 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos; 3038 if (AL.getNumArgs() > 1) { 3039 Expr *E = AL.getArgAsExpr(1); 3040 Optional<llvm::APSInt> Idx = llvm::APSInt(32); 3041 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) { 3042 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 3043 << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange(); 3044 return; 3045 } 3046 nullPos = Idx->getZExtValue(); 3047 3048 if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) { 3049 // FIXME: This error message could be improved, it would be nice 3050 // to say what the bounds actually are. 3051 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one) 3052 << E->getSourceRange(); 3053 return; 3054 } 3055 } 3056 3057 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3058 const FunctionType *FT = FD->getType()->castAs<FunctionType>(); 3059 if (isa<FunctionNoProtoType>(FT)) { 3060 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments); 3061 return; 3062 } 3063 3064 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 3065 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 3066 return; 3067 } 3068 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 3069 if (!MD->isVariadic()) { 3070 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 3071 return; 3072 } 3073 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) { 3074 if (!BD->isVariadic()) { 3075 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1; 3076 return; 3077 } 3078 } else if (const auto *V = dyn_cast<VarDecl>(D)) { 3079 QualType Ty = V->getType(); 3080 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 3081 const FunctionType *FT = Ty->isFunctionPointerType() 3082 ? D->getFunctionType() 3083 : Ty->castAs<BlockPointerType>() 3084 ->getPointeeType() 3085 ->castAs<FunctionType>(); 3086 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 3087 int m = Ty->isFunctionPointerType() ? 0 : 1; 3088 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m; 3089 return; 3090 } 3091 } else { 3092 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 3093 << AL << ExpectedFunctionMethodOrBlock; 3094 return; 3095 } 3096 } else { 3097 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 3098 << AL << ExpectedFunctionMethodOrBlock; 3099 return; 3100 } 3101 D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos)); 3102 } 3103 3104 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) { 3105 if (D->getFunctionType() && 3106 D->getFunctionType()->getReturnType()->isVoidType() && 3107 !isa<CXXConstructorDecl>(D)) { 3108 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0; 3109 return; 3110 } 3111 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 3112 if (MD->getReturnType()->isVoidType()) { 3113 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1; 3114 return; 3115 } 3116 3117 StringRef Str; 3118 if (AL.isStandardAttributeSyntax() && !AL.getScopeName()) { 3119 // The standard attribute cannot be applied to variable declarations such 3120 // as a function pointer. 3121 if (isa<VarDecl>(D)) 3122 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str) 3123 << AL << "functions, classes, or enumerations"; 3124 3125 // If this is spelled as the standard C++17 attribute, but not in C++17, 3126 // warn about using it as an extension. If there are attribute arguments, 3127 // then claim it's a C++2a extension instead. 3128 // FIXME: If WG14 does not seem likely to adopt the same feature, add an 3129 // extension warning for C2x mode. 3130 const LangOptions &LO = S.getLangOpts(); 3131 if (AL.getNumArgs() == 1) { 3132 if (LO.CPlusPlus && !LO.CPlusPlus20) 3133 S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL; 3134 3135 // Since this this is spelled [[nodiscard]], get the optional string 3136 // literal. If in C++ mode, but not in C++2a mode, diagnose as an 3137 // extension. 3138 // FIXME: C2x should support this feature as well, even as an extension. 3139 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr)) 3140 return; 3141 } else if (LO.CPlusPlus && !LO.CPlusPlus17) 3142 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL; 3143 } 3144 3145 D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str)); 3146 } 3147 3148 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3149 // weak_import only applies to variable & function declarations. 3150 bool isDef = false; 3151 if (!D->canBeWeakImported(isDef)) { 3152 if (isDef) 3153 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition) 3154 << "weak_import"; 3155 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) || 3156 (S.Context.getTargetInfo().getTriple().isOSDarwin() && 3157 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) { 3158 // Nothing to warn about here. 3159 } else 3160 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 3161 << AL << ExpectedVariableOrFunction; 3162 3163 return; 3164 } 3165 3166 D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL)); 3167 } 3168 3169 // Handles reqd_work_group_size and work_group_size_hint. 3170 template <typename WorkGroupAttr> 3171 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) { 3172 uint32_t WGSize[3]; 3173 for (unsigned i = 0; i < 3; ++i) { 3174 const Expr *E = AL.getArgAsExpr(i); 3175 if (!checkUInt32Argument(S, AL, E, WGSize[i], i, 3176 /*StrictlyUnsigned=*/true)) 3177 return; 3178 if (WGSize[i] == 0) { 3179 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero) 3180 << AL << E->getSourceRange(); 3181 return; 3182 } 3183 } 3184 3185 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>(); 3186 if (Existing && !(Existing->getXDim() == WGSize[0] && 3187 Existing->getYDim() == WGSize[1] && 3188 Existing->getZDim() == WGSize[2])) 3189 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 3190 3191 D->addAttr(::new (S.Context) 3192 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2])); 3193 } 3194 3195 // Handles intel_reqd_sub_group_size. 3196 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) { 3197 uint32_t SGSize; 3198 const Expr *E = AL.getArgAsExpr(0); 3199 if (!checkUInt32Argument(S, AL, E, SGSize)) 3200 return; 3201 if (SGSize == 0) { 3202 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero) 3203 << AL << E->getSourceRange(); 3204 return; 3205 } 3206 3207 OpenCLIntelReqdSubGroupSizeAttr *Existing = 3208 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>(); 3209 if (Existing && Existing->getSubGroupSize() != SGSize) 3210 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 3211 3212 D->addAttr(::new (S.Context) 3213 OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize)); 3214 } 3215 3216 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) { 3217 if (!AL.hasParsedType()) { 3218 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; 3219 return; 3220 } 3221 3222 TypeSourceInfo *ParmTSI = nullptr; 3223 QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI); 3224 assert(ParmTSI && "no type source info for attribute argument"); 3225 3226 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() && 3227 (ParmType->isBooleanType() || 3228 !ParmType->isIntegralType(S.getASTContext()))) { 3229 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL; 3230 return; 3231 } 3232 3233 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) { 3234 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) { 3235 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 3236 return; 3237 } 3238 } 3239 3240 D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI)); 3241 } 3242 3243 SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, 3244 StringRef Name) { 3245 // Explicit or partial specializations do not inherit 3246 // the section attribute from the primary template. 3247 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3248 if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate && 3249 FD->isFunctionTemplateSpecialization()) 3250 return nullptr; 3251 } 3252 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) { 3253 if (ExistingAttr->getName() == Name) 3254 return nullptr; 3255 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section) 3256 << 1 /*section*/; 3257 Diag(CI.getLoc(), diag::note_previous_attribute); 3258 return nullptr; 3259 } 3260 return ::new (Context) SectionAttr(Context, CI, Name); 3261 } 3262 3263 /// Used to implement to perform semantic checking on 3264 /// attribute((section("foo"))) specifiers. 3265 /// 3266 /// In this case, "foo" is passed in to be checked. If the section 3267 /// specifier is invalid, return an Error that indicates the problem. 3268 /// 3269 /// This is a simple quality of implementation feature to catch errors 3270 /// and give good diagnostics in cases when the assembler or code generator 3271 /// would otherwise reject the section specifier. 3272 llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) { 3273 if (!Context.getTargetInfo().getTriple().isOSDarwin()) 3274 return llvm::Error::success(); 3275 3276 // Let MCSectionMachO validate this. 3277 StringRef Segment, Section; 3278 unsigned TAA, StubSize; 3279 bool HasTAA; 3280 return llvm::MCSectionMachO::ParseSectionSpecifier(SecName, Segment, Section, 3281 TAA, HasTAA, StubSize); 3282 } 3283 3284 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) { 3285 if (llvm::Error E = isValidSectionSpecifier(SecName)) { 3286 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) 3287 << toString(std::move(E)) << 1 /*'section'*/; 3288 return false; 3289 } 3290 return true; 3291 } 3292 3293 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3294 // Make sure that there is a string literal as the sections's single 3295 // argument. 3296 StringRef Str; 3297 SourceLocation LiteralLoc; 3298 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc)) 3299 return; 3300 3301 if (!S.checkSectionName(LiteralLoc, Str)) 3302 return; 3303 3304 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str); 3305 if (NewAttr) { 3306 D->addAttr(NewAttr); 3307 if (isa<FunctionDecl, FunctionTemplateDecl, ObjCMethodDecl, 3308 ObjCPropertyDecl>(D)) 3309 S.UnifySection(NewAttr->getName(), 3310 ASTContext::PSF_Execute | ASTContext::PSF_Read, 3311 cast<NamedDecl>(D)); 3312 } 3313 } 3314 3315 // This is used for `__declspec(code_seg("segname"))` on a decl. 3316 // `#pragma code_seg("segname")` uses checkSectionName() instead. 3317 static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc, 3318 StringRef CodeSegName) { 3319 if (llvm::Error E = S.isValidSectionSpecifier(CodeSegName)) { 3320 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) 3321 << toString(std::move(E)) << 0 /*'code-seg'*/; 3322 return false; 3323 } 3324 3325 return true; 3326 } 3327 3328 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, 3329 StringRef Name) { 3330 // Explicit or partial specializations do not inherit 3331 // the code_seg attribute from the primary template. 3332 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3333 if (FD->isFunctionTemplateSpecialization()) 3334 return nullptr; 3335 } 3336 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) { 3337 if (ExistingAttr->getName() == Name) 3338 return nullptr; 3339 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section) 3340 << 0 /*codeseg*/; 3341 Diag(CI.getLoc(), diag::note_previous_attribute); 3342 return nullptr; 3343 } 3344 return ::new (Context) CodeSegAttr(Context, CI, Name); 3345 } 3346 3347 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3348 StringRef Str; 3349 SourceLocation LiteralLoc; 3350 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc)) 3351 return; 3352 if (!checkCodeSegName(S, LiteralLoc, Str)) 3353 return; 3354 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) { 3355 if (!ExistingAttr->isImplicit()) { 3356 S.Diag(AL.getLoc(), 3357 ExistingAttr->getName() == Str 3358 ? diag::warn_duplicate_codeseg_attribute 3359 : diag::err_conflicting_codeseg_attribute); 3360 return; 3361 } 3362 D->dropAttr<CodeSegAttr>(); 3363 } 3364 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str)) 3365 D->addAttr(CSA); 3366 } 3367 3368 // Check for things we'd like to warn about. Multiversioning issues are 3369 // handled later in the process, once we know how many exist. 3370 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) { 3371 enum FirstParam { Unsupported, Duplicate, Unknown }; 3372 enum SecondParam { None, Architecture, Tune }; 3373 enum ThirdParam { Target, TargetClones }; 3374 if (AttrStr.contains("fpmath=")) 3375 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3376 << Unsupported << None << "fpmath=" << Target; 3377 3378 // Diagnose use of tune if target doesn't support it. 3379 if (!Context.getTargetInfo().supportsTargetAttributeTune() && 3380 AttrStr.contains("tune=")) 3381 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3382 << Unsupported << None << "tune=" << Target; 3383 3384 ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr); 3385 3386 if (!ParsedAttrs.Architecture.empty() && 3387 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture)) 3388 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3389 << Unknown << Architecture << ParsedAttrs.Architecture << Target; 3390 3391 if (!ParsedAttrs.Tune.empty() && 3392 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune)) 3393 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3394 << Unknown << Tune << ParsedAttrs.Tune << Target; 3395 3396 if (ParsedAttrs.DuplicateArchitecture) 3397 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3398 << Duplicate << None << "arch=" << Target; 3399 if (ParsedAttrs.DuplicateTune) 3400 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3401 << Duplicate << None << "tune=" << Target; 3402 3403 for (const auto &Feature : ParsedAttrs.Features) { 3404 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -. 3405 if (!Context.getTargetInfo().isValidFeatureName(CurFeature)) 3406 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3407 << Unsupported << None << CurFeature << Target; 3408 } 3409 3410 TargetInfo::BranchProtectionInfo BPI; 3411 StringRef DiagMsg; 3412 if (ParsedAttrs.BranchProtection.empty()) 3413 return false; 3414 if (!Context.getTargetInfo().validateBranchProtection( 3415 ParsedAttrs.BranchProtection, ParsedAttrs.Architecture, BPI, 3416 DiagMsg)) { 3417 if (DiagMsg.empty()) 3418 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3419 << Unsupported << None << "branch-protection" << Target; 3420 return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec) 3421 << DiagMsg; 3422 } 3423 if (!DiagMsg.empty()) 3424 Diag(LiteralLoc, diag::warn_unsupported_branch_protection_spec) << DiagMsg; 3425 3426 return false; 3427 } 3428 3429 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3430 StringRef Str; 3431 SourceLocation LiteralLoc; 3432 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) || 3433 S.checkTargetAttr(LiteralLoc, Str)) 3434 return; 3435 3436 TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str); 3437 D->addAttr(NewAttr); 3438 } 3439 3440 bool Sema::checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str, 3441 const StringLiteral *Literal, 3442 bool &HasDefault, bool &HasCommas, 3443 SmallVectorImpl<StringRef> &Strings) { 3444 enum FirstParam { Unsupported, Duplicate, Unknown }; 3445 enum SecondParam { None, Architecture, Tune }; 3446 enum ThirdParam { Target, TargetClones }; 3447 HasCommas = HasCommas || Str.contains(','); 3448 // Warn on empty at the beginning of a string. 3449 if (Str.size() == 0) 3450 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3451 << Unsupported << None << "" << TargetClones; 3452 3453 std::pair<StringRef, StringRef> Parts = {{}, Str}; 3454 while (!Parts.second.empty()) { 3455 Parts = Parts.second.split(','); 3456 StringRef Cur = Parts.first.trim(); 3457 SourceLocation CurLoc = Literal->getLocationOfByte( 3458 Cur.data() - Literal->getString().data(), getSourceManager(), 3459 getLangOpts(), Context.getTargetInfo()); 3460 3461 bool DefaultIsDupe = false; 3462 if (Cur.empty()) 3463 return Diag(CurLoc, diag::warn_unsupported_target_attribute) 3464 << Unsupported << None << "" << TargetClones; 3465 3466 if (Cur.startswith("arch=")) { 3467 if (!Context.getTargetInfo().isValidCPUName( 3468 Cur.drop_front(sizeof("arch=") - 1))) 3469 return Diag(CurLoc, diag::warn_unsupported_target_attribute) 3470 << Unsupported << Architecture 3471 << Cur.drop_front(sizeof("arch=") - 1) << TargetClones; 3472 } else if (Cur == "default") { 3473 DefaultIsDupe = HasDefault; 3474 HasDefault = true; 3475 } else if (!Context.getTargetInfo().isValidFeatureName(Cur)) 3476 return Diag(CurLoc, diag::warn_unsupported_target_attribute) 3477 << Unsupported << None << Cur << TargetClones; 3478 3479 if (llvm::find(Strings, Cur) != Strings.end() || DefaultIsDupe) 3480 Diag(CurLoc, diag::warn_target_clone_duplicate_options); 3481 // Note: Add even if there are duplicates, since it changes name mangling. 3482 Strings.push_back(Cur); 3483 } 3484 3485 if (Str.rtrim().endswith(",")) 3486 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3487 << Unsupported << None << "" << TargetClones; 3488 return false; 3489 } 3490 3491 static void handleTargetClonesAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3492 // Ensure we don't combine these with themselves, since that causes some 3493 // confusing behavior. 3494 if (const auto *Other = D->getAttr<TargetClonesAttr>()) { 3495 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL; 3496 S.Diag(Other->getLocation(), diag::note_conflicting_attribute); 3497 return; 3498 } 3499 if (checkAttrMutualExclusion<TargetClonesAttr>(S, D, AL)) 3500 return; 3501 3502 SmallVector<StringRef, 2> Strings; 3503 bool HasCommas = false, HasDefault = false; 3504 3505 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 3506 StringRef CurStr; 3507 SourceLocation LiteralLoc; 3508 if (!S.checkStringLiteralArgumentAttr(AL, I, CurStr, &LiteralLoc) || 3509 S.checkTargetClonesAttrString( 3510 LiteralLoc, CurStr, 3511 cast<StringLiteral>(AL.getArgAsExpr(I)->IgnoreParenCasts()), 3512 HasDefault, HasCommas, Strings)) 3513 return; 3514 } 3515 3516 if (HasCommas && AL.getNumArgs() > 1) 3517 S.Diag(AL.getLoc(), diag::warn_target_clone_mixed_values); 3518 3519 if (!HasDefault) { 3520 S.Diag(AL.getLoc(), diag::err_target_clone_must_have_default); 3521 return; 3522 } 3523 3524 // FIXME: We could probably figure out how to get this to work for lambdas 3525 // someday. 3526 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 3527 if (MD->getParent()->isLambda()) { 3528 S.Diag(D->getLocation(), diag::err_multiversion_doesnt_support) 3529 << static_cast<unsigned>(MultiVersionKind::TargetClones) 3530 << /*Lambda*/ 9; 3531 return; 3532 } 3533 } 3534 3535 cast<FunctionDecl>(D)->setIsMultiVersion(); 3536 TargetClonesAttr *NewAttr = ::new (S.Context) 3537 TargetClonesAttr(S.Context, AL, Strings.data(), Strings.size()); 3538 D->addAttr(NewAttr); 3539 } 3540 3541 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3542 Expr *E = AL.getArgAsExpr(0); 3543 uint32_t VecWidth; 3544 if (!checkUInt32Argument(S, AL, E, VecWidth)) { 3545 AL.setInvalid(); 3546 return; 3547 } 3548 3549 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>(); 3550 if (Existing && Existing->getVectorWidth() != VecWidth) { 3551 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 3552 return; 3553 } 3554 3555 D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth)); 3556 } 3557 3558 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3559 Expr *E = AL.getArgAsExpr(0); 3560 SourceLocation Loc = E->getExprLoc(); 3561 FunctionDecl *FD = nullptr; 3562 DeclarationNameInfo NI; 3563 3564 // gcc only allows for simple identifiers. Since we support more than gcc, we 3565 // will warn the user. 3566 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 3567 if (DRE->hasQualifier()) 3568 S.Diag(Loc, diag::warn_cleanup_ext); 3569 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 3570 NI = DRE->getNameInfo(); 3571 if (!FD) { 3572 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1 3573 << NI.getName(); 3574 return; 3575 } 3576 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 3577 if (ULE->hasExplicitTemplateArgs()) 3578 S.Diag(Loc, diag::warn_cleanup_ext); 3579 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true); 3580 NI = ULE->getNameInfo(); 3581 if (!FD) { 3582 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2 3583 << NI.getName(); 3584 if (ULE->getType() == S.Context.OverloadTy) 3585 S.NoteAllOverloadCandidates(ULE); 3586 return; 3587 } 3588 } else { 3589 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0; 3590 return; 3591 } 3592 3593 if (FD->getNumParams() != 1) { 3594 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg) 3595 << NI.getName(); 3596 return; 3597 } 3598 3599 // We're currently more strict than GCC about what function types we accept. 3600 // If this ever proves to be a problem it should be easy to fix. 3601 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType()); 3602 QualType ParamTy = FD->getParamDecl(0)->getType(); 3603 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), 3604 ParamTy, Ty) != Sema::Compatible) { 3605 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type) 3606 << NI.getName() << ParamTy << Ty; 3607 return; 3608 } 3609 3610 D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD)); 3611 } 3612 3613 static void handleEnumExtensibilityAttr(Sema &S, Decl *D, 3614 const ParsedAttr &AL) { 3615 if (!AL.isArgIdent(0)) { 3616 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 3617 << AL << 0 << AANT_ArgumentIdentifier; 3618 return; 3619 } 3620 3621 EnumExtensibilityAttr::Kind ExtensibilityKind; 3622 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 3623 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(), 3624 ExtensibilityKind)) { 3625 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; 3626 return; 3627 } 3628 3629 D->addAttr(::new (S.Context) 3630 EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind)); 3631 } 3632 3633 /// Handle __attribute__((format_arg((idx)))) attribute based on 3634 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 3635 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3636 Expr *IdxExpr = AL.getArgAsExpr(0); 3637 ParamIdx Idx; 3638 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx)) 3639 return; 3640 3641 // Make sure the format string is really a string. 3642 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex()); 3643 3644 bool NotNSStringTy = !isNSStringType(Ty, S.Context); 3645 if (NotNSStringTy && 3646 !isCFStringType(Ty, S.Context) && 3647 (!Ty->isPointerType() || 3648 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) { 3649 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3650 << "a string type" << IdxExpr->getSourceRange() 3651 << getFunctionOrMethodParamRange(D, 0); 3652 return; 3653 } 3654 Ty = getFunctionOrMethodResultType(D); 3655 // replace instancetype with the class type 3656 auto Instancetype = S.Context.getObjCInstanceTypeDecl()->getTypeForDecl(); 3657 if (Ty->getAs<TypedefType>() == Instancetype) 3658 if (auto *OMD = dyn_cast<ObjCMethodDecl>(D)) 3659 if (auto *Interface = OMD->getClassInterface()) 3660 Ty = S.Context.getObjCObjectPointerType( 3661 QualType(Interface->getTypeForDecl(), 0)); 3662 if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true) && 3663 !isCFStringType(Ty, S.Context) && 3664 (!Ty->isPointerType() || 3665 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) { 3666 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not) 3667 << (NotNSStringTy ? "string type" : "NSString") 3668 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); 3669 return; 3670 } 3671 3672 D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx)); 3673 } 3674 3675 enum FormatAttrKind { 3676 CFStringFormat, 3677 NSStringFormat, 3678 StrftimeFormat, 3679 SupportedFormat, 3680 IgnoredFormat, 3681 InvalidFormat 3682 }; 3683 3684 /// getFormatAttrKind - Map from format attribute names to supported format 3685 /// types. 3686 static FormatAttrKind getFormatAttrKind(StringRef Format) { 3687 return llvm::StringSwitch<FormatAttrKind>(Format) 3688 // Check for formats that get handled specially. 3689 .Case("NSString", NSStringFormat) 3690 .Case("CFString", CFStringFormat) 3691 .Case("strftime", StrftimeFormat) 3692 3693 // Otherwise, check for supported formats. 3694 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat) 3695 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat) 3696 .Case("kprintf", SupportedFormat) // OpenBSD. 3697 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD. 3698 .Case("os_trace", SupportedFormat) 3699 .Case("os_log", SupportedFormat) 3700 3701 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat) 3702 .Default(InvalidFormat); 3703 } 3704 3705 /// Handle __attribute__((init_priority(priority))) attributes based on 3706 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html 3707 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3708 if (!S.getLangOpts().CPlusPlus) { 3709 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL; 3710 return; 3711 } 3712 3713 if (S.getCurFunctionOrMethodDecl()) { 3714 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr); 3715 AL.setInvalid(); 3716 return; 3717 } 3718 QualType T = cast<VarDecl>(D)->getType(); 3719 if (S.Context.getAsArrayType(T)) 3720 T = S.Context.getBaseElementType(T); 3721 if (!T->getAs<RecordType>()) { 3722 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr); 3723 AL.setInvalid(); 3724 return; 3725 } 3726 3727 Expr *E = AL.getArgAsExpr(0); 3728 uint32_t prioritynum; 3729 if (!checkUInt32Argument(S, AL, E, prioritynum)) { 3730 AL.setInvalid(); 3731 return; 3732 } 3733 3734 // Only perform the priority check if the attribute is outside of a system 3735 // header. Values <= 100 are reserved for the implementation, and libc++ 3736 // benefits from being able to specify values in that range. 3737 if ((prioritynum < 101 || prioritynum > 65535) && 3738 !S.getSourceManager().isInSystemHeader(AL.getLoc())) { 3739 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range) 3740 << E->getSourceRange() << AL << 101 << 65535; 3741 AL.setInvalid(); 3742 return; 3743 } 3744 D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum)); 3745 } 3746 3747 ErrorAttr *Sema::mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, 3748 StringRef NewUserDiagnostic) { 3749 if (const auto *EA = D->getAttr<ErrorAttr>()) { 3750 std::string NewAttr = CI.getNormalizedFullName(); 3751 assert((NewAttr == "error" || NewAttr == "warning") && 3752 "unexpected normalized full name"); 3753 bool Match = (EA->isError() && NewAttr == "error") || 3754 (EA->isWarning() && NewAttr == "warning"); 3755 if (!Match) { 3756 Diag(EA->getLocation(), diag::err_attributes_are_not_compatible) 3757 << CI << EA; 3758 Diag(CI.getLoc(), diag::note_conflicting_attribute); 3759 return nullptr; 3760 } 3761 if (EA->getUserDiagnostic() != NewUserDiagnostic) { 3762 Diag(CI.getLoc(), diag::warn_duplicate_attribute) << EA; 3763 Diag(EA->getLoc(), diag::note_previous_attribute); 3764 } 3765 D->dropAttr<ErrorAttr>(); 3766 } 3767 return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic); 3768 } 3769 3770 FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, 3771 IdentifierInfo *Format, int FormatIdx, 3772 int FirstArg) { 3773 // Check whether we already have an equivalent format attribute. 3774 for (auto *F : D->specific_attrs<FormatAttr>()) { 3775 if (F->getType() == Format && 3776 F->getFormatIdx() == FormatIdx && 3777 F->getFirstArg() == FirstArg) { 3778 // If we don't have a valid location for this attribute, adopt the 3779 // location. 3780 if (F->getLocation().isInvalid()) 3781 F->setRange(CI.getRange()); 3782 return nullptr; 3783 } 3784 } 3785 3786 return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg); 3787 } 3788 3789 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on 3790 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 3791 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3792 if (!AL.isArgIdent(0)) { 3793 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 3794 << AL << 1 << AANT_ArgumentIdentifier; 3795 return; 3796 } 3797 3798 // In C++ the implicit 'this' function parameter also counts, and they are 3799 // counted from one. 3800 bool HasImplicitThisParam = isInstanceMethod(D); 3801 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam; 3802 3803 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 3804 StringRef Format = II->getName(); 3805 3806 if (normalizeName(Format)) { 3807 // If we've modified the string name, we need a new identifier for it. 3808 II = &S.Context.Idents.get(Format); 3809 } 3810 3811 // Check for supported formats. 3812 FormatAttrKind Kind = getFormatAttrKind(Format); 3813 3814 if (Kind == IgnoredFormat) 3815 return; 3816 3817 if (Kind == InvalidFormat) { 3818 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 3819 << AL << II->getName(); 3820 return; 3821 } 3822 3823 // checks for the 2nd argument 3824 Expr *IdxExpr = AL.getArgAsExpr(1); 3825 uint32_t Idx; 3826 if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2)) 3827 return; 3828 3829 if (Idx < 1 || Idx > NumArgs) { 3830 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3831 << AL << 2 << IdxExpr->getSourceRange(); 3832 return; 3833 } 3834 3835 // FIXME: Do we need to bounds check? 3836 unsigned ArgIdx = Idx - 1; 3837 3838 if (HasImplicitThisParam) { 3839 if (ArgIdx == 0) { 3840 S.Diag(AL.getLoc(), 3841 diag::err_format_attribute_implicit_this_format_string) 3842 << IdxExpr->getSourceRange(); 3843 return; 3844 } 3845 ArgIdx--; 3846 } 3847 3848 // make sure the format string is really a string 3849 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx); 3850 3851 if (Kind == CFStringFormat) { 3852 if (!isCFStringType(Ty, S.Context)) { 3853 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3854 << "a CFString" << IdxExpr->getSourceRange() 3855 << getFunctionOrMethodParamRange(D, ArgIdx); 3856 return; 3857 } 3858 } else if (Kind == NSStringFormat) { 3859 // FIXME: do we need to check if the type is NSString*? What are the 3860 // semantics? 3861 if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true)) { 3862 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3863 << "an NSString" << IdxExpr->getSourceRange() 3864 << getFunctionOrMethodParamRange(D, ArgIdx); 3865 return; 3866 } 3867 } else if (!Ty->isPointerType() || 3868 !Ty->castAs<PointerType>()->getPointeeType()->isCharType()) { 3869 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3870 << "a string type" << IdxExpr->getSourceRange() 3871 << getFunctionOrMethodParamRange(D, ArgIdx); 3872 return; 3873 } 3874 3875 // check the 3rd argument 3876 Expr *FirstArgExpr = AL.getArgAsExpr(2); 3877 uint32_t FirstArg; 3878 if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3)) 3879 return; 3880 3881 // check if the function is variadic if the 3rd argument non-zero 3882 if (FirstArg != 0) { 3883 if (isFunctionOrMethodVariadic(D)) { 3884 ++NumArgs; // +1 for ... 3885 } else { 3886 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic); 3887 return; 3888 } 3889 } 3890 3891 // strftime requires FirstArg to be 0 because it doesn't read from any 3892 // variable the input is just the current time + the format string. 3893 if (Kind == StrftimeFormat) { 3894 if (FirstArg != 0) { 3895 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter) 3896 << FirstArgExpr->getSourceRange(); 3897 return; 3898 } 3899 // if 0 it disables parameter checking (to use with e.g. va_list) 3900 } else if (FirstArg != 0 && FirstArg != NumArgs) { 3901 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3902 << AL << 3 << FirstArgExpr->getSourceRange(); 3903 return; 3904 } 3905 3906 FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg); 3907 if (NewAttr) 3908 D->addAttr(NewAttr); 3909 } 3910 3911 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes. 3912 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3913 // The index that identifies the callback callee is mandatory. 3914 if (AL.getNumArgs() == 0) { 3915 S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee) 3916 << AL.getRange(); 3917 return; 3918 } 3919 3920 bool HasImplicitThisParam = isInstanceMethod(D); 3921 int32_t NumArgs = getFunctionOrMethodNumParams(D); 3922 3923 FunctionDecl *FD = D->getAsFunction(); 3924 assert(FD && "Expected a function declaration!"); 3925 3926 llvm::StringMap<int> NameIdxMapping; 3927 NameIdxMapping["__"] = -1; 3928 3929 NameIdxMapping["this"] = 0; 3930 3931 int Idx = 1; 3932 for (const ParmVarDecl *PVD : FD->parameters()) 3933 NameIdxMapping[PVD->getName()] = Idx++; 3934 3935 auto UnknownName = NameIdxMapping.end(); 3936 3937 SmallVector<int, 8> EncodingIndices; 3938 for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) { 3939 SourceRange SR; 3940 int32_t ArgIdx; 3941 3942 if (AL.isArgIdent(I)) { 3943 IdentifierLoc *IdLoc = AL.getArgAsIdent(I); 3944 auto It = NameIdxMapping.find(IdLoc->Ident->getName()); 3945 if (It == UnknownName) { 3946 S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown) 3947 << IdLoc->Ident << IdLoc->Loc; 3948 return; 3949 } 3950 3951 SR = SourceRange(IdLoc->Loc); 3952 ArgIdx = It->second; 3953 } else if (AL.isArgExpr(I)) { 3954 Expr *IdxExpr = AL.getArgAsExpr(I); 3955 3956 // If the expression is not parseable as an int32_t we have a problem. 3957 if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1, 3958 false)) { 3959 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3960 << AL << (I + 1) << IdxExpr->getSourceRange(); 3961 return; 3962 } 3963 3964 // Check oob, excluding the special values, 0 and -1. 3965 if (ArgIdx < -1 || ArgIdx > NumArgs) { 3966 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3967 << AL << (I + 1) << IdxExpr->getSourceRange(); 3968 return; 3969 } 3970 3971 SR = IdxExpr->getSourceRange(); 3972 } else { 3973 llvm_unreachable("Unexpected ParsedAttr argument type!"); 3974 } 3975 3976 if (ArgIdx == 0 && !HasImplicitThisParam) { 3977 S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available) 3978 << (I + 1) << SR; 3979 return; 3980 } 3981 3982 // Adjust for the case we do not have an implicit "this" parameter. In this 3983 // case we decrease all positive values by 1 to get LLVM argument indices. 3984 if (!HasImplicitThisParam && ArgIdx > 0) 3985 ArgIdx -= 1; 3986 3987 EncodingIndices.push_back(ArgIdx); 3988 } 3989 3990 int CalleeIdx = EncodingIndices.front(); 3991 // Check if the callee index is proper, thus not "this" and not "unknown". 3992 // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam" 3993 // is false and positive if "HasImplicitThisParam" is true. 3994 if (CalleeIdx < (int)HasImplicitThisParam) { 3995 S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee) 3996 << AL.getRange(); 3997 return; 3998 } 3999 4000 // Get the callee type, note the index adjustment as the AST doesn't contain 4001 // the this type (which the callee cannot reference anyway!). 4002 const Type *CalleeType = 4003 getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam) 4004 .getTypePtr(); 4005 if (!CalleeType || !CalleeType->isFunctionPointerType()) { 4006 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type) 4007 << AL.getRange(); 4008 return; 4009 } 4010 4011 const Type *CalleeFnType = 4012 CalleeType->getPointeeType()->getUnqualifiedDesugaredType(); 4013 4014 // TODO: Check the type of the callee arguments. 4015 4016 const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType); 4017 if (!CalleeFnProtoType) { 4018 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type) 4019 << AL.getRange(); 4020 return; 4021 } 4022 4023 if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) { 4024 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) 4025 << AL << (unsigned)(EncodingIndices.size() - 1); 4026 return; 4027 } 4028 4029 if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) { 4030 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) 4031 << AL << (unsigned)(EncodingIndices.size() - 1); 4032 return; 4033 } 4034 4035 if (CalleeFnProtoType->isVariadic()) { 4036 S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange(); 4037 return; 4038 } 4039 4040 // Do not allow multiple callback attributes. 4041 if (D->hasAttr<CallbackAttr>()) { 4042 S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange(); 4043 return; 4044 } 4045 4046 D->addAttr(::new (S.Context) CallbackAttr( 4047 S.Context, AL, EncodingIndices.data(), EncodingIndices.size())); 4048 } 4049 4050 static bool isFunctionLike(const Type &T) { 4051 // Check for explicit function types. 4052 // 'called_once' is only supported in Objective-C and it has 4053 // function pointers and block pointers. 4054 return T.isFunctionPointerType() || T.isBlockPointerType(); 4055 } 4056 4057 /// Handle 'called_once' attribute. 4058 static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4059 // 'called_once' only applies to parameters representing functions. 4060 QualType T = cast<ParmVarDecl>(D)->getType(); 4061 4062 if (!isFunctionLike(*T)) { 4063 S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type); 4064 return; 4065 } 4066 4067 D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL)); 4068 } 4069 4070 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4071 // Try to find the underlying union declaration. 4072 RecordDecl *RD = nullptr; 4073 const auto *TD = dyn_cast<TypedefNameDecl>(D); 4074 if (TD && TD->getUnderlyingType()->isUnionType()) 4075 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl(); 4076 else 4077 RD = dyn_cast<RecordDecl>(D); 4078 4079 if (!RD || !RD->isUnion()) { 4080 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL 4081 << ExpectedUnion; 4082 return; 4083 } 4084 4085 if (!RD->isCompleteDefinition()) { 4086 if (!RD->isBeingDefined()) 4087 S.Diag(AL.getLoc(), 4088 diag::warn_transparent_union_attribute_not_definition); 4089 return; 4090 } 4091 4092 RecordDecl::field_iterator Field = RD->field_begin(), 4093 FieldEnd = RD->field_end(); 4094 if (Field == FieldEnd) { 4095 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields); 4096 return; 4097 } 4098 4099 FieldDecl *FirstField = *Field; 4100 QualType FirstType = FirstField->getType(); 4101 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) { 4102 S.Diag(FirstField->getLocation(), 4103 diag::warn_transparent_union_attribute_floating) 4104 << FirstType->isVectorType() << FirstType; 4105 return; 4106 } 4107 4108 if (FirstType->isIncompleteType()) 4109 return; 4110 uint64_t FirstSize = S.Context.getTypeSize(FirstType); 4111 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType); 4112 for (; Field != FieldEnd; ++Field) { 4113 QualType FieldType = Field->getType(); 4114 if (FieldType->isIncompleteType()) 4115 return; 4116 // FIXME: this isn't fully correct; we also need to test whether the 4117 // members of the union would all have the same calling convention as the 4118 // first member of the union. Checking just the size and alignment isn't 4119 // sufficient (consider structs passed on the stack instead of in registers 4120 // as an example). 4121 if (S.Context.getTypeSize(FieldType) != FirstSize || 4122 S.Context.getTypeAlign(FieldType) > FirstAlign) { 4123 // Warn if we drop the attribute. 4124 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize; 4125 unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType) 4126 : S.Context.getTypeAlign(FieldType); 4127 S.Diag(Field->getLocation(), 4128 diag::warn_transparent_union_attribute_field_size_align) 4129 << isSize << *Field << FieldBits; 4130 unsigned FirstBits = isSize ? FirstSize : FirstAlign; 4131 S.Diag(FirstField->getLocation(), 4132 diag::note_transparent_union_first_field_size_align) 4133 << isSize << FirstBits; 4134 return; 4135 } 4136 } 4137 4138 RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL)); 4139 } 4140 4141 void Sema::AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, 4142 StringRef Str, MutableArrayRef<Expr *> Args) { 4143 auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI); 4144 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 4145 for (unsigned Idx = 0; Idx < Attr->args_size(); Idx++) { 4146 Expr *&E = Attr->args_begin()[Idx]; 4147 assert(E && "error are handled before"); 4148 if (E->isValueDependent() || E->isTypeDependent()) 4149 continue; 4150 4151 if (E->getType()->isArrayType()) 4152 E = ImpCastExprToType(E, Context.getPointerType(E->getType()), 4153 clang::CK_ArrayToPointerDecay) 4154 .get(); 4155 if (E->getType()->isFunctionType()) 4156 E = ImplicitCastExpr::Create(Context, 4157 Context.getPointerType(E->getType()), 4158 clang::CK_FunctionToPointerDecay, E, nullptr, 4159 VK_PRValue, FPOptionsOverride()); 4160 if (E->isLValue()) 4161 E = ImplicitCastExpr::Create(Context, E->getType().getNonReferenceType(), 4162 clang::CK_LValueToRValue, E, nullptr, 4163 VK_PRValue, FPOptionsOverride()); 4164 4165 Expr::EvalResult Eval; 4166 Notes.clear(); 4167 Eval.Diag = &Notes; 4168 4169 bool Result = 4170 E->EvaluateAsConstantExpr(Eval, Context); 4171 4172 /// Result means the expression can be folded to a constant. 4173 /// Note.empty() means the expression is a valid constant expression in the 4174 /// current language mode. 4175 if (!Result || !Notes.empty()) { 4176 Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type) 4177 << CI << (Idx + 1) << AANT_ArgumentConstantExpr; 4178 for (auto &Note : Notes) 4179 Diag(Note.first, Note.second); 4180 return; 4181 } 4182 assert(Eval.Val.hasValue()); 4183 E = ConstantExpr::Create(Context, E, Eval.Val); 4184 } 4185 D->addAttr(Attr); 4186 } 4187 4188 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4189 // Make sure that there is a string literal as the annotation's first 4190 // argument. 4191 StringRef Str; 4192 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 4193 return; 4194 4195 llvm::SmallVector<Expr *, 4> Args; 4196 Args.reserve(AL.getNumArgs() - 1); 4197 for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) { 4198 assert(!AL.isArgIdent(Idx)); 4199 Args.push_back(AL.getArgAsExpr(Idx)); 4200 } 4201 4202 S.AddAnnotationAttr(D, AL, Str, Args); 4203 } 4204 4205 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4206 S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0)); 4207 } 4208 4209 void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) { 4210 AlignValueAttr TmpAttr(Context, CI, E); 4211 SourceLocation AttrLoc = CI.getLoc(); 4212 4213 QualType T; 4214 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) 4215 T = TD->getUnderlyingType(); 4216 else if (const auto *VD = dyn_cast<ValueDecl>(D)) 4217 T = VD->getType(); 4218 else 4219 llvm_unreachable("Unknown decl type for align_value"); 4220 4221 if (!T->isDependentType() && !T->isAnyPointerType() && 4222 !T->isReferenceType() && !T->isMemberPointerType()) { 4223 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only) 4224 << &TmpAttr << T << D->getSourceRange(); 4225 return; 4226 } 4227 4228 if (!E->isValueDependent()) { 4229 llvm::APSInt Alignment; 4230 ExprResult ICE = VerifyIntegerConstantExpression( 4231 E, &Alignment, diag::err_align_value_attribute_argument_not_int); 4232 if (ICE.isInvalid()) 4233 return; 4234 4235 if (!Alignment.isPowerOf2()) { 4236 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 4237 << E->getSourceRange(); 4238 return; 4239 } 4240 4241 D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get())); 4242 return; 4243 } 4244 4245 // Save dependent expressions in the AST to be instantiated. 4246 D->addAttr(::new (Context) AlignValueAttr(Context, CI, E)); 4247 } 4248 4249 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4250 // check the attribute arguments. 4251 if (AL.getNumArgs() > 1) { 4252 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; 4253 return; 4254 } 4255 4256 if (AL.getNumArgs() == 0) { 4257 D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr)); 4258 return; 4259 } 4260 4261 Expr *E = AL.getArgAsExpr(0); 4262 if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) { 4263 S.Diag(AL.getEllipsisLoc(), 4264 diag::err_pack_expansion_without_parameter_packs); 4265 return; 4266 } 4267 4268 if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E)) 4269 return; 4270 4271 S.AddAlignedAttr(D, AL, E, AL.isPackExpansion()); 4272 } 4273 4274 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 4275 bool IsPackExpansion) { 4276 AlignedAttr TmpAttr(Context, CI, true, E); 4277 SourceLocation AttrLoc = CI.getLoc(); 4278 4279 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements. 4280 if (TmpAttr.isAlignas()) { 4281 // C++11 [dcl.align]p1: 4282 // An alignment-specifier may be applied to a variable or to a class 4283 // data member, but it shall not be applied to a bit-field, a function 4284 // parameter, the formal parameter of a catch clause, or a variable 4285 // declared with the register storage class specifier. An 4286 // alignment-specifier may also be applied to the declaration of a class 4287 // or enumeration type. 4288 // C11 6.7.5/2: 4289 // An alignment attribute shall not be specified in a declaration of 4290 // a typedef, or a bit-field, or a function, or a parameter, or an 4291 // object declared with the register storage-class specifier. 4292 int DiagKind = -1; 4293 if (isa<ParmVarDecl>(D)) { 4294 DiagKind = 0; 4295 } else if (const auto *VD = dyn_cast<VarDecl>(D)) { 4296 if (VD->getStorageClass() == SC_Register) 4297 DiagKind = 1; 4298 if (VD->isExceptionVariable()) 4299 DiagKind = 2; 4300 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) { 4301 if (FD->isBitField()) 4302 DiagKind = 3; 4303 } else if (!isa<TagDecl>(D)) { 4304 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr 4305 << (TmpAttr.isC11() ? ExpectedVariableOrField 4306 : ExpectedVariableFieldOrTag); 4307 return; 4308 } 4309 if (DiagKind != -1) { 4310 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type) 4311 << &TmpAttr << DiagKind; 4312 return; 4313 } 4314 } 4315 4316 if (E->isValueDependent()) { 4317 // We can't support a dependent alignment on a non-dependent type, 4318 // because we have no way to model that a type is "alignment-dependent" 4319 // but not dependent in any other way. 4320 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) { 4321 if (!TND->getUnderlyingType()->isDependentType()) { 4322 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name) 4323 << E->getSourceRange(); 4324 return; 4325 } 4326 } 4327 4328 // Save dependent expressions in the AST to be instantiated. 4329 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E); 4330 AA->setPackExpansion(IsPackExpansion); 4331 D->addAttr(AA); 4332 return; 4333 } 4334 4335 // FIXME: Cache the number on the AL object? 4336 llvm::APSInt Alignment; 4337 ExprResult ICE = VerifyIntegerConstantExpression( 4338 E, &Alignment, diag::err_aligned_attribute_argument_not_int); 4339 if (ICE.isInvalid()) 4340 return; 4341 4342 uint64_t AlignVal = Alignment.getZExtValue(); 4343 // 16 byte ByVal alignment not due to a vector member is not honoured by XL 4344 // on AIX. Emit a warning here that users are generating binary incompatible 4345 // code to be safe. 4346 if (AlignVal >= 16 && isa<FieldDecl>(D) && 4347 Context.getTargetInfo().getTriple().isOSAIX()) 4348 Diag(AttrLoc, diag::warn_not_xl_compatible) << E->getSourceRange(); 4349 4350 // C++11 [dcl.align]p2: 4351 // -- if the constant expression evaluates to zero, the alignment 4352 // specifier shall have no effect 4353 // C11 6.7.5p6: 4354 // An alignment specification of zero has no effect. 4355 if (!(TmpAttr.isAlignas() && !Alignment)) { 4356 if (!llvm::isPowerOf2_64(AlignVal)) { 4357 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 4358 << E->getSourceRange(); 4359 return; 4360 } 4361 } 4362 4363 uint64_t MaximumAlignment = Sema::MaximumAlignment; 4364 if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF()) 4365 MaximumAlignment = std::min(MaximumAlignment, uint64_t(8192)); 4366 if (AlignVal > MaximumAlignment) { 4367 Diag(AttrLoc, diag::err_attribute_aligned_too_great) 4368 << MaximumAlignment << E->getSourceRange(); 4369 return; 4370 } 4371 4372 const auto *VD = dyn_cast<VarDecl>(D); 4373 if (VD && Context.getTargetInfo().isTLSSupported()) { 4374 unsigned MaxTLSAlign = 4375 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign()) 4376 .getQuantity(); 4377 if (MaxTLSAlign && AlignVal > MaxTLSAlign && 4378 VD->getTLSKind() != VarDecl::TLS_None) { 4379 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 4380 << (unsigned)AlignVal << VD << MaxTLSAlign; 4381 return; 4382 } 4383 } 4384 4385 // On AIX, an aligned attribute can not decrease the alignment when applied 4386 // to a variable declaration with vector type. 4387 if (VD && Context.getTargetInfo().getTriple().isOSAIX()) { 4388 const Type *Ty = VD->getType().getTypePtr(); 4389 if (Ty->isVectorType() && AlignVal < 16) { 4390 Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned) 4391 << VD->getType() << 16; 4392 return; 4393 } 4394 } 4395 4396 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get()); 4397 AA->setPackExpansion(IsPackExpansion); 4398 D->addAttr(AA); 4399 } 4400 4401 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, 4402 TypeSourceInfo *TS, bool IsPackExpansion) { 4403 // FIXME: Cache the number on the AL object if non-dependent? 4404 // FIXME: Perform checking of type validity 4405 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS); 4406 AA->setPackExpansion(IsPackExpansion); 4407 D->addAttr(AA); 4408 } 4409 4410 void Sema::CheckAlignasUnderalignment(Decl *D) { 4411 assert(D->hasAttrs() && "no attributes on decl"); 4412 4413 QualType UnderlyingTy, DiagTy; 4414 if (const auto *VD = dyn_cast<ValueDecl>(D)) { 4415 UnderlyingTy = DiagTy = VD->getType(); 4416 } else { 4417 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D)); 4418 if (const auto *ED = dyn_cast<EnumDecl>(D)) 4419 UnderlyingTy = ED->getIntegerType(); 4420 } 4421 if (DiagTy->isDependentType() || DiagTy->isIncompleteType()) 4422 return; 4423 4424 // C++11 [dcl.align]p5, C11 6.7.5/4: 4425 // The combined effect of all alignment attributes in a declaration shall 4426 // not specify an alignment that is less strict than the alignment that 4427 // would otherwise be required for the entity being declared. 4428 AlignedAttr *AlignasAttr = nullptr; 4429 AlignedAttr *LastAlignedAttr = nullptr; 4430 unsigned Align = 0; 4431 for (auto *I : D->specific_attrs<AlignedAttr>()) { 4432 if (I->isAlignmentDependent()) 4433 return; 4434 if (I->isAlignas()) 4435 AlignasAttr = I; 4436 Align = std::max(Align, I->getAlignment(Context)); 4437 LastAlignedAttr = I; 4438 } 4439 4440 if (Align && DiagTy->isSizelessType()) { 4441 Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type) 4442 << LastAlignedAttr << DiagTy; 4443 } else if (AlignasAttr && Align) { 4444 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align); 4445 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy); 4446 if (NaturalAlign > RequestedAlign) 4447 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned) 4448 << DiagTy << (unsigned)NaturalAlign.getQuantity(); 4449 } 4450 } 4451 4452 bool Sema::checkMSInheritanceAttrOnDefinition( 4453 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 4454 MSInheritanceModel ExplicitModel) { 4455 assert(RD->hasDefinition() && "RD has no definition!"); 4456 4457 // We may not have seen base specifiers or any virtual methods yet. We will 4458 // have to wait until the record is defined to catch any mismatches. 4459 if (!RD->getDefinition()->isCompleteDefinition()) 4460 return false; 4461 4462 // The unspecified model never matches what a definition could need. 4463 if (ExplicitModel == MSInheritanceModel::Unspecified) 4464 return false; 4465 4466 if (BestCase) { 4467 if (RD->calculateInheritanceModel() == ExplicitModel) 4468 return false; 4469 } else { 4470 if (RD->calculateInheritanceModel() <= ExplicitModel) 4471 return false; 4472 } 4473 4474 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance) 4475 << 0 /*definition*/; 4476 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD; 4477 return true; 4478 } 4479 4480 /// parseModeAttrArg - Parses attribute mode string and returns parsed type 4481 /// attribute. 4482 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth, 4483 bool &IntegerMode, bool &ComplexMode, 4484 FloatModeKind &ExplicitType) { 4485 IntegerMode = true; 4486 ComplexMode = false; 4487 ExplicitType = FloatModeKind::NoFloat; 4488 switch (Str.size()) { 4489 case 2: 4490 switch (Str[0]) { 4491 case 'Q': 4492 DestWidth = 8; 4493 break; 4494 case 'H': 4495 DestWidth = 16; 4496 break; 4497 case 'S': 4498 DestWidth = 32; 4499 break; 4500 case 'D': 4501 DestWidth = 64; 4502 break; 4503 case 'X': 4504 DestWidth = 96; 4505 break; 4506 case 'K': // KFmode - IEEE quad precision (__float128) 4507 ExplicitType = FloatModeKind::Float128; 4508 DestWidth = Str[1] == 'I' ? 0 : 128; 4509 break; 4510 case 'T': 4511 ExplicitType = FloatModeKind::LongDouble; 4512 DestWidth = 128; 4513 break; 4514 case 'I': 4515 ExplicitType = FloatModeKind::Ibm128; 4516 DestWidth = Str[1] == 'I' ? 0 : 128; 4517 break; 4518 } 4519 if (Str[1] == 'F') { 4520 IntegerMode = false; 4521 } else if (Str[1] == 'C') { 4522 IntegerMode = false; 4523 ComplexMode = true; 4524 } else if (Str[1] != 'I') { 4525 DestWidth = 0; 4526 } 4527 break; 4528 case 4: 4529 // FIXME: glibc uses 'word' to define register_t; this is narrower than a 4530 // pointer on PIC16 and other embedded platforms. 4531 if (Str == "word") 4532 DestWidth = S.Context.getTargetInfo().getRegisterWidth(); 4533 else if (Str == "byte") 4534 DestWidth = S.Context.getTargetInfo().getCharWidth(); 4535 break; 4536 case 7: 4537 if (Str == "pointer") 4538 DestWidth = S.Context.getTargetInfo().getPointerWidth(0); 4539 break; 4540 case 11: 4541 if (Str == "unwind_word") 4542 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth(); 4543 break; 4544 } 4545 } 4546 4547 /// handleModeAttr - This attribute modifies the width of a decl with primitive 4548 /// type. 4549 /// 4550 /// Despite what would be logical, the mode attribute is a decl attribute, not a 4551 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be 4552 /// HImode, not an intermediate pointer. 4553 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4554 // This attribute isn't documented, but glibc uses it. It changes 4555 // the width of an int or unsigned int to the specified size. 4556 if (!AL.isArgIdent(0)) { 4557 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 4558 << AL << AANT_ArgumentIdentifier; 4559 return; 4560 } 4561 4562 IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident; 4563 4564 S.AddModeAttr(D, AL, Name); 4565 } 4566 4567 void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI, 4568 IdentifierInfo *Name, bool InInstantiation) { 4569 StringRef Str = Name->getName(); 4570 normalizeName(Str); 4571 SourceLocation AttrLoc = CI.getLoc(); 4572 4573 unsigned DestWidth = 0; 4574 bool IntegerMode = true; 4575 bool ComplexMode = false; 4576 FloatModeKind ExplicitType = FloatModeKind::NoFloat; 4577 llvm::APInt VectorSize(64, 0); 4578 if (Str.size() >= 4 && Str[0] == 'V') { 4579 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2). 4580 size_t StrSize = Str.size(); 4581 size_t VectorStringLength = 0; 4582 while ((VectorStringLength + 1) < StrSize && 4583 isdigit(Str[VectorStringLength + 1])) 4584 ++VectorStringLength; 4585 if (VectorStringLength && 4586 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) && 4587 VectorSize.isPowerOf2()) { 4588 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth, 4589 IntegerMode, ComplexMode, ExplicitType); 4590 // Avoid duplicate warning from template instantiation. 4591 if (!InInstantiation) 4592 Diag(AttrLoc, diag::warn_vector_mode_deprecated); 4593 } else { 4594 VectorSize = 0; 4595 } 4596 } 4597 4598 if (!VectorSize) 4599 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode, 4600 ExplicitType); 4601 4602 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t 4603 // and friends, at least with glibc. 4604 // FIXME: Make sure floating-point mappings are accurate 4605 // FIXME: Support XF and TF types 4606 if (!DestWidth) { 4607 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name; 4608 return; 4609 } 4610 4611 QualType OldTy; 4612 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) 4613 OldTy = TD->getUnderlyingType(); 4614 else if (const auto *ED = dyn_cast<EnumDecl>(D)) { 4615 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'. 4616 // Try to get type from enum declaration, default to int. 4617 OldTy = ED->getIntegerType(); 4618 if (OldTy.isNull()) 4619 OldTy = Context.IntTy; 4620 } else 4621 OldTy = cast<ValueDecl>(D)->getType(); 4622 4623 if (OldTy->isDependentType()) { 4624 D->addAttr(::new (Context) ModeAttr(Context, CI, Name)); 4625 return; 4626 } 4627 4628 // Base type can also be a vector type (see PR17453). 4629 // Distinguish between base type and base element type. 4630 QualType OldElemTy = OldTy; 4631 if (const auto *VT = OldTy->getAs<VectorType>()) 4632 OldElemTy = VT->getElementType(); 4633 4634 // GCC allows 'mode' attribute on enumeration types (even incomplete), except 4635 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete 4636 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected. 4637 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) && 4638 VectorSize.getBoolValue()) { 4639 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange(); 4640 return; 4641 } 4642 bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() && 4643 !OldElemTy->isBitIntType()) || 4644 OldElemTy->getAs<EnumType>(); 4645 4646 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() && 4647 !IntegralOrAnyEnumType) 4648 Diag(AttrLoc, diag::err_mode_not_primitive); 4649 else if (IntegerMode) { 4650 if (!IntegralOrAnyEnumType) 4651 Diag(AttrLoc, diag::err_mode_wrong_type); 4652 } else if (ComplexMode) { 4653 if (!OldElemTy->isComplexType()) 4654 Diag(AttrLoc, diag::err_mode_wrong_type); 4655 } else { 4656 if (!OldElemTy->isFloatingType()) 4657 Diag(AttrLoc, diag::err_mode_wrong_type); 4658 } 4659 4660 QualType NewElemTy; 4661 4662 if (IntegerMode) 4663 NewElemTy = Context.getIntTypeForBitwidth(DestWidth, 4664 OldElemTy->isSignedIntegerType()); 4665 else 4666 NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitType); 4667 4668 if (NewElemTy.isNull()) { 4669 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name; 4670 return; 4671 } 4672 4673 if (ComplexMode) { 4674 NewElemTy = Context.getComplexType(NewElemTy); 4675 } 4676 4677 QualType NewTy = NewElemTy; 4678 if (VectorSize.getBoolValue()) { 4679 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(), 4680 VectorType::GenericVector); 4681 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) { 4682 // Complex machine mode does not support base vector types. 4683 if (ComplexMode) { 4684 Diag(AttrLoc, diag::err_complex_mode_vector_type); 4685 return; 4686 } 4687 unsigned NumElements = Context.getTypeSize(OldElemTy) * 4688 OldVT->getNumElements() / 4689 Context.getTypeSize(NewElemTy); 4690 NewTy = 4691 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind()); 4692 } 4693 4694 if (NewTy.isNull()) { 4695 Diag(AttrLoc, diag::err_mode_wrong_type); 4696 return; 4697 } 4698 4699 // Install the new type. 4700 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) 4701 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy); 4702 else if (auto *ED = dyn_cast<EnumDecl>(D)) 4703 ED->setIntegerType(NewTy); 4704 else 4705 cast<ValueDecl>(D)->setType(NewTy); 4706 4707 D->addAttr(::new (Context) ModeAttr(Context, CI, Name)); 4708 } 4709 4710 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4711 D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL)); 4712 } 4713 4714 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, 4715 const AttributeCommonInfo &CI, 4716 const IdentifierInfo *Ident) { 4717 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 4718 Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident; 4719 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 4720 return nullptr; 4721 } 4722 4723 if (D->hasAttr<AlwaysInlineAttr>()) 4724 return nullptr; 4725 4726 return ::new (Context) AlwaysInlineAttr(Context, CI); 4727 } 4728 4729 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D, 4730 const ParsedAttr &AL) { 4731 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4732 // Attribute applies to Var but not any subclass of it (like ParmVar, 4733 // ImplicitParm or VarTemplateSpecialization). 4734 if (VD->getKind() != Decl::Var) { 4735 Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 4736 << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass 4737 : ExpectedVariableOrFunction); 4738 return nullptr; 4739 } 4740 // Attribute does not apply to non-static local variables. 4741 if (VD->hasLocalStorage()) { 4742 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage); 4743 return nullptr; 4744 } 4745 } 4746 4747 return ::new (Context) InternalLinkageAttr(Context, AL); 4748 } 4749 InternalLinkageAttr * 4750 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) { 4751 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4752 // Attribute applies to Var but not any subclass of it (like ParmVar, 4753 // ImplicitParm or VarTemplateSpecialization). 4754 if (VD->getKind() != Decl::Var) { 4755 Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type) 4756 << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass 4757 : ExpectedVariableOrFunction); 4758 return nullptr; 4759 } 4760 // Attribute does not apply to non-static local variables. 4761 if (VD->hasLocalStorage()) { 4762 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage); 4763 return nullptr; 4764 } 4765 } 4766 4767 return ::new (Context) InternalLinkageAttr(Context, AL); 4768 } 4769 4770 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) { 4771 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 4772 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'"; 4773 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 4774 return nullptr; 4775 } 4776 4777 if (D->hasAttr<MinSizeAttr>()) 4778 return nullptr; 4779 4780 return ::new (Context) MinSizeAttr(Context, CI); 4781 } 4782 4783 SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, 4784 StringRef Name) { 4785 if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) { 4786 if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) { 4787 Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible) 4788 << PrevSNA << &SNA; 4789 Diag(SNA.getLoc(), diag::note_conflicting_attribute); 4790 } 4791 4792 D->dropAttr<SwiftNameAttr>(); 4793 } 4794 return ::new (Context) SwiftNameAttr(Context, SNA, Name); 4795 } 4796 4797 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, 4798 const AttributeCommonInfo &CI) { 4799 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) { 4800 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline; 4801 Diag(CI.getLoc(), diag::note_conflicting_attribute); 4802 D->dropAttr<AlwaysInlineAttr>(); 4803 } 4804 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) { 4805 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize; 4806 Diag(CI.getLoc(), diag::note_conflicting_attribute); 4807 D->dropAttr<MinSizeAttr>(); 4808 } 4809 4810 if (D->hasAttr<OptimizeNoneAttr>()) 4811 return nullptr; 4812 4813 return ::new (Context) OptimizeNoneAttr(Context, CI); 4814 } 4815 4816 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4817 if (AlwaysInlineAttr *Inline = 4818 S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName())) 4819 D->addAttr(Inline); 4820 } 4821 4822 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4823 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL)) 4824 D->addAttr(MinSize); 4825 } 4826 4827 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4828 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL)) 4829 D->addAttr(Optnone); 4830 } 4831 4832 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4833 const auto *VD = cast<VarDecl>(D); 4834 if (VD->hasLocalStorage()) { 4835 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev); 4836 return; 4837 } 4838 // constexpr variable may already get an implicit constant attr, which should 4839 // be replaced by the explicit constant attr. 4840 if (auto *A = D->getAttr<CUDAConstantAttr>()) { 4841 if (!A->isImplicit()) 4842 return; 4843 D->dropAttr<CUDAConstantAttr>(); 4844 } 4845 D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL)); 4846 } 4847 4848 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4849 const auto *VD = cast<VarDecl>(D); 4850 // extern __shared__ is only allowed on arrays with no length (e.g. 4851 // "int x[]"). 4852 if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() && 4853 !isa<IncompleteArrayType>(VD->getType())) { 4854 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD; 4855 return; 4856 } 4857 if (S.getLangOpts().CUDA && VD->hasLocalStorage() && 4858 S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared) 4859 << S.CurrentCUDATarget()) 4860 return; 4861 D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL)); 4862 } 4863 4864 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4865 const auto *FD = cast<FunctionDecl>(D); 4866 if (!FD->getReturnType()->isVoidType() && 4867 !FD->getReturnType()->getAs<AutoType>() && 4868 !FD->getReturnType()->isInstantiationDependentType()) { 4869 SourceRange RTRange = FD->getReturnTypeSourceRange(); 4870 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return) 4871 << FD->getType() 4872 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 4873 : FixItHint()); 4874 return; 4875 } 4876 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) { 4877 if (Method->isInstance()) { 4878 S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method) 4879 << Method; 4880 return; 4881 } 4882 S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method; 4883 } 4884 // Only warn for "inline" when compiling for host, to cut down on noise. 4885 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice) 4886 S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD; 4887 4888 D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL)); 4889 // In host compilation the kernel is emitted as a stub function, which is 4890 // a helper function for launching the kernel. The instructions in the helper 4891 // function has nothing to do with the source code of the kernel. Do not emit 4892 // debug info for the stub function to avoid confusing the debugger. 4893 if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice) 4894 D->addAttr(NoDebugAttr::CreateImplicit(S.Context)); 4895 } 4896 4897 static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4898 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4899 if (VD->hasLocalStorage()) { 4900 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev); 4901 return; 4902 } 4903 } 4904 4905 if (auto *A = D->getAttr<CUDADeviceAttr>()) { 4906 if (!A->isImplicit()) 4907 return; 4908 D->dropAttr<CUDADeviceAttr>(); 4909 } 4910 D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL)); 4911 } 4912 4913 static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4914 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4915 if (VD->hasLocalStorage()) { 4916 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev); 4917 return; 4918 } 4919 } 4920 if (!D->hasAttr<HIPManagedAttr>()) 4921 D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL)); 4922 if (!D->hasAttr<CUDADeviceAttr>()) 4923 D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context)); 4924 } 4925 4926 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4927 const auto *Fn = cast<FunctionDecl>(D); 4928 if (!Fn->isInlineSpecified()) { 4929 S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline); 4930 return; 4931 } 4932 4933 if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern) 4934 S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern); 4935 4936 D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL)); 4937 } 4938 4939 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4940 if (hasDeclarator(D)) return; 4941 4942 // Diagnostic is emitted elsewhere: here we store the (valid) AL 4943 // in the Decl node for syntactic reasoning, e.g., pretty-printing. 4944 CallingConv CC; 4945 if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr)) 4946 return; 4947 4948 if (!isa<ObjCMethodDecl>(D)) { 4949 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 4950 << AL << ExpectedFunctionOrMethod; 4951 return; 4952 } 4953 4954 switch (AL.getKind()) { 4955 case ParsedAttr::AT_FastCall: 4956 D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL)); 4957 return; 4958 case ParsedAttr::AT_StdCall: 4959 D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL)); 4960 return; 4961 case ParsedAttr::AT_ThisCall: 4962 D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL)); 4963 return; 4964 case ParsedAttr::AT_CDecl: 4965 D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL)); 4966 return; 4967 case ParsedAttr::AT_Pascal: 4968 D->addAttr(::new (S.Context) PascalAttr(S.Context, AL)); 4969 return; 4970 case ParsedAttr::AT_SwiftCall: 4971 D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL)); 4972 return; 4973 case ParsedAttr::AT_SwiftAsyncCall: 4974 D->addAttr(::new (S.Context) SwiftAsyncCallAttr(S.Context, AL)); 4975 return; 4976 case ParsedAttr::AT_VectorCall: 4977 D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL)); 4978 return; 4979 case ParsedAttr::AT_MSABI: 4980 D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL)); 4981 return; 4982 case ParsedAttr::AT_SysVABI: 4983 D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL)); 4984 return; 4985 case ParsedAttr::AT_RegCall: 4986 D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL)); 4987 return; 4988 case ParsedAttr::AT_Pcs: { 4989 PcsAttr::PCSType PCS; 4990 switch (CC) { 4991 case CC_AAPCS: 4992 PCS = PcsAttr::AAPCS; 4993 break; 4994 case CC_AAPCS_VFP: 4995 PCS = PcsAttr::AAPCS_VFP; 4996 break; 4997 default: 4998 llvm_unreachable("unexpected calling convention in pcs attribute"); 4999 } 5000 5001 D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS)); 5002 return; 5003 } 5004 case ParsedAttr::AT_AArch64VectorPcs: 5005 D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL)); 5006 return; 5007 case ParsedAttr::AT_IntelOclBicc: 5008 D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL)); 5009 return; 5010 case ParsedAttr::AT_PreserveMost: 5011 D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL)); 5012 return; 5013 case ParsedAttr::AT_PreserveAll: 5014 D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL)); 5015 return; 5016 default: 5017 llvm_unreachable("unexpected attribute kind"); 5018 } 5019 } 5020 5021 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5022 if (!AL.checkAtLeastNumArgs(S, 1)) 5023 return; 5024 5025 std::vector<StringRef> DiagnosticIdentifiers; 5026 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 5027 StringRef RuleName; 5028 5029 if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr)) 5030 return; 5031 5032 // FIXME: Warn if the rule name is unknown. This is tricky because only 5033 // clang-tidy knows about available rules. 5034 DiagnosticIdentifiers.push_back(RuleName); 5035 } 5036 D->addAttr(::new (S.Context) 5037 SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(), 5038 DiagnosticIdentifiers.size())); 5039 } 5040 5041 static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5042 TypeSourceInfo *DerefTypeLoc = nullptr; 5043 QualType ParmType; 5044 if (AL.hasParsedType()) { 5045 ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc); 5046 5047 unsigned SelectIdx = ~0U; 5048 if (ParmType->isReferenceType()) 5049 SelectIdx = 0; 5050 else if (ParmType->isArrayType()) 5051 SelectIdx = 1; 5052 5053 if (SelectIdx != ~0U) { 5054 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) 5055 << SelectIdx << AL; 5056 return; 5057 } 5058 } 5059 5060 // To check if earlier decl attributes do not conflict the newly parsed ones 5061 // we always add (and check) the attribute to the canonical decl. We need 5062 // to repeat the check for attribute mutual exclusion because we're attaching 5063 // all of the attributes to the canonical declaration rather than the current 5064 // declaration. 5065 D = D->getCanonicalDecl(); 5066 if (AL.getKind() == ParsedAttr::AT_Owner) { 5067 if (checkAttrMutualExclusion<PointerAttr>(S, D, AL)) 5068 return; 5069 if (const auto *OAttr = D->getAttr<OwnerAttr>()) { 5070 const Type *ExistingDerefType = OAttr->getDerefTypeLoc() 5071 ? OAttr->getDerefType().getTypePtr() 5072 : nullptr; 5073 if (ExistingDerefType != ParmType.getTypePtrOrNull()) { 5074 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) 5075 << AL << OAttr; 5076 S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute); 5077 } 5078 return; 5079 } 5080 for (Decl *Redecl : D->redecls()) { 5081 Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc)); 5082 } 5083 } else { 5084 if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL)) 5085 return; 5086 if (const auto *PAttr = D->getAttr<PointerAttr>()) { 5087 const Type *ExistingDerefType = PAttr->getDerefTypeLoc() 5088 ? PAttr->getDerefType().getTypePtr() 5089 : nullptr; 5090 if (ExistingDerefType != ParmType.getTypePtrOrNull()) { 5091 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) 5092 << AL << PAttr; 5093 S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute); 5094 } 5095 return; 5096 } 5097 for (Decl *Redecl : D->redecls()) { 5098 Redecl->addAttr(::new (S.Context) 5099 PointerAttr(S.Context, AL, DerefTypeLoc)); 5100 } 5101 } 5102 } 5103 5104 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC, 5105 const FunctionDecl *FD) { 5106 if (Attrs.isInvalid()) 5107 return true; 5108 5109 if (Attrs.hasProcessingCache()) { 5110 CC = (CallingConv) Attrs.getProcessingCache(); 5111 return false; 5112 } 5113 5114 unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0; 5115 if (!Attrs.checkExactlyNumArgs(*this, ReqArgs)) { 5116 Attrs.setInvalid(); 5117 return true; 5118 } 5119 5120 // TODO: diagnose uses of these conventions on the wrong target. 5121 switch (Attrs.getKind()) { 5122 case ParsedAttr::AT_CDecl: 5123 CC = CC_C; 5124 break; 5125 case ParsedAttr::AT_FastCall: 5126 CC = CC_X86FastCall; 5127 break; 5128 case ParsedAttr::AT_StdCall: 5129 CC = CC_X86StdCall; 5130 break; 5131 case ParsedAttr::AT_ThisCall: 5132 CC = CC_X86ThisCall; 5133 break; 5134 case ParsedAttr::AT_Pascal: 5135 CC = CC_X86Pascal; 5136 break; 5137 case ParsedAttr::AT_SwiftCall: 5138 CC = CC_Swift; 5139 break; 5140 case ParsedAttr::AT_SwiftAsyncCall: 5141 CC = CC_SwiftAsync; 5142 break; 5143 case ParsedAttr::AT_VectorCall: 5144 CC = CC_X86VectorCall; 5145 break; 5146 case ParsedAttr::AT_AArch64VectorPcs: 5147 CC = CC_AArch64VectorCall; 5148 break; 5149 case ParsedAttr::AT_RegCall: 5150 CC = CC_X86RegCall; 5151 break; 5152 case ParsedAttr::AT_MSABI: 5153 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : 5154 CC_Win64; 5155 break; 5156 case ParsedAttr::AT_SysVABI: 5157 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV : 5158 CC_C; 5159 break; 5160 case ParsedAttr::AT_Pcs: { 5161 StringRef StrRef; 5162 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) { 5163 Attrs.setInvalid(); 5164 return true; 5165 } 5166 if (StrRef == "aapcs") { 5167 CC = CC_AAPCS; 5168 break; 5169 } else if (StrRef == "aapcs-vfp") { 5170 CC = CC_AAPCS_VFP; 5171 break; 5172 } 5173 5174 Attrs.setInvalid(); 5175 Diag(Attrs.getLoc(), diag::err_invalid_pcs); 5176 return true; 5177 } 5178 case ParsedAttr::AT_IntelOclBicc: 5179 CC = CC_IntelOclBicc; 5180 break; 5181 case ParsedAttr::AT_PreserveMost: 5182 CC = CC_PreserveMost; 5183 break; 5184 case ParsedAttr::AT_PreserveAll: 5185 CC = CC_PreserveAll; 5186 break; 5187 default: llvm_unreachable("unexpected attribute kind"); 5188 } 5189 5190 TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK; 5191 const TargetInfo &TI = Context.getTargetInfo(); 5192 // CUDA functions may have host and/or device attributes which indicate 5193 // their targeted execution environment, therefore the calling convention 5194 // of functions in CUDA should be checked against the target deduced based 5195 // on their host/device attributes. 5196 if (LangOpts.CUDA) { 5197 auto *Aux = Context.getAuxTargetInfo(); 5198 auto CudaTarget = IdentifyCUDATarget(FD); 5199 bool CheckHost = false, CheckDevice = false; 5200 switch (CudaTarget) { 5201 case CFT_HostDevice: 5202 CheckHost = true; 5203 CheckDevice = true; 5204 break; 5205 case CFT_Host: 5206 CheckHost = true; 5207 break; 5208 case CFT_Device: 5209 case CFT_Global: 5210 CheckDevice = true; 5211 break; 5212 case CFT_InvalidTarget: 5213 llvm_unreachable("unexpected cuda target"); 5214 } 5215 auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI; 5216 auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux; 5217 if (CheckHost && HostTI) 5218 A = HostTI->checkCallingConvention(CC); 5219 if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI) 5220 A = DeviceTI->checkCallingConvention(CC); 5221 } else { 5222 A = TI.checkCallingConvention(CC); 5223 } 5224 5225 switch (A) { 5226 case TargetInfo::CCCR_OK: 5227 break; 5228 5229 case TargetInfo::CCCR_Ignore: 5230 // Treat an ignored convention as if it was an explicit C calling convention 5231 // attribute. For example, __stdcall on Win x64 functions as __cdecl, so 5232 // that command line flags that change the default convention to 5233 // __vectorcall don't affect declarations marked __stdcall. 5234 CC = CC_C; 5235 break; 5236 5237 case TargetInfo::CCCR_Error: 5238 Diag(Attrs.getLoc(), diag::error_cconv_unsupported) 5239 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget; 5240 break; 5241 5242 case TargetInfo::CCCR_Warning: { 5243 Diag(Attrs.getLoc(), diag::warn_cconv_unsupported) 5244 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget; 5245 5246 // This convention is not valid for the target. Use the default function or 5247 // method calling convention. 5248 bool IsCXXMethod = false, IsVariadic = false; 5249 if (FD) { 5250 IsCXXMethod = FD->isCXXInstanceMember(); 5251 IsVariadic = FD->isVariadic(); 5252 } 5253 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod); 5254 break; 5255 } 5256 } 5257 5258 Attrs.setProcessingCache((unsigned) CC); 5259 return false; 5260 } 5261 5262 /// Pointer-like types in the default address space. 5263 static bool isValidSwiftContextType(QualType Ty) { 5264 if (!Ty->hasPointerRepresentation()) 5265 return Ty->isDependentType(); 5266 return Ty->getPointeeType().getAddressSpace() == LangAS::Default; 5267 } 5268 5269 /// Pointers and references in the default address space. 5270 static bool isValidSwiftIndirectResultType(QualType Ty) { 5271 if (const auto *PtrType = Ty->getAs<PointerType>()) { 5272 Ty = PtrType->getPointeeType(); 5273 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) { 5274 Ty = RefType->getPointeeType(); 5275 } else { 5276 return Ty->isDependentType(); 5277 } 5278 return Ty.getAddressSpace() == LangAS::Default; 5279 } 5280 5281 /// Pointers and references to pointers in the default address space. 5282 static bool isValidSwiftErrorResultType(QualType Ty) { 5283 if (const auto *PtrType = Ty->getAs<PointerType>()) { 5284 Ty = PtrType->getPointeeType(); 5285 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) { 5286 Ty = RefType->getPointeeType(); 5287 } else { 5288 return Ty->isDependentType(); 5289 } 5290 if (!Ty.getQualifiers().empty()) 5291 return false; 5292 return isValidSwiftContextType(Ty); 5293 } 5294 5295 void Sema::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, 5296 ParameterABI abi) { 5297 5298 QualType type = cast<ParmVarDecl>(D)->getType(); 5299 5300 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) { 5301 if (existingAttr->getABI() != abi) { 5302 Diag(CI.getLoc(), diag::err_attributes_are_not_compatible) 5303 << getParameterABISpelling(abi) << existingAttr; 5304 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute); 5305 return; 5306 } 5307 } 5308 5309 switch (abi) { 5310 case ParameterABI::Ordinary: 5311 llvm_unreachable("explicit attribute for ordinary parameter ABI?"); 5312 5313 case ParameterABI::SwiftContext: 5314 if (!isValidSwiftContextType(type)) { 5315 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type) 5316 << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type; 5317 } 5318 D->addAttr(::new (Context) SwiftContextAttr(Context, CI)); 5319 return; 5320 5321 case ParameterABI::SwiftAsyncContext: 5322 if (!isValidSwiftContextType(type)) { 5323 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type) 5324 << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type; 5325 } 5326 D->addAttr(::new (Context) SwiftAsyncContextAttr(Context, CI)); 5327 return; 5328 5329 case ParameterABI::SwiftErrorResult: 5330 if (!isValidSwiftErrorResultType(type)) { 5331 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type) 5332 << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type; 5333 } 5334 D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI)); 5335 return; 5336 5337 case ParameterABI::SwiftIndirectResult: 5338 if (!isValidSwiftIndirectResultType(type)) { 5339 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type) 5340 << getParameterABISpelling(abi) << /*pointer*/ 0 << type; 5341 } 5342 D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI)); 5343 return; 5344 } 5345 llvm_unreachable("bad parameter ABI attribute"); 5346 } 5347 5348 /// Checks a regparm attribute, returning true if it is ill-formed and 5349 /// otherwise setting numParams to the appropriate value. 5350 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) { 5351 if (AL.isInvalid()) 5352 return true; 5353 5354 if (!AL.checkExactlyNumArgs(*this, 1)) { 5355 AL.setInvalid(); 5356 return true; 5357 } 5358 5359 uint32_t NP; 5360 Expr *NumParamsExpr = AL.getArgAsExpr(0); 5361 if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) { 5362 AL.setInvalid(); 5363 return true; 5364 } 5365 5366 if (Context.getTargetInfo().getRegParmMax() == 0) { 5367 Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform) 5368 << NumParamsExpr->getSourceRange(); 5369 AL.setInvalid(); 5370 return true; 5371 } 5372 5373 numParams = NP; 5374 if (numParams > Context.getTargetInfo().getRegParmMax()) { 5375 Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number) 5376 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange(); 5377 AL.setInvalid(); 5378 return true; 5379 } 5380 5381 return false; 5382 } 5383 5384 // Checks whether an argument of launch_bounds attribute is 5385 // acceptable, performs implicit conversion to Rvalue, and returns 5386 // non-nullptr Expr result on success. Otherwise, it returns nullptr 5387 // and may output an error. 5388 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E, 5389 const CUDALaunchBoundsAttr &AL, 5390 const unsigned Idx) { 5391 if (S.DiagnoseUnexpandedParameterPack(E)) 5392 return nullptr; 5393 5394 // Accept template arguments for now as they depend on something else. 5395 // We'll get to check them when they eventually get instantiated. 5396 if (E->isValueDependent()) 5397 return E; 5398 5399 Optional<llvm::APSInt> I = llvm::APSInt(64); 5400 if (!(I = E->getIntegerConstantExpr(S.Context))) { 5401 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type) 5402 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange(); 5403 return nullptr; 5404 } 5405 // Make sure we can fit it in 32 bits. 5406 if (!I->isIntN(32)) { 5407 S.Diag(E->getExprLoc(), diag::err_ice_too_large) 5408 << toString(*I, 10, false) << 32 << /* Unsigned */ 1; 5409 return nullptr; 5410 } 5411 if (*I < 0) 5412 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative) 5413 << &AL << Idx << E->getSourceRange(); 5414 5415 // We may need to perform implicit conversion of the argument. 5416 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5417 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false); 5418 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E); 5419 assert(!ValArg.isInvalid() && 5420 "Unexpected PerformCopyInitialization() failure."); 5421 5422 return ValArg.getAs<Expr>(); 5423 } 5424 5425 void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, 5426 Expr *MaxThreads, Expr *MinBlocks) { 5427 CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks); 5428 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0); 5429 if (MaxThreads == nullptr) 5430 return; 5431 5432 if (MinBlocks) { 5433 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1); 5434 if (MinBlocks == nullptr) 5435 return; 5436 } 5437 5438 D->addAttr(::new (Context) 5439 CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks)); 5440 } 5441 5442 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5443 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2)) 5444 return; 5445 5446 S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0), 5447 AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr); 5448 } 5449 5450 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D, 5451 const ParsedAttr &AL) { 5452 if (!AL.isArgIdent(0)) { 5453 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 5454 << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier; 5455 return; 5456 } 5457 5458 ParamIdx ArgumentIdx; 5459 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1), 5460 ArgumentIdx)) 5461 return; 5462 5463 ParamIdx TypeTagIdx; 5464 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2), 5465 TypeTagIdx)) 5466 return; 5467 5468 bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag"; 5469 if (IsPointer) { 5470 // Ensure that buffer has a pointer type. 5471 unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex(); 5472 if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) || 5473 !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType()) 5474 S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0; 5475 } 5476 5477 D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr( 5478 S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx, 5479 IsPointer)); 5480 } 5481 5482 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D, 5483 const ParsedAttr &AL) { 5484 if (!AL.isArgIdent(0)) { 5485 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 5486 << AL << 1 << AANT_ArgumentIdentifier; 5487 return; 5488 } 5489 5490 if (!AL.checkExactlyNumArgs(S, 1)) 5491 return; 5492 5493 if (!isa<VarDecl>(D)) { 5494 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type) 5495 << AL << ExpectedVariable; 5496 return; 5497 } 5498 5499 IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident; 5500 TypeSourceInfo *MatchingCTypeLoc = nullptr; 5501 S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc); 5502 assert(MatchingCTypeLoc && "no type source info for attribute argument"); 5503 5504 D->addAttr(::new (S.Context) TypeTagForDatatypeAttr( 5505 S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(), 5506 AL.getMustBeNull())); 5507 } 5508 5509 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5510 ParamIdx ArgCount; 5511 5512 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0), 5513 ArgCount, 5514 true /* CanIndexImplicitThis */)) 5515 return; 5516 5517 // ArgCount isn't a parameter index [0;n), it's a count [1;n] 5518 D->addAttr(::new (S.Context) 5519 XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex())); 5520 } 5521 5522 static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D, 5523 const ParsedAttr &AL) { 5524 uint32_t Count = 0, Offset = 0; 5525 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Count, 0, true)) 5526 return; 5527 if (AL.getNumArgs() == 2) { 5528 Expr *Arg = AL.getArgAsExpr(1); 5529 if (!checkUInt32Argument(S, AL, Arg, Offset, 1, true)) 5530 return; 5531 if (Count < Offset) { 5532 S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range) 5533 << &AL << 0 << Count << Arg->getBeginLoc(); 5534 return; 5535 } 5536 } 5537 D->addAttr(::new (S.Context) 5538 PatchableFunctionEntryAttr(S.Context, AL, Count, Offset)); 5539 } 5540 5541 namespace { 5542 struct IntrinToName { 5543 uint32_t Id; 5544 int32_t FullName; 5545 int32_t ShortName; 5546 }; 5547 } // unnamed namespace 5548 5549 static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName, 5550 ArrayRef<IntrinToName> Map, 5551 const char *IntrinNames) { 5552 if (AliasName.startswith("__arm_")) 5553 AliasName = AliasName.substr(6); 5554 const IntrinToName *It = std::lower_bound( 5555 Map.begin(), Map.end(), BuiltinID, 5556 [](const IntrinToName &L, unsigned Id) { return L.Id < Id; }); 5557 if (It == Map.end() || It->Id != BuiltinID) 5558 return false; 5559 StringRef FullName(&IntrinNames[It->FullName]); 5560 if (AliasName == FullName) 5561 return true; 5562 if (It->ShortName == -1) 5563 return false; 5564 StringRef ShortName(&IntrinNames[It->ShortName]); 5565 return AliasName == ShortName; 5566 } 5567 5568 static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) { 5569 #include "clang/Basic/arm_mve_builtin_aliases.inc" 5570 // The included file defines: 5571 // - ArrayRef<IntrinToName> Map 5572 // - const char IntrinNames[] 5573 return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames); 5574 } 5575 5576 static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) { 5577 #include "clang/Basic/arm_cde_builtin_aliases.inc" 5578 return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames); 5579 } 5580 5581 static bool ArmSveAliasValid(ASTContext &Context, unsigned BuiltinID, 5582 StringRef AliasName) { 5583 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 5584 BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(BuiltinID); 5585 return BuiltinID >= AArch64::FirstSVEBuiltin && 5586 BuiltinID <= AArch64::LastSVEBuiltin; 5587 } 5588 5589 static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5590 if (!AL.isArgIdent(0)) { 5591 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 5592 << AL << 1 << AANT_ArgumentIdentifier; 5593 return; 5594 } 5595 5596 IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident; 5597 unsigned BuiltinID = Ident->getBuiltinID(); 5598 StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName(); 5599 5600 bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 5601 if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) || 5602 (!IsAArch64 && !ArmMveAliasValid(BuiltinID, AliasName) && 5603 !ArmCdeAliasValid(BuiltinID, AliasName))) { 5604 S.Diag(AL.getLoc(), diag::err_attribute_arm_builtin_alias); 5605 return; 5606 } 5607 5608 D->addAttr(::new (S.Context) ArmBuiltinAliasAttr(S.Context, AL, Ident)); 5609 } 5610 5611 static bool RISCVAliasValid(unsigned BuiltinID, StringRef AliasName) { 5612 return BuiltinID >= RISCV::FirstRVVBuiltin && 5613 BuiltinID <= RISCV::LastRVVBuiltin; 5614 } 5615 5616 static void handleBuiltinAliasAttr(Sema &S, Decl *D, 5617 const ParsedAttr &AL) { 5618 if (!AL.isArgIdent(0)) { 5619 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 5620 << AL << 1 << AANT_ArgumentIdentifier; 5621 return; 5622 } 5623 5624 IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident; 5625 unsigned BuiltinID = Ident->getBuiltinID(); 5626 StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName(); 5627 5628 bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 5629 bool IsARM = S.Context.getTargetInfo().getTriple().isARM(); 5630 bool IsRISCV = S.Context.getTargetInfo().getTriple().isRISCV(); 5631 if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) || 5632 (IsARM && !ArmMveAliasValid(BuiltinID, AliasName) && 5633 !ArmCdeAliasValid(BuiltinID, AliasName)) || 5634 (IsRISCV && !RISCVAliasValid(BuiltinID, AliasName)) || 5635 (!IsAArch64 && !IsARM && !IsRISCV)) { 5636 S.Diag(AL.getLoc(), diag::err_attribute_builtin_alias) << AL; 5637 return; 5638 } 5639 5640 D->addAttr(::new (S.Context) BuiltinAliasAttr(S.Context, AL, Ident)); 5641 } 5642 5643 //===----------------------------------------------------------------------===// 5644 // Checker-specific attribute handlers. 5645 //===----------------------------------------------------------------------===// 5646 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) { 5647 return QT->isDependentType() || QT->isObjCRetainableType(); 5648 } 5649 5650 static bool isValidSubjectOfNSAttribute(QualType QT) { 5651 return QT->isDependentType() || QT->isObjCObjectPointerType() || 5652 QT->isObjCNSObjectType(); 5653 } 5654 5655 static bool isValidSubjectOfCFAttribute(QualType QT) { 5656 return QT->isDependentType() || QT->isPointerType() || 5657 isValidSubjectOfNSAttribute(QT); 5658 } 5659 5660 static bool isValidSubjectOfOSAttribute(QualType QT) { 5661 if (QT->isDependentType()) 5662 return true; 5663 QualType PT = QT->getPointeeType(); 5664 return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr; 5665 } 5666 5667 void Sema::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, 5668 RetainOwnershipKind K, 5669 bool IsTemplateInstantiation) { 5670 ValueDecl *VD = cast<ValueDecl>(D); 5671 switch (K) { 5672 case RetainOwnershipKind::OS: 5673 handleSimpleAttributeOrDiagnose<OSConsumedAttr>( 5674 *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()), 5675 diag::warn_ns_attribute_wrong_parameter_type, 5676 /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1); 5677 return; 5678 case RetainOwnershipKind::NS: 5679 handleSimpleAttributeOrDiagnose<NSConsumedAttr>( 5680 *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()), 5681 5682 // These attributes are normally just advisory, but in ARC, ns_consumed 5683 // is significant. Allow non-dependent code to contain inappropriate 5684 // attributes even in ARC, but require template instantiations to be 5685 // set up correctly. 5686 ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount) 5687 ? diag::err_ns_attribute_wrong_parameter_type 5688 : diag::warn_ns_attribute_wrong_parameter_type), 5689 /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0); 5690 return; 5691 case RetainOwnershipKind::CF: 5692 handleSimpleAttributeOrDiagnose<CFConsumedAttr>( 5693 *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()), 5694 diag::warn_ns_attribute_wrong_parameter_type, 5695 /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1); 5696 return; 5697 } 5698 } 5699 5700 static Sema::RetainOwnershipKind 5701 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) { 5702 switch (AL.getKind()) { 5703 case ParsedAttr::AT_CFConsumed: 5704 case ParsedAttr::AT_CFReturnsRetained: 5705 case ParsedAttr::AT_CFReturnsNotRetained: 5706 return Sema::RetainOwnershipKind::CF; 5707 case ParsedAttr::AT_OSConsumesThis: 5708 case ParsedAttr::AT_OSConsumed: 5709 case ParsedAttr::AT_OSReturnsRetained: 5710 case ParsedAttr::AT_OSReturnsNotRetained: 5711 case ParsedAttr::AT_OSReturnsRetainedOnZero: 5712 case ParsedAttr::AT_OSReturnsRetainedOnNonZero: 5713 return Sema::RetainOwnershipKind::OS; 5714 case ParsedAttr::AT_NSConsumesSelf: 5715 case ParsedAttr::AT_NSConsumed: 5716 case ParsedAttr::AT_NSReturnsRetained: 5717 case ParsedAttr::AT_NSReturnsNotRetained: 5718 case ParsedAttr::AT_NSReturnsAutoreleased: 5719 return Sema::RetainOwnershipKind::NS; 5720 default: 5721 llvm_unreachable("Wrong argument supplied"); 5722 } 5723 } 5724 5725 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) { 5726 if (isValidSubjectOfNSReturnsRetainedAttribute(QT)) 5727 return false; 5728 5729 Diag(Loc, diag::warn_ns_attribute_wrong_return_type) 5730 << "'ns_returns_retained'" << 0 << 0; 5731 return true; 5732 } 5733 5734 /// \return whether the parameter is a pointer to OSObject pointer. 5735 static bool isValidOSObjectOutParameter(const Decl *D) { 5736 const auto *PVD = dyn_cast<ParmVarDecl>(D); 5737 if (!PVD) 5738 return false; 5739 QualType QT = PVD->getType(); 5740 QualType PT = QT->getPointeeType(); 5741 return !PT.isNull() && isValidSubjectOfOSAttribute(PT); 5742 } 5743 5744 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D, 5745 const ParsedAttr &AL) { 5746 QualType ReturnType; 5747 Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL); 5748 5749 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 5750 ReturnType = MD->getReturnType(); 5751 } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) && 5752 (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) { 5753 return; // ignore: was handled as a type attribute 5754 } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) { 5755 ReturnType = PD->getType(); 5756 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 5757 ReturnType = FD->getReturnType(); 5758 } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) { 5759 // Attributes on parameters are used for out-parameters, 5760 // passed as pointers-to-pointers. 5761 unsigned DiagID = K == Sema::RetainOwnershipKind::CF 5762 ? /*pointer-to-CF-pointer*/2 5763 : /*pointer-to-OSObject-pointer*/3; 5764 ReturnType = Param->getType()->getPointeeType(); 5765 if (ReturnType.isNull()) { 5766 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type) 5767 << AL << DiagID << AL.getRange(); 5768 return; 5769 } 5770 } else if (AL.isUsedAsTypeAttr()) { 5771 return; 5772 } else { 5773 AttributeDeclKind ExpectedDeclKind; 5774 switch (AL.getKind()) { 5775 default: llvm_unreachable("invalid ownership attribute"); 5776 case ParsedAttr::AT_NSReturnsRetained: 5777 case ParsedAttr::AT_NSReturnsAutoreleased: 5778 case ParsedAttr::AT_NSReturnsNotRetained: 5779 ExpectedDeclKind = ExpectedFunctionOrMethod; 5780 break; 5781 5782 case ParsedAttr::AT_OSReturnsRetained: 5783 case ParsedAttr::AT_OSReturnsNotRetained: 5784 case ParsedAttr::AT_CFReturnsRetained: 5785 case ParsedAttr::AT_CFReturnsNotRetained: 5786 ExpectedDeclKind = ExpectedFunctionMethodOrParameter; 5787 break; 5788 } 5789 S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type) 5790 << AL.getRange() << AL << ExpectedDeclKind; 5791 return; 5792 } 5793 5794 bool TypeOK; 5795 bool Cf; 5796 unsigned ParmDiagID = 2; // Pointer-to-CF-pointer 5797 switch (AL.getKind()) { 5798 default: llvm_unreachable("invalid ownership attribute"); 5799 case ParsedAttr::AT_NSReturnsRetained: 5800 TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType); 5801 Cf = false; 5802 break; 5803 5804 case ParsedAttr::AT_NSReturnsAutoreleased: 5805 case ParsedAttr::AT_NSReturnsNotRetained: 5806 TypeOK = isValidSubjectOfNSAttribute(ReturnType); 5807 Cf = false; 5808 break; 5809 5810 case ParsedAttr::AT_CFReturnsRetained: 5811 case ParsedAttr::AT_CFReturnsNotRetained: 5812 TypeOK = isValidSubjectOfCFAttribute(ReturnType); 5813 Cf = true; 5814 break; 5815 5816 case ParsedAttr::AT_OSReturnsRetained: 5817 case ParsedAttr::AT_OSReturnsNotRetained: 5818 TypeOK = isValidSubjectOfOSAttribute(ReturnType); 5819 Cf = true; 5820 ParmDiagID = 3; // Pointer-to-OSObject-pointer 5821 break; 5822 } 5823 5824 if (!TypeOK) { 5825 if (AL.isUsedAsTypeAttr()) 5826 return; 5827 5828 if (isa<ParmVarDecl>(D)) { 5829 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type) 5830 << AL << ParmDiagID << AL.getRange(); 5831 } else { 5832 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type. 5833 enum : unsigned { 5834 Function, 5835 Method, 5836 Property 5837 } SubjectKind = Function; 5838 if (isa<ObjCMethodDecl>(D)) 5839 SubjectKind = Method; 5840 else if (isa<ObjCPropertyDecl>(D)) 5841 SubjectKind = Property; 5842 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type) 5843 << AL << SubjectKind << Cf << AL.getRange(); 5844 } 5845 return; 5846 } 5847 5848 switch (AL.getKind()) { 5849 default: 5850 llvm_unreachable("invalid ownership attribute"); 5851 case ParsedAttr::AT_NSReturnsAutoreleased: 5852 handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL); 5853 return; 5854 case ParsedAttr::AT_CFReturnsNotRetained: 5855 handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL); 5856 return; 5857 case ParsedAttr::AT_NSReturnsNotRetained: 5858 handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL); 5859 return; 5860 case ParsedAttr::AT_CFReturnsRetained: 5861 handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL); 5862 return; 5863 case ParsedAttr::AT_NSReturnsRetained: 5864 handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL); 5865 return; 5866 case ParsedAttr::AT_OSReturnsRetained: 5867 handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL); 5868 return; 5869 case ParsedAttr::AT_OSReturnsNotRetained: 5870 handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL); 5871 return; 5872 }; 5873 } 5874 5875 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D, 5876 const ParsedAttr &Attrs) { 5877 const int EP_ObjCMethod = 1; 5878 const int EP_ObjCProperty = 2; 5879 5880 SourceLocation loc = Attrs.getLoc(); 5881 QualType resultType; 5882 if (isa<ObjCMethodDecl>(D)) 5883 resultType = cast<ObjCMethodDecl>(D)->getReturnType(); 5884 else 5885 resultType = cast<ObjCPropertyDecl>(D)->getType(); 5886 5887 if (!resultType->isReferenceType() && 5888 (!resultType->isPointerType() || resultType->isObjCRetainableType())) { 5889 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type) 5890 << SourceRange(loc) << Attrs 5891 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty) 5892 << /*non-retainable pointer*/ 2; 5893 5894 // Drop the attribute. 5895 return; 5896 } 5897 5898 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs)); 5899 } 5900 5901 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D, 5902 const ParsedAttr &Attrs) { 5903 const auto *Method = cast<ObjCMethodDecl>(D); 5904 5905 const DeclContext *DC = Method->getDeclContext(); 5906 if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) { 5907 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs 5908 << 0; 5909 S.Diag(PDecl->getLocation(), diag::note_protocol_decl); 5910 return; 5911 } 5912 if (Method->getMethodFamily() == OMF_dealloc) { 5913 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs 5914 << 1; 5915 return; 5916 } 5917 5918 D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs)); 5919 } 5920 5921 static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &AL) { 5922 auto *E = AL.getArgAsExpr(0); 5923 auto Loc = E ? E->getBeginLoc() : AL.getLoc(); 5924 5925 auto *DRE = dyn_cast<DeclRefExpr>(AL.getArgAsExpr(0)); 5926 if (!DRE) { 5927 S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 0; 5928 return; 5929 } 5930 5931 auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 5932 if (!VD) { 5933 S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 1 << DRE->getDecl(); 5934 return; 5935 } 5936 5937 if (!isNSStringType(VD->getType(), S.Context) && 5938 !isCFStringType(VD->getType(), S.Context)) { 5939 S.Diag(Loc, diag::err_nserrordomain_wrong_type) << VD; 5940 return; 5941 } 5942 5943 D->addAttr(::new (S.Context) NSErrorDomainAttr(S.Context, AL, VD)); 5944 } 5945 5946 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5947 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr; 5948 5949 if (!Parm) { 5950 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0; 5951 return; 5952 } 5953 5954 // Typedefs only allow objc_bridge(id) and have some additional checking. 5955 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 5956 if (!Parm->Ident->isStr("id")) { 5957 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL; 5958 return; 5959 } 5960 5961 // Only allow 'cv void *'. 5962 QualType T = TD->getUnderlyingType(); 5963 if (!T->isVoidPointerType()) { 5964 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer); 5965 return; 5966 } 5967 } 5968 5969 D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident)); 5970 } 5971 5972 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D, 5973 const ParsedAttr &AL) { 5974 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr; 5975 5976 if (!Parm) { 5977 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0; 5978 return; 5979 } 5980 5981 D->addAttr(::new (S.Context) 5982 ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident)); 5983 } 5984 5985 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D, 5986 const ParsedAttr &AL) { 5987 IdentifierInfo *RelatedClass = 5988 AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr; 5989 if (!RelatedClass) { 5990 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0; 5991 return; 5992 } 5993 IdentifierInfo *ClassMethod = 5994 AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr; 5995 IdentifierInfo *InstanceMethod = 5996 AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr; 5997 D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr( 5998 S.Context, AL, RelatedClass, ClassMethod, InstanceMethod)); 5999 } 6000 6001 static void handleObjCDesignatedInitializer(Sema &S, Decl *D, 6002 const ParsedAttr &AL) { 6003 DeclContext *Ctx = D->getDeclContext(); 6004 6005 // This attribute can only be applied to methods in interfaces or class 6006 // extensions. 6007 if (!isa<ObjCInterfaceDecl>(Ctx) && 6008 !(isa<ObjCCategoryDecl>(Ctx) && 6009 cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) { 6010 S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init); 6011 return; 6012 } 6013 6014 ObjCInterfaceDecl *IFace; 6015 if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx)) 6016 IFace = CatDecl->getClassInterface(); 6017 else 6018 IFace = cast<ObjCInterfaceDecl>(Ctx); 6019 6020 if (!IFace) 6021 return; 6022 6023 IFace->setHasDesignatedInitializers(); 6024 D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL)); 6025 } 6026 6027 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) { 6028 StringRef MetaDataName; 6029 if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName)) 6030 return; 6031 D->addAttr(::new (S.Context) 6032 ObjCRuntimeNameAttr(S.Context, AL, MetaDataName)); 6033 } 6034 6035 // When a user wants to use objc_boxable with a union or struct 6036 // but they don't have access to the declaration (legacy/third-party code) 6037 // then they can 'enable' this feature with a typedef: 6038 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct; 6039 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) { 6040 bool notify = false; 6041 6042 auto *RD = dyn_cast<RecordDecl>(D); 6043 if (RD && RD->getDefinition()) { 6044 RD = RD->getDefinition(); 6045 notify = true; 6046 } 6047 6048 if (RD) { 6049 ObjCBoxableAttr *BoxableAttr = 6050 ::new (S.Context) ObjCBoxableAttr(S.Context, AL); 6051 RD->addAttr(BoxableAttr); 6052 if (notify) { 6053 // we need to notify ASTReader/ASTWriter about 6054 // modification of existing declaration 6055 if (ASTMutationListener *L = S.getASTMutationListener()) 6056 L->AddedAttributeToRecord(BoxableAttr, RD); 6057 } 6058 } 6059 } 6060 6061 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6062 if (hasDeclarator(D)) return; 6063 6064 S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type) 6065 << AL.getRange() << AL << ExpectedVariable; 6066 } 6067 6068 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D, 6069 const ParsedAttr &AL) { 6070 const auto *VD = cast<ValueDecl>(D); 6071 QualType QT = VD->getType(); 6072 6073 if (!QT->isDependentType() && 6074 !QT->isObjCLifetimeType()) { 6075 S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type) 6076 << QT; 6077 return; 6078 } 6079 6080 Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime(); 6081 6082 // If we have no lifetime yet, check the lifetime we're presumably 6083 // going to infer. 6084 if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType()) 6085 Lifetime = QT->getObjCARCImplicitLifetime(); 6086 6087 switch (Lifetime) { 6088 case Qualifiers::OCL_None: 6089 assert(QT->isDependentType() && 6090 "didn't infer lifetime for non-dependent type?"); 6091 break; 6092 6093 case Qualifiers::OCL_Weak: // meaningful 6094 case Qualifiers::OCL_Strong: // meaningful 6095 break; 6096 6097 case Qualifiers::OCL_ExplicitNone: 6098 case Qualifiers::OCL_Autoreleasing: 6099 S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless) 6100 << (Lifetime == Qualifiers::OCL_Autoreleasing); 6101 break; 6102 } 6103 6104 D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL)); 6105 } 6106 6107 static void handleSwiftAttrAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6108 // Make sure that there is a string literal as the annotation's single 6109 // argument. 6110 StringRef Str; 6111 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 6112 return; 6113 6114 D->addAttr(::new (S.Context) SwiftAttrAttr(S.Context, AL, Str)); 6115 } 6116 6117 static void handleSwiftBridge(Sema &S, Decl *D, const ParsedAttr &AL) { 6118 // Make sure that there is a string literal as the annotation's single 6119 // argument. 6120 StringRef BT; 6121 if (!S.checkStringLiteralArgumentAttr(AL, 0, BT)) 6122 return; 6123 6124 // Warn about duplicate attributes if they have different arguments, but drop 6125 // any duplicate attributes regardless. 6126 if (const auto *Other = D->getAttr<SwiftBridgeAttr>()) { 6127 if (Other->getSwiftType() != BT) 6128 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 6129 return; 6130 } 6131 6132 D->addAttr(::new (S.Context) SwiftBridgeAttr(S.Context, AL, BT)); 6133 } 6134 6135 static bool isErrorParameter(Sema &S, QualType QT) { 6136 const auto *PT = QT->getAs<PointerType>(); 6137 if (!PT) 6138 return false; 6139 6140 QualType Pointee = PT->getPointeeType(); 6141 6142 // Check for NSError**. 6143 if (const auto *OPT = Pointee->getAs<ObjCObjectPointerType>()) 6144 if (const auto *ID = OPT->getInterfaceDecl()) 6145 if (ID->getIdentifier() == S.getNSErrorIdent()) 6146 return true; 6147 6148 // Check for CFError**. 6149 if (const auto *PT = Pointee->getAs<PointerType>()) 6150 if (const auto *RT = PT->getPointeeType()->getAs<RecordType>()) 6151 if (S.isCFError(RT->getDecl())) 6152 return true; 6153 6154 return false; 6155 } 6156 6157 static void handleSwiftError(Sema &S, Decl *D, const ParsedAttr &AL) { 6158 auto hasErrorParameter = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool { 6159 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) { 6160 if (isErrorParameter(S, getFunctionOrMethodParamType(D, I))) 6161 return true; 6162 } 6163 6164 S.Diag(AL.getLoc(), diag::err_attr_swift_error_no_error_parameter) 6165 << AL << isa<ObjCMethodDecl>(D); 6166 return false; 6167 }; 6168 6169 auto hasPointerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool { 6170 // - C, ObjC, and block pointers are definitely okay. 6171 // - References are definitely not okay. 6172 // - nullptr_t is weird, but acceptable. 6173 QualType RT = getFunctionOrMethodResultType(D); 6174 if (RT->hasPointerRepresentation() && !RT->isReferenceType()) 6175 return true; 6176 6177 S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type) 6178 << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D) 6179 << /*pointer*/ 1; 6180 return false; 6181 }; 6182 6183 auto hasIntegerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool { 6184 QualType RT = getFunctionOrMethodResultType(D); 6185 if (RT->isIntegralType(S.Context)) 6186 return true; 6187 6188 S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type) 6189 << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D) 6190 << /*integral*/ 0; 6191 return false; 6192 }; 6193 6194 if (D->isInvalidDecl()) 6195 return; 6196 6197 IdentifierLoc *Loc = AL.getArgAsIdent(0); 6198 SwiftErrorAttr::ConventionKind Convention; 6199 if (!SwiftErrorAttr::ConvertStrToConventionKind(Loc->Ident->getName(), 6200 Convention)) { 6201 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 6202 << AL << Loc->Ident; 6203 return; 6204 } 6205 6206 switch (Convention) { 6207 case SwiftErrorAttr::None: 6208 // No additional validation required. 6209 break; 6210 6211 case SwiftErrorAttr::NonNullError: 6212 if (!hasErrorParameter(S, D, AL)) 6213 return; 6214 break; 6215 6216 case SwiftErrorAttr::NullResult: 6217 if (!hasErrorParameter(S, D, AL) || !hasPointerResult(S, D, AL)) 6218 return; 6219 break; 6220 6221 case SwiftErrorAttr::NonZeroResult: 6222 case SwiftErrorAttr::ZeroResult: 6223 if (!hasErrorParameter(S, D, AL) || !hasIntegerResult(S, D, AL)) 6224 return; 6225 break; 6226 } 6227 6228 D->addAttr(::new (S.Context) SwiftErrorAttr(S.Context, AL, Convention)); 6229 } 6230 6231 static void checkSwiftAsyncErrorBlock(Sema &S, Decl *D, 6232 const SwiftAsyncErrorAttr *ErrorAttr, 6233 const SwiftAsyncAttr *AsyncAttr) { 6234 if (AsyncAttr->getKind() == SwiftAsyncAttr::None) { 6235 if (ErrorAttr->getConvention() != SwiftAsyncErrorAttr::None) { 6236 S.Diag(AsyncAttr->getLocation(), 6237 diag::err_swift_async_error_without_swift_async) 6238 << AsyncAttr << isa<ObjCMethodDecl>(D); 6239 } 6240 return; 6241 } 6242 6243 const ParmVarDecl *HandlerParam = getFunctionOrMethodParam( 6244 D, AsyncAttr->getCompletionHandlerIndex().getASTIndex()); 6245 // handleSwiftAsyncAttr already verified the type is correct, so no need to 6246 // double-check it here. 6247 const auto *FuncTy = HandlerParam->getType() 6248 ->castAs<BlockPointerType>() 6249 ->getPointeeType() 6250 ->getAs<FunctionProtoType>(); 6251 ArrayRef<QualType> BlockParams; 6252 if (FuncTy) 6253 BlockParams = FuncTy->getParamTypes(); 6254 6255 switch (ErrorAttr->getConvention()) { 6256 case SwiftAsyncErrorAttr::ZeroArgument: 6257 case SwiftAsyncErrorAttr::NonZeroArgument: { 6258 uint32_t ParamIdx = ErrorAttr->getHandlerParamIdx(); 6259 if (ParamIdx == 0 || ParamIdx > BlockParams.size()) { 6260 S.Diag(ErrorAttr->getLocation(), 6261 diag::err_attribute_argument_out_of_bounds) << ErrorAttr << 2; 6262 return; 6263 } 6264 QualType ErrorParam = BlockParams[ParamIdx - 1]; 6265 if (!ErrorParam->isIntegralType(S.Context)) { 6266 StringRef ConvStr = 6267 ErrorAttr->getConvention() == SwiftAsyncErrorAttr::ZeroArgument 6268 ? "zero_argument" 6269 : "nonzero_argument"; 6270 S.Diag(ErrorAttr->getLocation(), diag::err_swift_async_error_non_integral) 6271 << ErrorAttr << ConvStr << ParamIdx << ErrorParam; 6272 return; 6273 } 6274 break; 6275 } 6276 case SwiftAsyncErrorAttr::NonNullError: { 6277 bool AnyErrorParams = false; 6278 for (QualType Param : BlockParams) { 6279 // Check for NSError *. 6280 if (const auto *ObjCPtrTy = Param->getAs<ObjCObjectPointerType>()) { 6281 if (const auto *ID = ObjCPtrTy->getInterfaceDecl()) { 6282 if (ID->getIdentifier() == S.getNSErrorIdent()) { 6283 AnyErrorParams = true; 6284 break; 6285 } 6286 } 6287 } 6288 // Check for CFError *. 6289 if (const auto *PtrTy = Param->getAs<PointerType>()) { 6290 if (const auto *RT = PtrTy->getPointeeType()->getAs<RecordType>()) { 6291 if (S.isCFError(RT->getDecl())) { 6292 AnyErrorParams = true; 6293 break; 6294 } 6295 } 6296 } 6297 } 6298 6299 if (!AnyErrorParams) { 6300 S.Diag(ErrorAttr->getLocation(), 6301 diag::err_swift_async_error_no_error_parameter) 6302 << ErrorAttr << isa<ObjCMethodDecl>(D); 6303 return; 6304 } 6305 break; 6306 } 6307 case SwiftAsyncErrorAttr::None: 6308 break; 6309 } 6310 } 6311 6312 static void handleSwiftAsyncError(Sema &S, Decl *D, const ParsedAttr &AL) { 6313 IdentifierLoc *IDLoc = AL.getArgAsIdent(0); 6314 SwiftAsyncErrorAttr::ConventionKind ConvKind; 6315 if (!SwiftAsyncErrorAttr::ConvertStrToConventionKind(IDLoc->Ident->getName(), 6316 ConvKind)) { 6317 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 6318 << AL << IDLoc->Ident; 6319 return; 6320 } 6321 6322 uint32_t ParamIdx = 0; 6323 switch (ConvKind) { 6324 case SwiftAsyncErrorAttr::ZeroArgument: 6325 case SwiftAsyncErrorAttr::NonZeroArgument: { 6326 if (!AL.checkExactlyNumArgs(S, 2)) 6327 return; 6328 6329 Expr *IdxExpr = AL.getArgAsExpr(1); 6330 if (!checkUInt32Argument(S, AL, IdxExpr, ParamIdx)) 6331 return; 6332 break; 6333 } 6334 case SwiftAsyncErrorAttr::NonNullError: 6335 case SwiftAsyncErrorAttr::None: { 6336 if (!AL.checkExactlyNumArgs(S, 1)) 6337 return; 6338 break; 6339 } 6340 } 6341 6342 auto *ErrorAttr = 6343 ::new (S.Context) SwiftAsyncErrorAttr(S.Context, AL, ConvKind, ParamIdx); 6344 D->addAttr(ErrorAttr); 6345 6346 if (auto *AsyncAttr = D->getAttr<SwiftAsyncAttr>()) 6347 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr); 6348 } 6349 6350 // For a function, this will validate a compound Swift name, e.g. 6351 // <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, and 6352 // the function will output the number of parameter names, and whether this is a 6353 // single-arg initializer. 6354 // 6355 // For a type, enum constant, property, or variable declaration, this will 6356 // validate either a simple identifier, or a qualified 6357 // <code>context.identifier</code> name. 6358 static bool 6359 validateSwiftFunctionName(Sema &S, const ParsedAttr &AL, SourceLocation Loc, 6360 StringRef Name, unsigned &SwiftParamCount, 6361 bool &IsSingleParamInit) { 6362 SwiftParamCount = 0; 6363 IsSingleParamInit = false; 6364 6365 // Check whether this will be mapped to a getter or setter of a property. 6366 bool IsGetter = false, IsSetter = false; 6367 if (Name.startswith("getter:")) { 6368 IsGetter = true; 6369 Name = Name.substr(7); 6370 } else if (Name.startswith("setter:")) { 6371 IsSetter = true; 6372 Name = Name.substr(7); 6373 } 6374 6375 if (Name.back() != ')') { 6376 S.Diag(Loc, diag::warn_attr_swift_name_function) << AL; 6377 return false; 6378 } 6379 6380 bool IsMember = false; 6381 StringRef ContextName, BaseName, Parameters; 6382 6383 std::tie(BaseName, Parameters) = Name.split('('); 6384 6385 // Split at the first '.', if it exists, which separates the context name 6386 // from the base name. 6387 std::tie(ContextName, BaseName) = BaseName.split('.'); 6388 if (BaseName.empty()) { 6389 BaseName = ContextName; 6390 ContextName = StringRef(); 6391 } else if (ContextName.empty() || !isValidAsciiIdentifier(ContextName)) { 6392 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) 6393 << AL << /*context*/ 1; 6394 return false; 6395 } else { 6396 IsMember = true; 6397 } 6398 6399 if (!isValidAsciiIdentifier(BaseName) || BaseName == "_") { 6400 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) 6401 << AL << /*basename*/ 0; 6402 return false; 6403 } 6404 6405 bool IsSubscript = BaseName == "subscript"; 6406 // A subscript accessor must be a getter or setter. 6407 if (IsSubscript && !IsGetter && !IsSetter) { 6408 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter) 6409 << AL << /* getter or setter */ 0; 6410 return false; 6411 } 6412 6413 if (Parameters.empty()) { 6414 S.Diag(Loc, diag::warn_attr_swift_name_missing_parameters) << AL; 6415 return false; 6416 } 6417 6418 assert(Parameters.back() == ')' && "expected ')'"); 6419 Parameters = Parameters.drop_back(); // ')' 6420 6421 if (Parameters.empty()) { 6422 // Setters and subscripts must have at least one parameter. 6423 if (IsSubscript) { 6424 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter) 6425 << AL << /* have at least one parameter */1; 6426 return false; 6427 } 6428 6429 if (IsSetter) { 6430 S.Diag(Loc, diag::warn_attr_swift_name_setter_parameters) << AL; 6431 return false; 6432 } 6433 6434 return true; 6435 } 6436 6437 if (Parameters.back() != ':') { 6438 S.Diag(Loc, diag::warn_attr_swift_name_function) << AL; 6439 return false; 6440 } 6441 6442 StringRef CurrentParam; 6443 llvm::Optional<unsigned> SelfLocation; 6444 unsigned NewValueCount = 0; 6445 llvm::Optional<unsigned> NewValueLocation; 6446 do { 6447 std::tie(CurrentParam, Parameters) = Parameters.split(':'); 6448 6449 if (!isValidAsciiIdentifier(CurrentParam)) { 6450 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) 6451 << AL << /*parameter*/2; 6452 return false; 6453 } 6454 6455 if (IsMember && CurrentParam == "self") { 6456 // "self" indicates the "self" argument for a member. 6457 6458 // More than one "self"? 6459 if (SelfLocation) { 6460 S.Diag(Loc, diag::warn_attr_swift_name_multiple_selfs) << AL; 6461 return false; 6462 } 6463 6464 // The "self" location is the current parameter. 6465 SelfLocation = SwiftParamCount; 6466 } else if (CurrentParam == "newValue") { 6467 // "newValue" indicates the "newValue" argument for a setter. 6468 6469 // There should only be one 'newValue', but it's only significant for 6470 // subscript accessors, so don't error right away. 6471 ++NewValueCount; 6472 6473 NewValueLocation = SwiftParamCount; 6474 } 6475 6476 ++SwiftParamCount; 6477 } while (!Parameters.empty()); 6478 6479 // Only instance subscripts are currently supported. 6480 if (IsSubscript && !SelfLocation) { 6481 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter) 6482 << AL << /*have a 'self:' parameter*/2; 6483 return false; 6484 } 6485 6486 IsSingleParamInit = 6487 SwiftParamCount == 1 && BaseName == "init" && CurrentParam != "_"; 6488 6489 // Check the number of parameters for a getter/setter. 6490 if (IsGetter || IsSetter) { 6491 // Setters have one parameter for the new value. 6492 unsigned NumExpectedParams = IsGetter ? 0 : 1; 6493 unsigned ParamDiag = 6494 IsGetter ? diag::warn_attr_swift_name_getter_parameters 6495 : diag::warn_attr_swift_name_setter_parameters; 6496 6497 // Instance methods have one parameter for "self". 6498 if (SelfLocation) 6499 ++NumExpectedParams; 6500 6501 // Subscripts may have additional parameters beyond the expected params for 6502 // the index. 6503 if (IsSubscript) { 6504 if (SwiftParamCount < NumExpectedParams) { 6505 S.Diag(Loc, ParamDiag) << AL; 6506 return false; 6507 } 6508 6509 // A subscript setter must explicitly label its newValue parameter to 6510 // distinguish it from index parameters. 6511 if (IsSetter) { 6512 if (!NewValueLocation) { 6513 S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_no_newValue) 6514 << AL; 6515 return false; 6516 } 6517 if (NewValueCount > 1) { 6518 S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_multiple_newValues) 6519 << AL; 6520 return false; 6521 } 6522 } else { 6523 // Subscript getters should have no 'newValue:' parameter. 6524 if (NewValueLocation) { 6525 S.Diag(Loc, diag::warn_attr_swift_name_subscript_getter_newValue) 6526 << AL; 6527 return false; 6528 } 6529 } 6530 } else { 6531 // Property accessors must have exactly the number of expected params. 6532 if (SwiftParamCount != NumExpectedParams) { 6533 S.Diag(Loc, ParamDiag) << AL; 6534 return false; 6535 } 6536 } 6537 } 6538 6539 return true; 6540 } 6541 6542 bool Sema::DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, 6543 const ParsedAttr &AL, bool IsAsync) { 6544 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 6545 ArrayRef<ParmVarDecl*> Params; 6546 unsigned ParamCount; 6547 6548 if (const auto *Method = dyn_cast<ObjCMethodDecl>(D)) { 6549 ParamCount = Method->getSelector().getNumArgs(); 6550 Params = Method->parameters().slice(0, ParamCount); 6551 } else { 6552 const auto *F = cast<FunctionDecl>(D); 6553 6554 ParamCount = F->getNumParams(); 6555 Params = F->parameters(); 6556 6557 if (!F->hasWrittenPrototype()) { 6558 Diag(Loc, diag::warn_attribute_wrong_decl_type) << AL 6559 << ExpectedFunctionWithProtoType; 6560 return false; 6561 } 6562 } 6563 6564 // The async name drops the last callback parameter. 6565 if (IsAsync) { 6566 if (ParamCount == 0) { 6567 Diag(Loc, diag::warn_attr_swift_name_decl_missing_params) 6568 << AL << isa<ObjCMethodDecl>(D); 6569 return false; 6570 } 6571 ParamCount -= 1; 6572 } 6573 6574 unsigned SwiftParamCount; 6575 bool IsSingleParamInit; 6576 if (!validateSwiftFunctionName(*this, AL, Loc, Name, 6577 SwiftParamCount, IsSingleParamInit)) 6578 return false; 6579 6580 bool ParamCountValid; 6581 if (SwiftParamCount == ParamCount) { 6582 ParamCountValid = true; 6583 } else if (SwiftParamCount > ParamCount) { 6584 ParamCountValid = IsSingleParamInit && ParamCount == 0; 6585 } else { 6586 // We have fewer Swift parameters than Objective-C parameters, but that 6587 // might be because we've transformed some of them. Check for potential 6588 // "out" parameters and err on the side of not warning. 6589 unsigned MaybeOutParamCount = 6590 llvm::count_if(Params, [](const ParmVarDecl *Param) -> bool { 6591 QualType ParamTy = Param->getType(); 6592 if (ParamTy->isReferenceType() || ParamTy->isPointerType()) 6593 return !ParamTy->getPointeeType().isConstQualified(); 6594 return false; 6595 }); 6596 6597 ParamCountValid = SwiftParamCount + MaybeOutParamCount >= ParamCount; 6598 } 6599 6600 if (!ParamCountValid) { 6601 Diag(Loc, diag::warn_attr_swift_name_num_params) 6602 << (SwiftParamCount > ParamCount) << AL << ParamCount 6603 << SwiftParamCount; 6604 return false; 6605 } 6606 } else if ((isa<EnumConstantDecl>(D) || isa<ObjCProtocolDecl>(D) || 6607 isa<ObjCInterfaceDecl>(D) || isa<ObjCPropertyDecl>(D) || 6608 isa<VarDecl>(D) || isa<TypedefNameDecl>(D) || isa<TagDecl>(D) || 6609 isa<IndirectFieldDecl>(D) || isa<FieldDecl>(D)) && 6610 !IsAsync) { 6611 StringRef ContextName, BaseName; 6612 6613 std::tie(ContextName, BaseName) = Name.split('.'); 6614 if (BaseName.empty()) { 6615 BaseName = ContextName; 6616 ContextName = StringRef(); 6617 } else if (!isValidAsciiIdentifier(ContextName)) { 6618 Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL 6619 << /*context*/1; 6620 return false; 6621 } 6622 6623 if (!isValidAsciiIdentifier(BaseName)) { 6624 Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL 6625 << /*basename*/0; 6626 return false; 6627 } 6628 } else { 6629 Diag(Loc, diag::warn_attr_swift_name_decl_kind) << AL; 6630 return false; 6631 } 6632 return true; 6633 } 6634 6635 static void handleSwiftName(Sema &S, Decl *D, const ParsedAttr &AL) { 6636 StringRef Name; 6637 SourceLocation Loc; 6638 if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc)) 6639 return; 6640 6641 if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/false)) 6642 return; 6643 6644 D->addAttr(::new (S.Context) SwiftNameAttr(S.Context, AL, Name)); 6645 } 6646 6647 static void handleSwiftAsyncName(Sema &S, Decl *D, const ParsedAttr &AL) { 6648 StringRef Name; 6649 SourceLocation Loc; 6650 if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc)) 6651 return; 6652 6653 if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/true)) 6654 return; 6655 6656 D->addAttr(::new (S.Context) SwiftAsyncNameAttr(S.Context, AL, Name)); 6657 } 6658 6659 static void handleSwiftNewType(Sema &S, Decl *D, const ParsedAttr &AL) { 6660 // Make sure that there is an identifier as the annotation's single argument. 6661 if (!AL.checkExactlyNumArgs(S, 1)) 6662 return; 6663 6664 if (!AL.isArgIdent(0)) { 6665 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 6666 << AL << AANT_ArgumentIdentifier; 6667 return; 6668 } 6669 6670 SwiftNewTypeAttr::NewtypeKind Kind; 6671 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 6672 if (!SwiftNewTypeAttr::ConvertStrToNewtypeKind(II->getName(), Kind)) { 6673 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; 6674 return; 6675 } 6676 6677 if (!isa<TypedefNameDecl>(D)) { 6678 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str) 6679 << AL << "typedefs"; 6680 return; 6681 } 6682 6683 D->addAttr(::new (S.Context) SwiftNewTypeAttr(S.Context, AL, Kind)); 6684 } 6685 6686 static void handleSwiftAsyncAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6687 if (!AL.isArgIdent(0)) { 6688 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 6689 << AL << 1 << AANT_ArgumentIdentifier; 6690 return; 6691 } 6692 6693 SwiftAsyncAttr::Kind Kind; 6694 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 6695 if (!SwiftAsyncAttr::ConvertStrToKind(II->getName(), Kind)) { 6696 S.Diag(AL.getLoc(), diag::err_swift_async_no_access) << AL << II; 6697 return; 6698 } 6699 6700 ParamIdx Idx; 6701 if (Kind == SwiftAsyncAttr::None) { 6702 // If this is 'none', then there shouldn't be any additional arguments. 6703 if (!AL.checkExactlyNumArgs(S, 1)) 6704 return; 6705 } else { 6706 // Non-none swift_async requires a completion handler index argument. 6707 if (!AL.checkExactlyNumArgs(S, 2)) 6708 return; 6709 6710 Expr *HandlerIdx = AL.getArgAsExpr(1); 6711 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, HandlerIdx, Idx)) 6712 return; 6713 6714 const ParmVarDecl *CompletionBlock = 6715 getFunctionOrMethodParam(D, Idx.getASTIndex()); 6716 QualType CompletionBlockType = CompletionBlock->getType(); 6717 if (!CompletionBlockType->isBlockPointerType()) { 6718 S.Diag(CompletionBlock->getLocation(), 6719 diag::err_swift_async_bad_block_type) 6720 << CompletionBlock->getType(); 6721 return; 6722 } 6723 QualType BlockTy = 6724 CompletionBlockType->castAs<BlockPointerType>()->getPointeeType(); 6725 if (!BlockTy->castAs<FunctionType>()->getReturnType()->isVoidType()) { 6726 S.Diag(CompletionBlock->getLocation(), 6727 diag::err_swift_async_bad_block_type) 6728 << CompletionBlock->getType(); 6729 return; 6730 } 6731 } 6732 6733 auto *AsyncAttr = 6734 ::new (S.Context) SwiftAsyncAttr(S.Context, AL, Kind, Idx); 6735 D->addAttr(AsyncAttr); 6736 6737 if (auto *ErrorAttr = D->getAttr<SwiftAsyncErrorAttr>()) 6738 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr); 6739 } 6740 6741 //===----------------------------------------------------------------------===// 6742 // Microsoft specific attribute handlers. 6743 //===----------------------------------------------------------------------===// 6744 6745 UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, 6746 StringRef UuidAsWritten, MSGuidDecl *GuidDecl) { 6747 if (const auto *UA = D->getAttr<UuidAttr>()) { 6748 if (declaresSameEntity(UA->getGuidDecl(), GuidDecl)) 6749 return nullptr; 6750 if (!UA->getGuid().empty()) { 6751 Diag(UA->getLocation(), diag::err_mismatched_uuid); 6752 Diag(CI.getLoc(), diag::note_previous_uuid); 6753 D->dropAttr<UuidAttr>(); 6754 } 6755 } 6756 6757 return ::new (Context) UuidAttr(Context, CI, UuidAsWritten, GuidDecl); 6758 } 6759 6760 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6761 if (!S.LangOpts.CPlusPlus) { 6762 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang) 6763 << AL << AttributeLangSupport::C; 6764 return; 6765 } 6766 6767 StringRef OrigStrRef; 6768 SourceLocation LiteralLoc; 6769 if (!S.checkStringLiteralArgumentAttr(AL, 0, OrigStrRef, &LiteralLoc)) 6770 return; 6771 6772 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or 6773 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former. 6774 StringRef StrRef = OrigStrRef; 6775 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}') 6776 StrRef = StrRef.drop_front().drop_back(); 6777 6778 // Validate GUID length. 6779 if (StrRef.size() != 36) { 6780 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 6781 return; 6782 } 6783 6784 for (unsigned i = 0; i < 36; ++i) { 6785 if (i == 8 || i == 13 || i == 18 || i == 23) { 6786 if (StrRef[i] != '-') { 6787 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 6788 return; 6789 } 6790 } else if (!isHexDigit(StrRef[i])) { 6791 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 6792 return; 6793 } 6794 } 6795 6796 // Convert to our parsed format and canonicalize. 6797 MSGuidDecl::Parts Parsed; 6798 StrRef.substr(0, 8).getAsInteger(16, Parsed.Part1); 6799 StrRef.substr(9, 4).getAsInteger(16, Parsed.Part2); 6800 StrRef.substr(14, 4).getAsInteger(16, Parsed.Part3); 6801 for (unsigned i = 0; i != 8; ++i) 6802 StrRef.substr(19 + 2 * i + (i >= 2 ? 1 : 0), 2) 6803 .getAsInteger(16, Parsed.Part4And5[i]); 6804 MSGuidDecl *Guid = S.Context.getMSGuidDecl(Parsed); 6805 6806 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's 6807 // the only thing in the [] list, the [] too), and add an insertion of 6808 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas 6809 // separating attributes nor of the [ and the ] are in the AST. 6810 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc" 6811 // on cfe-dev. 6812 if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling. 6813 S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated); 6814 6815 UuidAttr *UA = S.mergeUuidAttr(D, AL, OrigStrRef, Guid); 6816 if (UA) 6817 D->addAttr(UA); 6818 } 6819 6820 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6821 if (!S.LangOpts.CPlusPlus) { 6822 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang) 6823 << AL << AttributeLangSupport::C; 6824 return; 6825 } 6826 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr( 6827 D, AL, /*BestCase=*/true, (MSInheritanceModel)AL.getSemanticSpelling()); 6828 if (IA) { 6829 D->addAttr(IA); 6830 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 6831 } 6832 } 6833 6834 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6835 const auto *VD = cast<VarDecl>(D); 6836 if (!S.Context.getTargetInfo().isTLSSupported()) { 6837 S.Diag(AL.getLoc(), diag::err_thread_unsupported); 6838 return; 6839 } 6840 if (VD->getTSCSpec() != TSCS_unspecified) { 6841 S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable); 6842 return; 6843 } 6844 if (VD->hasLocalStorage()) { 6845 S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)"; 6846 return; 6847 } 6848 D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL)); 6849 } 6850 6851 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6852 SmallVector<StringRef, 4> Tags; 6853 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 6854 StringRef Tag; 6855 if (!S.checkStringLiteralArgumentAttr(AL, I, Tag)) 6856 return; 6857 Tags.push_back(Tag); 6858 } 6859 6860 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) { 6861 if (!NS->isInline()) { 6862 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0; 6863 return; 6864 } 6865 if (NS->isAnonymousNamespace()) { 6866 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1; 6867 return; 6868 } 6869 if (AL.getNumArgs() == 0) 6870 Tags.push_back(NS->getName()); 6871 } else if (!AL.checkAtLeastNumArgs(S, 1)) 6872 return; 6873 6874 // Store tags sorted and without duplicates. 6875 llvm::sort(Tags); 6876 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end()); 6877 6878 D->addAttr(::new (S.Context) 6879 AbiTagAttr(S.Context, AL, Tags.data(), Tags.size())); 6880 } 6881 6882 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6883 // Check the attribute arguments. 6884 if (AL.getNumArgs() > 1) { 6885 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1; 6886 return; 6887 } 6888 6889 StringRef Str; 6890 SourceLocation ArgLoc; 6891 6892 if (AL.getNumArgs() == 0) 6893 Str = ""; 6894 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 6895 return; 6896 6897 ARMInterruptAttr::InterruptType Kind; 6898 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 6899 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str 6900 << ArgLoc; 6901 return; 6902 } 6903 6904 D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind)); 6905 } 6906 6907 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6908 // MSP430 'interrupt' attribute is applied to 6909 // a function with no parameters and void return type. 6910 if (!isFunctionOrMethod(D)) { 6911 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 6912 << "'interrupt'" << ExpectedFunctionOrMethod; 6913 return; 6914 } 6915 6916 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { 6917 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 6918 << /*MSP430*/ 1 << 0; 6919 return; 6920 } 6921 6922 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 6923 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 6924 << /*MSP430*/ 1 << 1; 6925 return; 6926 } 6927 6928 // The attribute takes one integer argument. 6929 if (!AL.checkExactlyNumArgs(S, 1)) 6930 return; 6931 6932 if (!AL.isArgExpr(0)) { 6933 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 6934 << AL << AANT_ArgumentIntegerConstant; 6935 return; 6936 } 6937 6938 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0)); 6939 Optional<llvm::APSInt> NumParams = llvm::APSInt(32); 6940 if (!(NumParams = NumParamsExpr->getIntegerConstantExpr(S.Context))) { 6941 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 6942 << AL << AANT_ArgumentIntegerConstant 6943 << NumParamsExpr->getSourceRange(); 6944 return; 6945 } 6946 // The argument should be in range 0..63. 6947 unsigned Num = NumParams->getLimitedValue(255); 6948 if (Num > 63) { 6949 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 6950 << AL << (int)NumParams->getSExtValue() 6951 << NumParamsExpr->getSourceRange(); 6952 return; 6953 } 6954 6955 D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num)); 6956 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 6957 } 6958 6959 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6960 // Only one optional argument permitted. 6961 if (AL.getNumArgs() > 1) { 6962 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1; 6963 return; 6964 } 6965 6966 StringRef Str; 6967 SourceLocation ArgLoc; 6968 6969 if (AL.getNumArgs() == 0) 6970 Str = ""; 6971 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 6972 return; 6973 6974 // Semantic checks for a function with the 'interrupt' attribute for MIPS: 6975 // a) Must be a function. 6976 // b) Must have no parameters. 6977 // c) Must have the 'void' return type. 6978 // d) Cannot have the 'mips16' attribute, as that instruction set 6979 // lacks the 'eret' instruction. 6980 // e) The attribute itself must either have no argument or one of the 6981 // valid interrupt types, see [MipsInterruptDocs]. 6982 6983 if (!isFunctionOrMethod(D)) { 6984 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 6985 << "'interrupt'" << ExpectedFunctionOrMethod; 6986 return; 6987 } 6988 6989 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { 6990 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 6991 << /*MIPS*/ 0 << 0; 6992 return; 6993 } 6994 6995 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 6996 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 6997 << /*MIPS*/ 0 << 1; 6998 return; 6999 } 7000 7001 // We still have to do this manually because the Interrupt attributes are 7002 // a bit special due to sharing their spellings across targets. 7003 if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL)) 7004 return; 7005 7006 MipsInterruptAttr::InterruptType Kind; 7007 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 7008 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 7009 << AL << "'" + std::string(Str) + "'"; 7010 return; 7011 } 7012 7013 D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind)); 7014 } 7015 7016 static void handleM68kInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7017 if (!AL.checkExactlyNumArgs(S, 1)) 7018 return; 7019 7020 if (!AL.isArgExpr(0)) { 7021 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 7022 << AL << AANT_ArgumentIntegerConstant; 7023 return; 7024 } 7025 7026 // FIXME: Check for decl - it should be void ()(void). 7027 7028 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0)); 7029 auto MaybeNumParams = NumParamsExpr->getIntegerConstantExpr(S.Context); 7030 if (!MaybeNumParams) { 7031 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 7032 << AL << AANT_ArgumentIntegerConstant 7033 << NumParamsExpr->getSourceRange(); 7034 return; 7035 } 7036 7037 unsigned Num = MaybeNumParams->getLimitedValue(255); 7038 if ((Num & 1) || Num > 30) { 7039 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 7040 << AL << (int)MaybeNumParams->getSExtValue() 7041 << NumParamsExpr->getSourceRange(); 7042 return; 7043 } 7044 7045 D->addAttr(::new (S.Context) M68kInterruptAttr(S.Context, AL, Num)); 7046 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 7047 } 7048 7049 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7050 // Semantic checks for a function with the 'interrupt' attribute. 7051 // a) Must be a function. 7052 // b) Must have the 'void' return type. 7053 // c) Must take 1 or 2 arguments. 7054 // d) The 1st argument must be a pointer. 7055 // e) The 2nd argument (if any) must be an unsigned integer. 7056 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) || 7057 CXXMethodDecl::isStaticOverloadedOperator( 7058 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) { 7059 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 7060 << AL << ExpectedFunctionWithProtoType; 7061 return; 7062 } 7063 // Interrupt handler must have void return type. 7064 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 7065 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(), 7066 diag::err_anyx86_interrupt_attribute) 7067 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 7068 ? 0 7069 : 1) 7070 << 0; 7071 return; 7072 } 7073 // Interrupt handler must have 1 or 2 parameters. 7074 unsigned NumParams = getFunctionOrMethodNumParams(D); 7075 if (NumParams < 1 || NumParams > 2) { 7076 S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute) 7077 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 7078 ? 0 7079 : 1) 7080 << 1; 7081 return; 7082 } 7083 // The first argument must be a pointer. 7084 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) { 7085 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(), 7086 diag::err_anyx86_interrupt_attribute) 7087 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 7088 ? 0 7089 : 1) 7090 << 2; 7091 return; 7092 } 7093 // The second argument, if present, must be an unsigned integer. 7094 unsigned TypeSize = 7095 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64 7096 ? 64 7097 : 32; 7098 if (NumParams == 2 && 7099 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() || 7100 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) { 7101 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(), 7102 diag::err_anyx86_interrupt_attribute) 7103 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 7104 ? 0 7105 : 1) 7106 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false); 7107 return; 7108 } 7109 D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL)); 7110 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 7111 } 7112 7113 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7114 if (!isFunctionOrMethod(D)) { 7115 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 7116 << "'interrupt'" << ExpectedFunction; 7117 return; 7118 } 7119 7120 if (!AL.checkExactlyNumArgs(S, 0)) 7121 return; 7122 7123 handleSimpleAttribute<AVRInterruptAttr>(S, D, AL); 7124 } 7125 7126 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7127 if (!isFunctionOrMethod(D)) { 7128 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 7129 << "'signal'" << ExpectedFunction; 7130 return; 7131 } 7132 7133 if (!AL.checkExactlyNumArgs(S, 0)) 7134 return; 7135 7136 handleSimpleAttribute<AVRSignalAttr>(S, D, AL); 7137 } 7138 7139 static void handleBPFPreserveAIRecord(Sema &S, RecordDecl *RD) { 7140 // Add preserve_access_index attribute to all fields and inner records. 7141 for (auto D : RD->decls()) { 7142 if (D->hasAttr<BPFPreserveAccessIndexAttr>()) 7143 continue; 7144 7145 D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S.Context)); 7146 if (auto *Rec = dyn_cast<RecordDecl>(D)) 7147 handleBPFPreserveAIRecord(S, Rec); 7148 } 7149 } 7150 7151 static void handleBPFPreserveAccessIndexAttr(Sema &S, Decl *D, 7152 const ParsedAttr &AL) { 7153 auto *Rec = cast<RecordDecl>(D); 7154 handleBPFPreserveAIRecord(S, Rec); 7155 Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL)); 7156 } 7157 7158 static bool hasBTFDeclTagAttr(Decl *D, StringRef Tag) { 7159 for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) { 7160 if (I->getBTFDeclTag() == Tag) 7161 return true; 7162 } 7163 return false; 7164 } 7165 7166 static void handleBTFDeclTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7167 StringRef Str; 7168 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 7169 return; 7170 if (hasBTFDeclTagAttr(D, Str)) 7171 return; 7172 7173 D->addAttr(::new (S.Context) BTFDeclTagAttr(S.Context, AL, Str)); 7174 } 7175 7176 BTFDeclTagAttr *Sema::mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL) { 7177 if (hasBTFDeclTagAttr(D, AL.getBTFDeclTag())) 7178 return nullptr; 7179 return ::new (Context) BTFDeclTagAttr(Context, AL, AL.getBTFDeclTag()); 7180 } 7181 7182 static void handleWebAssemblyExportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7183 if (!isFunctionOrMethod(D)) { 7184 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 7185 << "'export_name'" << ExpectedFunction; 7186 return; 7187 } 7188 7189 auto *FD = cast<FunctionDecl>(D); 7190 if (FD->isThisDeclarationADefinition()) { 7191 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0; 7192 return; 7193 } 7194 7195 StringRef Str; 7196 SourceLocation ArgLoc; 7197 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 7198 return; 7199 7200 D->addAttr(::new (S.Context) WebAssemblyExportNameAttr(S.Context, AL, Str)); 7201 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 7202 } 7203 7204 WebAssemblyImportModuleAttr * 7205 Sema::mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL) { 7206 auto *FD = cast<FunctionDecl>(D); 7207 7208 if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 7209 if (ExistingAttr->getImportModule() == AL.getImportModule()) 7210 return nullptr; 7211 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 0 7212 << ExistingAttr->getImportModule() << AL.getImportModule(); 7213 Diag(AL.getLoc(), diag::note_previous_attribute); 7214 return nullptr; 7215 } 7216 if (FD->hasBody()) { 7217 Diag(AL.getLoc(), diag::warn_import_on_definition) << 0; 7218 return nullptr; 7219 } 7220 return ::new (Context) WebAssemblyImportModuleAttr(Context, AL, 7221 AL.getImportModule()); 7222 } 7223 7224 WebAssemblyImportNameAttr * 7225 Sema::mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL) { 7226 auto *FD = cast<FunctionDecl>(D); 7227 7228 if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportNameAttr>()) { 7229 if (ExistingAttr->getImportName() == AL.getImportName()) 7230 return nullptr; 7231 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 1 7232 << ExistingAttr->getImportName() << AL.getImportName(); 7233 Diag(AL.getLoc(), diag::note_previous_attribute); 7234 return nullptr; 7235 } 7236 if (FD->hasBody()) { 7237 Diag(AL.getLoc(), diag::warn_import_on_definition) << 1; 7238 return nullptr; 7239 } 7240 return ::new (Context) WebAssemblyImportNameAttr(Context, AL, 7241 AL.getImportName()); 7242 } 7243 7244 static void 7245 handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7246 auto *FD = cast<FunctionDecl>(D); 7247 7248 StringRef Str; 7249 SourceLocation ArgLoc; 7250 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 7251 return; 7252 if (FD->hasBody()) { 7253 S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 0; 7254 return; 7255 } 7256 7257 FD->addAttr(::new (S.Context) 7258 WebAssemblyImportModuleAttr(S.Context, AL, Str)); 7259 } 7260 7261 static void 7262 handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7263 auto *FD = cast<FunctionDecl>(D); 7264 7265 StringRef Str; 7266 SourceLocation ArgLoc; 7267 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 7268 return; 7269 if (FD->hasBody()) { 7270 S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 1; 7271 return; 7272 } 7273 7274 FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str)); 7275 } 7276 7277 static void handleRISCVInterruptAttr(Sema &S, Decl *D, 7278 const ParsedAttr &AL) { 7279 // Warn about repeated attributes. 7280 if (const auto *A = D->getAttr<RISCVInterruptAttr>()) { 7281 S.Diag(AL.getRange().getBegin(), 7282 diag::warn_riscv_repeated_interrupt_attribute); 7283 S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute); 7284 return; 7285 } 7286 7287 // Check the attribute argument. Argument is optional. 7288 if (!AL.checkAtMostNumArgs(S, 1)) 7289 return; 7290 7291 StringRef Str; 7292 SourceLocation ArgLoc; 7293 7294 // 'machine'is the default interrupt mode. 7295 if (AL.getNumArgs() == 0) 7296 Str = "machine"; 7297 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 7298 return; 7299 7300 // Semantic checks for a function with the 'interrupt' attribute: 7301 // - Must be a function. 7302 // - Must have no parameters. 7303 // - Must have the 'void' return type. 7304 // - The attribute itself must either have no argument or one of the 7305 // valid interrupt types, see [RISCVInterruptDocs]. 7306 7307 if (D->getFunctionType() == nullptr) { 7308 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 7309 << "'interrupt'" << ExpectedFunction; 7310 return; 7311 } 7312 7313 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { 7314 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 7315 << /*RISC-V*/ 2 << 0; 7316 return; 7317 } 7318 7319 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 7320 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 7321 << /*RISC-V*/ 2 << 1; 7322 return; 7323 } 7324 7325 RISCVInterruptAttr::InterruptType Kind; 7326 if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 7327 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str 7328 << ArgLoc; 7329 return; 7330 } 7331 7332 D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind)); 7333 } 7334 7335 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7336 // Dispatch the interrupt attribute based on the current target. 7337 switch (S.Context.getTargetInfo().getTriple().getArch()) { 7338 case llvm::Triple::msp430: 7339 handleMSP430InterruptAttr(S, D, AL); 7340 break; 7341 case llvm::Triple::mipsel: 7342 case llvm::Triple::mips: 7343 handleMipsInterruptAttr(S, D, AL); 7344 break; 7345 case llvm::Triple::m68k: 7346 handleM68kInterruptAttr(S, D, AL); 7347 break; 7348 case llvm::Triple::x86: 7349 case llvm::Triple::x86_64: 7350 handleAnyX86InterruptAttr(S, D, AL); 7351 break; 7352 case llvm::Triple::avr: 7353 handleAVRInterruptAttr(S, D, AL); 7354 break; 7355 case llvm::Triple::riscv32: 7356 case llvm::Triple::riscv64: 7357 handleRISCVInterruptAttr(S, D, AL); 7358 break; 7359 default: 7360 handleARMInterruptAttr(S, D, AL); 7361 break; 7362 } 7363 } 7364 7365 static bool 7366 checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr, 7367 const AMDGPUFlatWorkGroupSizeAttr &Attr) { 7368 // Accept template arguments for now as they depend on something else. 7369 // We'll get to check them when they eventually get instantiated. 7370 if (MinExpr->isValueDependent() || MaxExpr->isValueDependent()) 7371 return false; 7372 7373 uint32_t Min = 0; 7374 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0)) 7375 return true; 7376 7377 uint32_t Max = 0; 7378 if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1)) 7379 return true; 7380 7381 if (Min == 0 && Max != 0) { 7382 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid) 7383 << &Attr << 0; 7384 return true; 7385 } 7386 if (Min > Max) { 7387 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid) 7388 << &Attr << 1; 7389 return true; 7390 } 7391 7392 return false; 7393 } 7394 7395 void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl *D, 7396 const AttributeCommonInfo &CI, 7397 Expr *MinExpr, Expr *MaxExpr) { 7398 AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr); 7399 7400 if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr)) 7401 return; 7402 7403 D->addAttr(::new (Context) 7404 AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr)); 7405 } 7406 7407 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D, 7408 const ParsedAttr &AL) { 7409 Expr *MinExpr = AL.getArgAsExpr(0); 7410 Expr *MaxExpr = AL.getArgAsExpr(1); 7411 7412 S.addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr); 7413 } 7414 7415 static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr, 7416 Expr *MaxExpr, 7417 const AMDGPUWavesPerEUAttr &Attr) { 7418 if (S.DiagnoseUnexpandedParameterPack(MinExpr) || 7419 (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr))) 7420 return true; 7421 7422 // Accept template arguments for now as they depend on something else. 7423 // We'll get to check them when they eventually get instantiated. 7424 if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent())) 7425 return false; 7426 7427 uint32_t Min = 0; 7428 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0)) 7429 return true; 7430 7431 uint32_t Max = 0; 7432 if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1)) 7433 return true; 7434 7435 if (Min == 0 && Max != 0) { 7436 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid) 7437 << &Attr << 0; 7438 return true; 7439 } 7440 if (Max != 0 && Min > Max) { 7441 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid) 7442 << &Attr << 1; 7443 return true; 7444 } 7445 7446 return false; 7447 } 7448 7449 void Sema::addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, 7450 Expr *MinExpr, Expr *MaxExpr) { 7451 AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr); 7452 7453 if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr)) 7454 return; 7455 7456 D->addAttr(::new (Context) 7457 AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr)); 7458 } 7459 7460 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7461 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2)) 7462 return; 7463 7464 Expr *MinExpr = AL.getArgAsExpr(0); 7465 Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr; 7466 7467 S.addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr); 7468 } 7469 7470 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7471 uint32_t NumSGPR = 0; 7472 Expr *NumSGPRExpr = AL.getArgAsExpr(0); 7473 if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR)) 7474 return; 7475 7476 D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR)); 7477 } 7478 7479 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7480 uint32_t NumVGPR = 0; 7481 Expr *NumVGPRExpr = AL.getArgAsExpr(0); 7482 if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR)) 7483 return; 7484 7485 D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR)); 7486 } 7487 7488 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D, 7489 const ParsedAttr &AL) { 7490 // If we try to apply it to a function pointer, don't warn, but don't 7491 // do anything, either. It doesn't matter anyway, because there's nothing 7492 // special about calling a force_align_arg_pointer function. 7493 const auto *VD = dyn_cast<ValueDecl>(D); 7494 if (VD && VD->getType()->isFunctionPointerType()) 7495 return; 7496 // Also don't warn on function pointer typedefs. 7497 const auto *TD = dyn_cast<TypedefNameDecl>(D); 7498 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() || 7499 TD->getUnderlyingType()->isFunctionType())) 7500 return; 7501 // Attribute can only be applied to function types. 7502 if (!isa<FunctionDecl>(D)) { 7503 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 7504 << AL << ExpectedFunction; 7505 return; 7506 } 7507 7508 D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL)); 7509 } 7510 7511 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) { 7512 uint32_t Version; 7513 Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0)); 7514 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version)) 7515 return; 7516 7517 // TODO: Investigate what happens with the next major version of MSVC. 7518 if (Version != LangOptions::MSVC2015 / 100) { 7519 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 7520 << AL << Version << VersionExpr->getSourceRange(); 7521 return; 7522 } 7523 7524 // The attribute expects a "major" version number like 19, but new versions of 7525 // MSVC have moved to updating the "minor", or less significant numbers, so we 7526 // have to multiply by 100 now. 7527 Version *= 100; 7528 7529 D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version)); 7530 } 7531 7532 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, 7533 const AttributeCommonInfo &CI) { 7534 if (D->hasAttr<DLLExportAttr>()) { 7535 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'"; 7536 return nullptr; 7537 } 7538 7539 if (D->hasAttr<DLLImportAttr>()) 7540 return nullptr; 7541 7542 return ::new (Context) DLLImportAttr(Context, CI); 7543 } 7544 7545 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, 7546 const AttributeCommonInfo &CI) { 7547 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) { 7548 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import; 7549 D->dropAttr<DLLImportAttr>(); 7550 } 7551 7552 if (D->hasAttr<DLLExportAttr>()) 7553 return nullptr; 7554 7555 return ::new (Context) DLLExportAttr(Context, CI); 7556 } 7557 7558 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) { 7559 if (isa<ClassTemplatePartialSpecializationDecl>(D) && 7560 (S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) { 7561 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A; 7562 return; 7563 } 7564 7565 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 7566 if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport && 7567 !(S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) { 7568 // MinGW doesn't allow dllimport on inline functions. 7569 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline) 7570 << A; 7571 return; 7572 } 7573 } 7574 7575 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 7576 if ((S.Context.getTargetInfo().shouldDLLImportComdatSymbols()) && 7577 MD->getParent()->isLambda()) { 7578 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A; 7579 return; 7580 } 7581 } 7582 7583 Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport 7584 ? (Attr *)S.mergeDLLExportAttr(D, A) 7585 : (Attr *)S.mergeDLLImportAttr(D, A); 7586 if (NewAttr) 7587 D->addAttr(NewAttr); 7588 } 7589 7590 MSInheritanceAttr * 7591 Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, 7592 bool BestCase, 7593 MSInheritanceModel Model) { 7594 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) { 7595 if (IA->getInheritanceModel() == Model) 7596 return nullptr; 7597 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance) 7598 << 1 /*previous declaration*/; 7599 Diag(CI.getLoc(), diag::note_previous_ms_inheritance); 7600 D->dropAttr<MSInheritanceAttr>(); 7601 } 7602 7603 auto *RD = cast<CXXRecordDecl>(D); 7604 if (RD->hasDefinition()) { 7605 if (checkMSInheritanceAttrOnDefinition(RD, CI.getRange(), BestCase, 7606 Model)) { 7607 return nullptr; 7608 } 7609 } else { 7610 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) { 7611 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance) 7612 << 1 /*partial specialization*/; 7613 return nullptr; 7614 } 7615 if (RD->getDescribedClassTemplate()) { 7616 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance) 7617 << 0 /*primary template*/; 7618 return nullptr; 7619 } 7620 } 7621 7622 return ::new (Context) MSInheritanceAttr(Context, CI, BestCase); 7623 } 7624 7625 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7626 // The capability attributes take a single string parameter for the name of 7627 // the capability they represent. The lockable attribute does not take any 7628 // parameters. However, semantically, both attributes represent the same 7629 // concept, and so they use the same semantic attribute. Eventually, the 7630 // lockable attribute will be removed. 7631 // 7632 // For backward compatibility, any capability which has no specified string 7633 // literal will be considered a "mutex." 7634 StringRef N("mutex"); 7635 SourceLocation LiteralLoc; 7636 if (AL.getKind() == ParsedAttr::AT_Capability && 7637 !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc)) 7638 return; 7639 7640 D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N)); 7641 } 7642 7643 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7644 SmallVector<Expr*, 1> Args; 7645 if (!checkLockFunAttrCommon(S, D, AL, Args)) 7646 return; 7647 7648 D->addAttr(::new (S.Context) 7649 AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size())); 7650 } 7651 7652 static void handleAcquireCapabilityAttr(Sema &S, Decl *D, 7653 const ParsedAttr &AL) { 7654 SmallVector<Expr*, 1> Args; 7655 if (!checkLockFunAttrCommon(S, D, AL, Args)) 7656 return; 7657 7658 D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(), 7659 Args.size())); 7660 } 7661 7662 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D, 7663 const ParsedAttr &AL) { 7664 SmallVector<Expr*, 2> Args; 7665 if (!checkTryLockFunAttrCommon(S, D, AL, Args)) 7666 return; 7667 7668 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr( 7669 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size())); 7670 } 7671 7672 static void handleReleaseCapabilityAttr(Sema &S, Decl *D, 7673 const ParsedAttr &AL) { 7674 // Check that all arguments are lockable objects. 7675 SmallVector<Expr *, 1> Args; 7676 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true); 7677 7678 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(), 7679 Args.size())); 7680 } 7681 7682 static void handleRequiresCapabilityAttr(Sema &S, Decl *D, 7683 const ParsedAttr &AL) { 7684 if (!AL.checkAtLeastNumArgs(S, 1)) 7685 return; 7686 7687 // check that all arguments are lockable objects 7688 SmallVector<Expr*, 1> Args; 7689 checkAttrArgsAreCapabilityObjs(S, D, AL, Args); 7690 if (Args.empty()) 7691 return; 7692 7693 RequiresCapabilityAttr *RCA = ::new (S.Context) 7694 RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size()); 7695 7696 D->addAttr(RCA); 7697 } 7698 7699 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7700 if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) { 7701 if (NSD->isAnonymousNamespace()) { 7702 S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace); 7703 // Do not want to attach the attribute to the namespace because that will 7704 // cause confusing diagnostic reports for uses of declarations within the 7705 // namespace. 7706 return; 7707 } 7708 } else if (isa<UsingDecl, UnresolvedUsingTypenameDecl, 7709 UnresolvedUsingValueDecl>(D)) { 7710 S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using) 7711 << AL; 7712 return; 7713 } 7714 7715 // Handle the cases where the attribute has a text message. 7716 StringRef Str, Replacement; 7717 if (AL.isArgExpr(0) && AL.getArgAsExpr(0) && 7718 !S.checkStringLiteralArgumentAttr(AL, 0, Str)) 7719 return; 7720 7721 // Support a single optional message only for Declspec and [[]] spellings. 7722 if (AL.isDeclspecAttribute() || AL.isStandardAttributeSyntax()) 7723 AL.checkAtMostNumArgs(S, 1); 7724 else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) && 7725 !S.checkStringLiteralArgumentAttr(AL, 1, Replacement)) 7726 return; 7727 7728 if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope()) 7729 S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL; 7730 7731 D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement)); 7732 } 7733 7734 static bool isGlobalVar(const Decl *D) { 7735 if (const auto *S = dyn_cast<VarDecl>(D)) 7736 return S->hasGlobalStorage(); 7737 return false; 7738 } 7739 7740 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7741 if (!AL.checkAtLeastNumArgs(S, 1)) 7742 return; 7743 7744 std::vector<StringRef> Sanitizers; 7745 7746 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 7747 StringRef SanitizerName; 7748 SourceLocation LiteralLoc; 7749 7750 if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc)) 7751 return; 7752 7753 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 7754 SanitizerMask() && 7755 SanitizerName != "coverage") 7756 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName; 7757 else if (isGlobalVar(D) && SanitizerName != "address") 7758 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 7759 << AL << ExpectedFunctionOrMethod; 7760 Sanitizers.push_back(SanitizerName); 7761 } 7762 7763 D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(), 7764 Sanitizers.size())); 7765 } 7766 7767 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D, 7768 const ParsedAttr &AL) { 7769 StringRef AttrName = AL.getAttrName()->getName(); 7770 normalizeName(AttrName); 7771 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName) 7772 .Case("no_address_safety_analysis", "address") 7773 .Case("no_sanitize_address", "address") 7774 .Case("no_sanitize_thread", "thread") 7775 .Case("no_sanitize_memory", "memory"); 7776 if (isGlobalVar(D) && SanitizerName != "address") 7777 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 7778 << AL << ExpectedFunction; 7779 7780 // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a 7781 // NoSanitizeAttr object; but we need to calculate the correct spelling list 7782 // index rather than incorrectly assume the index for NoSanitizeSpecificAttr 7783 // has the same spellings as the index for NoSanitizeAttr. We don't have a 7784 // general way to "translate" between the two, so this hack attempts to work 7785 // around the issue with hard-coded indices. This is critical for calling 7786 // getSpelling() or prettyPrint() on the resulting semantic attribute object 7787 // without failing assertions. 7788 unsigned TranslatedSpellingIndex = 0; 7789 if (AL.isStandardAttributeSyntax()) 7790 TranslatedSpellingIndex = 1; 7791 7792 AttributeCommonInfo Info = AL; 7793 Info.setAttributeSpellingListIndex(TranslatedSpellingIndex); 7794 D->addAttr(::new (S.Context) 7795 NoSanitizeAttr(S.Context, Info, &SanitizerName, 1)); 7796 } 7797 7798 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7799 if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL)) 7800 D->addAttr(Internal); 7801 } 7802 7803 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7804 if (S.LangOpts.getOpenCLCompatibleVersion() < 200) 7805 S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version) 7806 << AL << "2.0" << 1; 7807 else 7808 S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) 7809 << AL << S.LangOpts.getOpenCLVersionString(); 7810 } 7811 7812 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7813 if (D->isInvalidDecl()) 7814 return; 7815 7816 // Check if there is only one access qualifier. 7817 if (D->hasAttr<OpenCLAccessAttr>()) { 7818 if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() == 7819 AL.getSemanticSpelling()) { 7820 S.Diag(AL.getLoc(), diag::warn_duplicate_declspec) 7821 << AL.getAttrName()->getName() << AL.getRange(); 7822 } else { 7823 S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers) 7824 << D->getSourceRange(); 7825 D->setInvalidDecl(true); 7826 return; 7827 } 7828 } 7829 7830 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that 7831 // an image object can be read and written. OpenCL v2.0 s6.13.6 - A kernel 7832 // cannot read from and write to the same pipe object. Using the read_write 7833 // (or __read_write) qualifier with the pipe qualifier is a compilation error. 7834 // OpenCL v3.0 s6.8 - For OpenCL C 2.0, or with the 7835 // __opencl_c_read_write_images feature, image objects specified as arguments 7836 // to a kernel can additionally be declared to be read-write. 7837 // C++ for OpenCL 1.0 inherits rule from OpenCL C v2.0. 7838 // C++ for OpenCL 2021 inherits rule from OpenCL C v3.0. 7839 if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) { 7840 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr(); 7841 if (AL.getAttrName()->getName().contains("read_write")) { 7842 bool ReadWriteImagesUnsupported = 7843 (S.getLangOpts().getOpenCLCompatibleVersion() < 200) || 7844 (S.getLangOpts().getOpenCLCompatibleVersion() == 300 && 7845 !S.getOpenCLOptions().isSupported("__opencl_c_read_write_images", 7846 S.getLangOpts())); 7847 if (ReadWriteImagesUnsupported || DeclTy->isPipeType()) { 7848 S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write) 7849 << AL << PDecl->getType() << DeclTy->isImageType(); 7850 D->setInvalidDecl(true); 7851 return; 7852 } 7853 } 7854 } 7855 7856 D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL)); 7857 } 7858 7859 static void handleZeroCallUsedRegsAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7860 // Check that the argument is a string literal. 7861 StringRef KindStr; 7862 SourceLocation LiteralLoc; 7863 if (!S.checkStringLiteralArgumentAttr(AL, 0, KindStr, &LiteralLoc)) 7864 return; 7865 7866 ZeroCallUsedRegsAttr::ZeroCallUsedRegsKind Kind; 7867 if (!ZeroCallUsedRegsAttr::ConvertStrToZeroCallUsedRegsKind(KindStr, Kind)) { 7868 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) 7869 << AL << KindStr; 7870 return; 7871 } 7872 7873 D->dropAttr<ZeroCallUsedRegsAttr>(); 7874 D->addAttr(ZeroCallUsedRegsAttr::Create(S.Context, Kind, AL)); 7875 } 7876 7877 static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7878 // The 'sycl_kernel' attribute applies only to function templates. 7879 const auto *FD = cast<FunctionDecl>(D); 7880 const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate(); 7881 assert(FT && "Function template is expected"); 7882 7883 // Function template must have at least two template parameters. 7884 const TemplateParameterList *TL = FT->getTemplateParameters(); 7885 if (TL->size() < 2) { 7886 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params); 7887 return; 7888 } 7889 7890 // Template parameters must be typenames. 7891 for (unsigned I = 0; I < 2; ++I) { 7892 const NamedDecl *TParam = TL->getParam(I); 7893 if (isa<NonTypeTemplateParmDecl>(TParam)) { 7894 S.Diag(FT->getLocation(), 7895 diag::warn_sycl_kernel_invalid_template_param_type); 7896 return; 7897 } 7898 } 7899 7900 // Function must have at least one argument. 7901 if (getFunctionOrMethodNumParams(D) != 1) { 7902 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_function_params); 7903 return; 7904 } 7905 7906 // Function must return void. 7907 QualType RetTy = getFunctionOrMethodResultType(D); 7908 if (!RetTy->isVoidType()) { 7909 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_return_type); 7910 return; 7911 } 7912 7913 handleSimpleAttribute<SYCLKernelAttr>(S, D, AL); 7914 } 7915 7916 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) { 7917 if (!cast<VarDecl>(D)->hasGlobalStorage()) { 7918 S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var) 7919 << (A.getKind() == ParsedAttr::AT_AlwaysDestroy); 7920 return; 7921 } 7922 7923 if (A.getKind() == ParsedAttr::AT_AlwaysDestroy) 7924 handleSimpleAttribute<AlwaysDestroyAttr>(S, D, A); 7925 else 7926 handleSimpleAttribute<NoDestroyAttr>(S, D, A); 7927 } 7928 7929 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7930 assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic && 7931 "uninitialized is only valid on automatic duration variables"); 7932 D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL)); 7933 } 7934 7935 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD, 7936 bool DiagnoseFailure) { 7937 QualType Ty = VD->getType(); 7938 if (!Ty->isObjCRetainableType()) { 7939 if (DiagnoseFailure) { 7940 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained) 7941 << 0; 7942 } 7943 return false; 7944 } 7945 7946 Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime(); 7947 7948 // Sema::inferObjCARCLifetime must run after processing decl attributes 7949 // (because __block lowers to an attribute), so if the lifetime hasn't been 7950 // explicitly specified, infer it locally now. 7951 if (LifetimeQual == Qualifiers::OCL_None) 7952 LifetimeQual = Ty->getObjCARCImplicitLifetime(); 7953 7954 // The attributes only really makes sense for __strong variables; ignore any 7955 // attempts to annotate a parameter with any other lifetime qualifier. 7956 if (LifetimeQual != Qualifiers::OCL_Strong) { 7957 if (DiagnoseFailure) { 7958 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained) 7959 << 1; 7960 } 7961 return false; 7962 } 7963 7964 // Tampering with the type of a VarDecl here is a bit of a hack, but we need 7965 // to ensure that the variable is 'const' so that we can error on 7966 // modification, which can otherwise over-release. 7967 VD->setType(Ty.withConst()); 7968 VD->setARCPseudoStrong(true); 7969 return true; 7970 } 7971 7972 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D, 7973 const ParsedAttr &AL) { 7974 if (auto *VD = dyn_cast<VarDecl>(D)) { 7975 assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically"); 7976 if (!VD->hasLocalStorage()) { 7977 S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained) 7978 << 0; 7979 return; 7980 } 7981 7982 if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true)) 7983 return; 7984 7985 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL); 7986 return; 7987 } 7988 7989 // If D is a function-like declaration (method, block, or function), then we 7990 // make every parameter psuedo-strong. 7991 unsigned NumParams = 7992 hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0; 7993 for (unsigned I = 0; I != NumParams; ++I) { 7994 auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I)); 7995 QualType Ty = PVD->getType(); 7996 7997 // If a user wrote a parameter with __strong explicitly, then assume they 7998 // want "real" strong semantics for that parameter. This works because if 7999 // the parameter was written with __strong, then the strong qualifier will 8000 // be non-local. 8001 if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() == 8002 Qualifiers::OCL_Strong) 8003 continue; 8004 8005 tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false); 8006 } 8007 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL); 8008 } 8009 8010 static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 8011 // Check that the return type is a `typedef int kern_return_t` or a typedef 8012 // around it, because otherwise MIG convention checks make no sense. 8013 // BlockDecl doesn't store a return type, so it's annoying to check, 8014 // so let's skip it for now. 8015 if (!isa<BlockDecl>(D)) { 8016 QualType T = getFunctionOrMethodResultType(D); 8017 bool IsKernReturnT = false; 8018 while (const auto *TT = T->getAs<TypedefType>()) { 8019 IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t"); 8020 T = TT->desugar(); 8021 } 8022 if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) { 8023 S.Diag(D->getBeginLoc(), 8024 diag::warn_mig_server_routine_does_not_return_kern_return_t); 8025 return; 8026 } 8027 } 8028 8029 handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL); 8030 } 8031 8032 static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 8033 // Warn if the return type is not a pointer or reference type. 8034 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 8035 QualType RetTy = FD->getReturnType(); 8036 if (!RetTy->isPointerType() && !RetTy->isReferenceType()) { 8037 S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer) 8038 << AL.getRange() << RetTy; 8039 return; 8040 } 8041 } 8042 8043 handleSimpleAttribute<MSAllocatorAttr>(S, D, AL); 8044 } 8045 8046 static void handleAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 8047 if (AL.isUsedAsTypeAttr()) 8048 return; 8049 // Warn if the parameter is definitely not an output parameter. 8050 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) { 8051 if (PVD->getType()->isIntegerType()) { 8052 S.Diag(AL.getLoc(), diag::err_attribute_output_parameter) 8053 << AL.getRange(); 8054 return; 8055 } 8056 } 8057 StringRef Argument; 8058 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument)) 8059 return; 8060 D->addAttr(AcquireHandleAttr::Create(S.Context, Argument, AL)); 8061 } 8062 8063 template<typename Attr> 8064 static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 8065 StringRef Argument; 8066 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument)) 8067 return; 8068 D->addAttr(Attr::Create(S.Context, Argument, AL)); 8069 } 8070 8071 static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 8072 // The guard attribute takes a single identifier argument. 8073 8074 if (!AL.isArgIdent(0)) { 8075 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 8076 << AL << AANT_ArgumentIdentifier; 8077 return; 8078 } 8079 8080 CFGuardAttr::GuardArg Arg; 8081 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 8082 if (!CFGuardAttr::ConvertStrToGuardArg(II->getName(), Arg)) { 8083 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; 8084 return; 8085 } 8086 8087 D->addAttr(::new (S.Context) CFGuardAttr(S.Context, AL, Arg)); 8088 } 8089 8090 8091 template <typename AttrTy> 8092 static const AttrTy *findEnforceTCBAttrByName(Decl *D, StringRef Name) { 8093 auto Attrs = D->specific_attrs<AttrTy>(); 8094 auto I = llvm::find_if(Attrs, 8095 [Name](const AttrTy *A) { 8096 return A->getTCBName() == Name; 8097 }); 8098 return I == Attrs.end() ? nullptr : *I; 8099 } 8100 8101 template <typename AttrTy, typename ConflictingAttrTy> 8102 static void handleEnforceTCBAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 8103 StringRef Argument; 8104 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument)) 8105 return; 8106 8107 // A function cannot be have both regular and leaf membership in the same TCB. 8108 if (const ConflictingAttrTy *ConflictingAttr = 8109 findEnforceTCBAttrByName<ConflictingAttrTy>(D, Argument)) { 8110 // We could attach a note to the other attribute but in this case 8111 // there's no need given how the two are very close to each other. 8112 S.Diag(AL.getLoc(), diag::err_tcb_conflicting_attributes) 8113 << AL.getAttrName()->getName() << ConflictingAttr->getAttrName()->getName() 8114 << Argument; 8115 8116 // Error recovery: drop the non-leaf attribute so that to suppress 8117 // all future warnings caused by erroneous attributes. The leaf attribute 8118 // needs to be kept because it can only suppresses warnings, not cause them. 8119 D->dropAttr<EnforceTCBAttr>(); 8120 return; 8121 } 8122 8123 D->addAttr(AttrTy::Create(S.Context, Argument, AL)); 8124 } 8125 8126 template <typename AttrTy, typename ConflictingAttrTy> 8127 static AttrTy *mergeEnforceTCBAttrImpl(Sema &S, Decl *D, const AttrTy &AL) { 8128 // Check if the new redeclaration has different leaf-ness in the same TCB. 8129 StringRef TCBName = AL.getTCBName(); 8130 if (const ConflictingAttrTy *ConflictingAttr = 8131 findEnforceTCBAttrByName<ConflictingAttrTy>(D, TCBName)) { 8132 S.Diag(ConflictingAttr->getLoc(), diag::err_tcb_conflicting_attributes) 8133 << ConflictingAttr->getAttrName()->getName() 8134 << AL.getAttrName()->getName() << TCBName; 8135 8136 // Add a note so that the user could easily find the conflicting attribute. 8137 S.Diag(AL.getLoc(), diag::note_conflicting_attribute); 8138 8139 // More error recovery. 8140 D->dropAttr<EnforceTCBAttr>(); 8141 return nullptr; 8142 } 8143 8144 ASTContext &Context = S.getASTContext(); 8145 return ::new(Context) AttrTy(Context, AL, AL.getTCBName()); 8146 } 8147 8148 EnforceTCBAttr *Sema::mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL) { 8149 return mergeEnforceTCBAttrImpl<EnforceTCBAttr, EnforceTCBLeafAttr>( 8150 *this, D, AL); 8151 } 8152 8153 EnforceTCBLeafAttr *Sema::mergeEnforceTCBLeafAttr( 8154 Decl *D, const EnforceTCBLeafAttr &AL) { 8155 return mergeEnforceTCBAttrImpl<EnforceTCBLeafAttr, EnforceTCBAttr>( 8156 *this, D, AL); 8157 } 8158 8159 //===----------------------------------------------------------------------===// 8160 // Top Level Sema Entry Points 8161 //===----------------------------------------------------------------------===// 8162 8163 // Returns true if the attribute must delay setting its arguments until after 8164 // template instantiation, and false otherwise. 8165 static bool MustDelayAttributeArguments(const ParsedAttr &AL) { 8166 // Only attributes that accept expression parameter packs can delay arguments. 8167 if (!AL.acceptsExprPack()) 8168 return false; 8169 8170 bool AttrHasVariadicArg = AL.hasVariadicArg(); 8171 unsigned AttrNumArgs = AL.getNumArgMembers(); 8172 for (size_t I = 0; I < std::min(AL.getNumArgs(), AttrNumArgs); ++I) { 8173 bool IsLastAttrArg = I == (AttrNumArgs - 1); 8174 // If the argument is the last argument and it is variadic it can contain 8175 // any expression. 8176 if (IsLastAttrArg && AttrHasVariadicArg) 8177 return false; 8178 Expr *E = AL.getArgAsExpr(I); 8179 bool ArgMemberCanHoldExpr = AL.isParamExpr(I); 8180 // If the expression is a pack expansion then arguments must be delayed 8181 // unless the argument is an expression and it is the last argument of the 8182 // attribute. 8183 if (isa<PackExpansionExpr>(E)) 8184 return !(IsLastAttrArg && ArgMemberCanHoldExpr); 8185 // Last case is if the expression is value dependent then it must delay 8186 // arguments unless the corresponding argument is able to hold the 8187 // expression. 8188 if (E->isValueDependent() && !ArgMemberCanHoldExpr) 8189 return true; 8190 } 8191 return false; 8192 } 8193 8194 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if 8195 /// the attribute applies to decls. If the attribute is a type attribute, just 8196 /// silently ignore it if a GNU attribute. 8197 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, 8198 const ParsedAttr &AL, 8199 bool IncludeCXX11Attributes) { 8200 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 8201 return; 8202 8203 // Ignore C++11 attributes on declarator chunks: they appertain to the type 8204 // instead. 8205 if (AL.isCXX11Attribute() && !IncludeCXX11Attributes) 8206 return; 8207 8208 // Unknown attributes are automatically warned on. Target-specific attributes 8209 // which do not apply to the current target architecture are treated as 8210 // though they were unknown attributes. 8211 if (AL.getKind() == ParsedAttr::UnknownAttribute || 8212 !AL.existsInTarget(S.Context.getTargetInfo())) { 8213 S.Diag(AL.getLoc(), 8214 AL.isDeclspecAttribute() 8215 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored 8216 : (unsigned)diag::warn_unknown_attribute_ignored) 8217 << AL << AL.getRange(); 8218 return; 8219 } 8220 8221 // Check if argument population must delayed to after template instantiation. 8222 bool MustDelayArgs = MustDelayAttributeArguments(AL); 8223 8224 // Argument number check must be skipped if arguments are delayed. 8225 if (S.checkCommonAttributeFeatures(D, AL, MustDelayArgs)) 8226 return; 8227 8228 if (MustDelayArgs) { 8229 AL.handleAttrWithDelayedArgs(S, D); 8230 return; 8231 } 8232 8233 switch (AL.getKind()) { 8234 default: 8235 if (AL.getInfo().handleDeclAttribute(S, D, AL) != ParsedAttrInfo::NotHandled) 8236 break; 8237 if (!AL.isStmtAttr()) { 8238 // Type attributes are handled elsewhere; silently move on. 8239 assert(AL.isTypeAttr() && "Non-type attribute not handled"); 8240 break; 8241 } 8242 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a 8243 // statement attribute is not written on a declaration, but this code is 8244 // needed for attributes in Attr.td that do not list any subjects. 8245 S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl) 8246 << AL << D->getLocation(); 8247 break; 8248 case ParsedAttr::AT_Interrupt: 8249 handleInterruptAttr(S, D, AL); 8250 break; 8251 case ParsedAttr::AT_X86ForceAlignArgPointer: 8252 handleX86ForceAlignArgPointerAttr(S, D, AL); 8253 break; 8254 case ParsedAttr::AT_DLLExport: 8255 case ParsedAttr::AT_DLLImport: 8256 handleDLLAttr(S, D, AL); 8257 break; 8258 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize: 8259 handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL); 8260 break; 8261 case ParsedAttr::AT_AMDGPUWavesPerEU: 8262 handleAMDGPUWavesPerEUAttr(S, D, AL); 8263 break; 8264 case ParsedAttr::AT_AMDGPUNumSGPR: 8265 handleAMDGPUNumSGPRAttr(S, D, AL); 8266 break; 8267 case ParsedAttr::AT_AMDGPUNumVGPR: 8268 handleAMDGPUNumVGPRAttr(S, D, AL); 8269 break; 8270 case ParsedAttr::AT_AVRSignal: 8271 handleAVRSignalAttr(S, D, AL); 8272 break; 8273 case ParsedAttr::AT_BPFPreserveAccessIndex: 8274 handleBPFPreserveAccessIndexAttr(S, D, AL); 8275 break; 8276 case ParsedAttr::AT_BTFDeclTag: 8277 handleBTFDeclTagAttr(S, D, AL); 8278 break; 8279 case ParsedAttr::AT_WebAssemblyExportName: 8280 handleWebAssemblyExportNameAttr(S, D, AL); 8281 break; 8282 case ParsedAttr::AT_WebAssemblyImportModule: 8283 handleWebAssemblyImportModuleAttr(S, D, AL); 8284 break; 8285 case ParsedAttr::AT_WebAssemblyImportName: 8286 handleWebAssemblyImportNameAttr(S, D, AL); 8287 break; 8288 case ParsedAttr::AT_IBOutlet: 8289 handleIBOutlet(S, D, AL); 8290 break; 8291 case ParsedAttr::AT_IBOutletCollection: 8292 handleIBOutletCollection(S, D, AL); 8293 break; 8294 case ParsedAttr::AT_IFunc: 8295 handleIFuncAttr(S, D, AL); 8296 break; 8297 case ParsedAttr::AT_Alias: 8298 handleAliasAttr(S, D, AL); 8299 break; 8300 case ParsedAttr::AT_Aligned: 8301 handleAlignedAttr(S, D, AL); 8302 break; 8303 case ParsedAttr::AT_AlignValue: 8304 handleAlignValueAttr(S, D, AL); 8305 break; 8306 case ParsedAttr::AT_AllocSize: 8307 handleAllocSizeAttr(S, D, AL); 8308 break; 8309 case ParsedAttr::AT_AlwaysInline: 8310 handleAlwaysInlineAttr(S, D, AL); 8311 break; 8312 case ParsedAttr::AT_AnalyzerNoReturn: 8313 handleAnalyzerNoReturnAttr(S, D, AL); 8314 break; 8315 case ParsedAttr::AT_TLSModel: 8316 handleTLSModelAttr(S, D, AL); 8317 break; 8318 case ParsedAttr::AT_Annotate: 8319 handleAnnotateAttr(S, D, AL); 8320 break; 8321 case ParsedAttr::AT_Availability: 8322 handleAvailabilityAttr(S, D, AL); 8323 break; 8324 case ParsedAttr::AT_CarriesDependency: 8325 handleDependencyAttr(S, scope, D, AL); 8326 break; 8327 case ParsedAttr::AT_CPUDispatch: 8328 case ParsedAttr::AT_CPUSpecific: 8329 handleCPUSpecificAttr(S, D, AL); 8330 break; 8331 case ParsedAttr::AT_Common: 8332 handleCommonAttr(S, D, AL); 8333 break; 8334 case ParsedAttr::AT_CUDAConstant: 8335 handleConstantAttr(S, D, AL); 8336 break; 8337 case ParsedAttr::AT_PassObjectSize: 8338 handlePassObjectSizeAttr(S, D, AL); 8339 break; 8340 case ParsedAttr::AT_Constructor: 8341 handleConstructorAttr(S, D, AL); 8342 break; 8343 case ParsedAttr::AT_Deprecated: 8344 handleDeprecatedAttr(S, D, AL); 8345 break; 8346 case ParsedAttr::AT_Destructor: 8347 handleDestructorAttr(S, D, AL); 8348 break; 8349 case ParsedAttr::AT_EnableIf: 8350 handleEnableIfAttr(S, D, AL); 8351 break; 8352 case ParsedAttr::AT_Error: 8353 handleErrorAttr(S, D, AL); 8354 break; 8355 case ParsedAttr::AT_DiagnoseIf: 8356 handleDiagnoseIfAttr(S, D, AL); 8357 break; 8358 case ParsedAttr::AT_DiagnoseAsBuiltin: 8359 handleDiagnoseAsBuiltinAttr(S, D, AL); 8360 break; 8361 case ParsedAttr::AT_NoBuiltin: 8362 handleNoBuiltinAttr(S, D, AL); 8363 break; 8364 case ParsedAttr::AT_ExtVectorType: 8365 handleExtVectorTypeAttr(S, D, AL); 8366 break; 8367 case ParsedAttr::AT_ExternalSourceSymbol: 8368 handleExternalSourceSymbolAttr(S, D, AL); 8369 break; 8370 case ParsedAttr::AT_MinSize: 8371 handleMinSizeAttr(S, D, AL); 8372 break; 8373 case ParsedAttr::AT_OptimizeNone: 8374 handleOptimizeNoneAttr(S, D, AL); 8375 break; 8376 case ParsedAttr::AT_EnumExtensibility: 8377 handleEnumExtensibilityAttr(S, D, AL); 8378 break; 8379 case ParsedAttr::AT_SYCLKernel: 8380 handleSYCLKernelAttr(S, D, AL); 8381 break; 8382 case ParsedAttr::AT_SYCLSpecialClass: 8383 handleSimpleAttribute<SYCLSpecialClassAttr>(S, D, AL); 8384 break; 8385 case ParsedAttr::AT_Format: 8386 handleFormatAttr(S, D, AL); 8387 break; 8388 case ParsedAttr::AT_FormatArg: 8389 handleFormatArgAttr(S, D, AL); 8390 break; 8391 case ParsedAttr::AT_Callback: 8392 handleCallbackAttr(S, D, AL); 8393 break; 8394 case ParsedAttr::AT_CalledOnce: 8395 handleCalledOnceAttr(S, D, AL); 8396 break; 8397 case ParsedAttr::AT_CUDAGlobal: 8398 handleGlobalAttr(S, D, AL); 8399 break; 8400 case ParsedAttr::AT_CUDADevice: 8401 handleDeviceAttr(S, D, AL); 8402 break; 8403 case ParsedAttr::AT_HIPManaged: 8404 handleManagedAttr(S, D, AL); 8405 break; 8406 case ParsedAttr::AT_GNUInline: 8407 handleGNUInlineAttr(S, D, AL); 8408 break; 8409 case ParsedAttr::AT_CUDALaunchBounds: 8410 handleLaunchBoundsAttr(S, D, AL); 8411 break; 8412 case ParsedAttr::AT_Restrict: 8413 handleRestrictAttr(S, D, AL); 8414 break; 8415 case ParsedAttr::AT_Mode: 8416 handleModeAttr(S, D, AL); 8417 break; 8418 case ParsedAttr::AT_NonNull: 8419 if (auto *PVD = dyn_cast<ParmVarDecl>(D)) 8420 handleNonNullAttrParameter(S, PVD, AL); 8421 else 8422 handleNonNullAttr(S, D, AL); 8423 break; 8424 case ParsedAttr::AT_ReturnsNonNull: 8425 handleReturnsNonNullAttr(S, D, AL); 8426 break; 8427 case ParsedAttr::AT_NoEscape: 8428 handleNoEscapeAttr(S, D, AL); 8429 break; 8430 case ParsedAttr::AT_AssumeAligned: 8431 handleAssumeAlignedAttr(S, D, AL); 8432 break; 8433 case ParsedAttr::AT_AllocAlign: 8434 handleAllocAlignAttr(S, D, AL); 8435 break; 8436 case ParsedAttr::AT_Ownership: 8437 handleOwnershipAttr(S, D, AL); 8438 break; 8439 case ParsedAttr::AT_Naked: 8440 handleNakedAttr(S, D, AL); 8441 break; 8442 case ParsedAttr::AT_NoReturn: 8443 handleNoReturnAttr(S, D, AL); 8444 break; 8445 case ParsedAttr::AT_CXX11NoReturn: 8446 handleStandardNoReturnAttr(S, D, AL); 8447 break; 8448 case ParsedAttr::AT_AnyX86NoCfCheck: 8449 handleNoCfCheckAttr(S, D, AL); 8450 break; 8451 case ParsedAttr::AT_NoThrow: 8452 if (!AL.isUsedAsTypeAttr()) 8453 handleSimpleAttribute<NoThrowAttr>(S, D, AL); 8454 break; 8455 case ParsedAttr::AT_CUDAShared: 8456 handleSharedAttr(S, D, AL); 8457 break; 8458 case ParsedAttr::AT_VecReturn: 8459 handleVecReturnAttr(S, D, AL); 8460 break; 8461 case ParsedAttr::AT_ObjCOwnership: 8462 handleObjCOwnershipAttr(S, D, AL); 8463 break; 8464 case ParsedAttr::AT_ObjCPreciseLifetime: 8465 handleObjCPreciseLifetimeAttr(S, D, AL); 8466 break; 8467 case ParsedAttr::AT_ObjCReturnsInnerPointer: 8468 handleObjCReturnsInnerPointerAttr(S, D, AL); 8469 break; 8470 case ParsedAttr::AT_ObjCRequiresSuper: 8471 handleObjCRequiresSuperAttr(S, D, AL); 8472 break; 8473 case ParsedAttr::AT_ObjCBridge: 8474 handleObjCBridgeAttr(S, D, AL); 8475 break; 8476 case ParsedAttr::AT_ObjCBridgeMutable: 8477 handleObjCBridgeMutableAttr(S, D, AL); 8478 break; 8479 case ParsedAttr::AT_ObjCBridgeRelated: 8480 handleObjCBridgeRelatedAttr(S, D, AL); 8481 break; 8482 case ParsedAttr::AT_ObjCDesignatedInitializer: 8483 handleObjCDesignatedInitializer(S, D, AL); 8484 break; 8485 case ParsedAttr::AT_ObjCRuntimeName: 8486 handleObjCRuntimeName(S, D, AL); 8487 break; 8488 case ParsedAttr::AT_ObjCBoxable: 8489 handleObjCBoxable(S, D, AL); 8490 break; 8491 case ParsedAttr::AT_NSErrorDomain: 8492 handleNSErrorDomain(S, D, AL); 8493 break; 8494 case ParsedAttr::AT_CFConsumed: 8495 case ParsedAttr::AT_NSConsumed: 8496 case ParsedAttr::AT_OSConsumed: 8497 S.AddXConsumedAttr(D, AL, parsedAttrToRetainOwnershipKind(AL), 8498 /*IsTemplateInstantiation=*/false); 8499 break; 8500 case ParsedAttr::AT_OSReturnsRetainedOnZero: 8501 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>( 8502 S, D, AL, isValidOSObjectOutParameter(D), 8503 diag::warn_ns_attribute_wrong_parameter_type, 8504 /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange()); 8505 break; 8506 case ParsedAttr::AT_OSReturnsRetainedOnNonZero: 8507 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>( 8508 S, D, AL, isValidOSObjectOutParameter(D), 8509 diag::warn_ns_attribute_wrong_parameter_type, 8510 /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange()); 8511 break; 8512 case ParsedAttr::AT_NSReturnsAutoreleased: 8513 case ParsedAttr::AT_NSReturnsNotRetained: 8514 case ParsedAttr::AT_NSReturnsRetained: 8515 case ParsedAttr::AT_CFReturnsNotRetained: 8516 case ParsedAttr::AT_CFReturnsRetained: 8517 case ParsedAttr::AT_OSReturnsNotRetained: 8518 case ParsedAttr::AT_OSReturnsRetained: 8519 handleXReturnsXRetainedAttr(S, D, AL); 8520 break; 8521 case ParsedAttr::AT_WorkGroupSizeHint: 8522 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL); 8523 break; 8524 case ParsedAttr::AT_ReqdWorkGroupSize: 8525 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL); 8526 break; 8527 case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize: 8528 handleSubGroupSize(S, D, AL); 8529 break; 8530 case ParsedAttr::AT_VecTypeHint: 8531 handleVecTypeHint(S, D, AL); 8532 break; 8533 case ParsedAttr::AT_InitPriority: 8534 handleInitPriorityAttr(S, D, AL); 8535 break; 8536 case ParsedAttr::AT_Packed: 8537 handlePackedAttr(S, D, AL); 8538 break; 8539 case ParsedAttr::AT_PreferredName: 8540 handlePreferredName(S, D, AL); 8541 break; 8542 case ParsedAttr::AT_Section: 8543 handleSectionAttr(S, D, AL); 8544 break; 8545 case ParsedAttr::AT_CodeSeg: 8546 handleCodeSegAttr(S, D, AL); 8547 break; 8548 case ParsedAttr::AT_Target: 8549 handleTargetAttr(S, D, AL); 8550 break; 8551 case ParsedAttr::AT_TargetClones: 8552 handleTargetClonesAttr(S, D, AL); 8553 break; 8554 case ParsedAttr::AT_MinVectorWidth: 8555 handleMinVectorWidthAttr(S, D, AL); 8556 break; 8557 case ParsedAttr::AT_Unavailable: 8558 handleAttrWithMessage<UnavailableAttr>(S, D, AL); 8559 break; 8560 case ParsedAttr::AT_Assumption: 8561 handleAssumumptionAttr(S, D, AL); 8562 break; 8563 case ParsedAttr::AT_ObjCDirect: 8564 handleObjCDirectAttr(S, D, AL); 8565 break; 8566 case ParsedAttr::AT_ObjCDirectMembers: 8567 handleObjCDirectMembersAttr(S, D, AL); 8568 handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL); 8569 break; 8570 case ParsedAttr::AT_ObjCExplicitProtocolImpl: 8571 handleObjCSuppresProtocolAttr(S, D, AL); 8572 break; 8573 case ParsedAttr::AT_Unused: 8574 handleUnusedAttr(S, D, AL); 8575 break; 8576 case ParsedAttr::AT_Visibility: 8577 handleVisibilityAttr(S, D, AL, false); 8578 break; 8579 case ParsedAttr::AT_TypeVisibility: 8580 handleVisibilityAttr(S, D, AL, true); 8581 break; 8582 case ParsedAttr::AT_WarnUnusedResult: 8583 handleWarnUnusedResult(S, D, AL); 8584 break; 8585 case ParsedAttr::AT_WeakRef: 8586 handleWeakRefAttr(S, D, AL); 8587 break; 8588 case ParsedAttr::AT_WeakImport: 8589 handleWeakImportAttr(S, D, AL); 8590 break; 8591 case ParsedAttr::AT_TransparentUnion: 8592 handleTransparentUnionAttr(S, D, AL); 8593 break; 8594 case ParsedAttr::AT_ObjCMethodFamily: 8595 handleObjCMethodFamilyAttr(S, D, AL); 8596 break; 8597 case ParsedAttr::AT_ObjCNSObject: 8598 handleObjCNSObject(S, D, AL); 8599 break; 8600 case ParsedAttr::AT_ObjCIndependentClass: 8601 handleObjCIndependentClass(S, D, AL); 8602 break; 8603 case ParsedAttr::AT_Blocks: 8604 handleBlocksAttr(S, D, AL); 8605 break; 8606 case ParsedAttr::AT_Sentinel: 8607 handleSentinelAttr(S, D, AL); 8608 break; 8609 case ParsedAttr::AT_Cleanup: 8610 handleCleanupAttr(S, D, AL); 8611 break; 8612 case ParsedAttr::AT_NoDebug: 8613 handleNoDebugAttr(S, D, AL); 8614 break; 8615 case ParsedAttr::AT_CmseNSEntry: 8616 handleCmseNSEntryAttr(S, D, AL); 8617 break; 8618 case ParsedAttr::AT_StdCall: 8619 case ParsedAttr::AT_CDecl: 8620 case ParsedAttr::AT_FastCall: 8621 case ParsedAttr::AT_ThisCall: 8622 case ParsedAttr::AT_Pascal: 8623 case ParsedAttr::AT_RegCall: 8624 case ParsedAttr::AT_SwiftCall: 8625 case ParsedAttr::AT_SwiftAsyncCall: 8626 case ParsedAttr::AT_VectorCall: 8627 case ParsedAttr::AT_MSABI: 8628 case ParsedAttr::AT_SysVABI: 8629 case ParsedAttr::AT_Pcs: 8630 case ParsedAttr::AT_IntelOclBicc: 8631 case ParsedAttr::AT_PreserveMost: 8632 case ParsedAttr::AT_PreserveAll: 8633 case ParsedAttr::AT_AArch64VectorPcs: 8634 handleCallConvAttr(S, D, AL); 8635 break; 8636 case ParsedAttr::AT_Suppress: 8637 handleSuppressAttr(S, D, AL); 8638 break; 8639 case ParsedAttr::AT_Owner: 8640 case ParsedAttr::AT_Pointer: 8641 handleLifetimeCategoryAttr(S, D, AL); 8642 break; 8643 case ParsedAttr::AT_OpenCLAccess: 8644 handleOpenCLAccessAttr(S, D, AL); 8645 break; 8646 case ParsedAttr::AT_OpenCLNoSVM: 8647 handleOpenCLNoSVMAttr(S, D, AL); 8648 break; 8649 case ParsedAttr::AT_SwiftContext: 8650 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftContext); 8651 break; 8652 case ParsedAttr::AT_SwiftAsyncContext: 8653 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftAsyncContext); 8654 break; 8655 case ParsedAttr::AT_SwiftErrorResult: 8656 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftErrorResult); 8657 break; 8658 case ParsedAttr::AT_SwiftIndirectResult: 8659 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftIndirectResult); 8660 break; 8661 case ParsedAttr::AT_InternalLinkage: 8662 handleInternalLinkageAttr(S, D, AL); 8663 break; 8664 case ParsedAttr::AT_ZeroCallUsedRegs: 8665 handleZeroCallUsedRegsAttr(S, D, AL); 8666 break; 8667 8668 // Microsoft attributes: 8669 case ParsedAttr::AT_LayoutVersion: 8670 handleLayoutVersion(S, D, AL); 8671 break; 8672 case ParsedAttr::AT_Uuid: 8673 handleUuidAttr(S, D, AL); 8674 break; 8675 case ParsedAttr::AT_MSInheritance: 8676 handleMSInheritanceAttr(S, D, AL); 8677 break; 8678 case ParsedAttr::AT_Thread: 8679 handleDeclspecThreadAttr(S, D, AL); 8680 break; 8681 8682 case ParsedAttr::AT_AbiTag: 8683 handleAbiTagAttr(S, D, AL); 8684 break; 8685 case ParsedAttr::AT_CFGuard: 8686 handleCFGuardAttr(S, D, AL); 8687 break; 8688 8689 // Thread safety attributes: 8690 case ParsedAttr::AT_AssertExclusiveLock: 8691 handleAssertExclusiveLockAttr(S, D, AL); 8692 break; 8693 case ParsedAttr::AT_AssertSharedLock: 8694 handleAssertSharedLockAttr(S, D, AL); 8695 break; 8696 case ParsedAttr::AT_PtGuardedVar: 8697 handlePtGuardedVarAttr(S, D, AL); 8698 break; 8699 case ParsedAttr::AT_NoSanitize: 8700 handleNoSanitizeAttr(S, D, AL); 8701 break; 8702 case ParsedAttr::AT_NoSanitizeSpecific: 8703 handleNoSanitizeSpecificAttr(S, D, AL); 8704 break; 8705 case ParsedAttr::AT_GuardedBy: 8706 handleGuardedByAttr(S, D, AL); 8707 break; 8708 case ParsedAttr::AT_PtGuardedBy: 8709 handlePtGuardedByAttr(S, D, AL); 8710 break; 8711 case ParsedAttr::AT_ExclusiveTrylockFunction: 8712 handleExclusiveTrylockFunctionAttr(S, D, AL); 8713 break; 8714 case ParsedAttr::AT_LockReturned: 8715 handleLockReturnedAttr(S, D, AL); 8716 break; 8717 case ParsedAttr::AT_LocksExcluded: 8718 handleLocksExcludedAttr(S, D, AL); 8719 break; 8720 case ParsedAttr::AT_SharedTrylockFunction: 8721 handleSharedTrylockFunctionAttr(S, D, AL); 8722 break; 8723 case ParsedAttr::AT_AcquiredBefore: 8724 handleAcquiredBeforeAttr(S, D, AL); 8725 break; 8726 case ParsedAttr::AT_AcquiredAfter: 8727 handleAcquiredAfterAttr(S, D, AL); 8728 break; 8729 8730 // Capability analysis attributes. 8731 case ParsedAttr::AT_Capability: 8732 case ParsedAttr::AT_Lockable: 8733 handleCapabilityAttr(S, D, AL); 8734 break; 8735 case ParsedAttr::AT_RequiresCapability: 8736 handleRequiresCapabilityAttr(S, D, AL); 8737 break; 8738 8739 case ParsedAttr::AT_AssertCapability: 8740 handleAssertCapabilityAttr(S, D, AL); 8741 break; 8742 case ParsedAttr::AT_AcquireCapability: 8743 handleAcquireCapabilityAttr(S, D, AL); 8744 break; 8745 case ParsedAttr::AT_ReleaseCapability: 8746 handleReleaseCapabilityAttr(S, D, AL); 8747 break; 8748 case ParsedAttr::AT_TryAcquireCapability: 8749 handleTryAcquireCapabilityAttr(S, D, AL); 8750 break; 8751 8752 // Consumed analysis attributes. 8753 case ParsedAttr::AT_Consumable: 8754 handleConsumableAttr(S, D, AL); 8755 break; 8756 case ParsedAttr::AT_CallableWhen: 8757 handleCallableWhenAttr(S, D, AL); 8758 break; 8759 case ParsedAttr::AT_ParamTypestate: 8760 handleParamTypestateAttr(S, D, AL); 8761 break; 8762 case ParsedAttr::AT_ReturnTypestate: 8763 handleReturnTypestateAttr(S, D, AL); 8764 break; 8765 case ParsedAttr::AT_SetTypestate: 8766 handleSetTypestateAttr(S, D, AL); 8767 break; 8768 case ParsedAttr::AT_TestTypestate: 8769 handleTestTypestateAttr(S, D, AL); 8770 break; 8771 8772 // Type safety attributes. 8773 case ParsedAttr::AT_ArgumentWithTypeTag: 8774 handleArgumentWithTypeTagAttr(S, D, AL); 8775 break; 8776 case ParsedAttr::AT_TypeTagForDatatype: 8777 handleTypeTagForDatatypeAttr(S, D, AL); 8778 break; 8779 8780 // Swift attributes. 8781 case ParsedAttr::AT_SwiftAsyncName: 8782 handleSwiftAsyncName(S, D, AL); 8783 break; 8784 case ParsedAttr::AT_SwiftAttr: 8785 handleSwiftAttrAttr(S, D, AL); 8786 break; 8787 case ParsedAttr::AT_SwiftBridge: 8788 handleSwiftBridge(S, D, AL); 8789 break; 8790 case ParsedAttr::AT_SwiftError: 8791 handleSwiftError(S, D, AL); 8792 break; 8793 case ParsedAttr::AT_SwiftName: 8794 handleSwiftName(S, D, AL); 8795 break; 8796 case ParsedAttr::AT_SwiftNewType: 8797 handleSwiftNewType(S, D, AL); 8798 break; 8799 case ParsedAttr::AT_SwiftAsync: 8800 handleSwiftAsyncAttr(S, D, AL); 8801 break; 8802 case ParsedAttr::AT_SwiftAsyncError: 8803 handleSwiftAsyncError(S, D, AL); 8804 break; 8805 8806 // XRay attributes. 8807 case ParsedAttr::AT_XRayLogArgs: 8808 handleXRayLogArgsAttr(S, D, AL); 8809 break; 8810 8811 case ParsedAttr::AT_PatchableFunctionEntry: 8812 handlePatchableFunctionEntryAttr(S, D, AL); 8813 break; 8814 8815 case ParsedAttr::AT_AlwaysDestroy: 8816 case ParsedAttr::AT_NoDestroy: 8817 handleDestroyAttr(S, D, AL); 8818 break; 8819 8820 case ParsedAttr::AT_Uninitialized: 8821 handleUninitializedAttr(S, D, AL); 8822 break; 8823 8824 case ParsedAttr::AT_ObjCExternallyRetained: 8825 handleObjCExternallyRetainedAttr(S, D, AL); 8826 break; 8827 8828 case ParsedAttr::AT_MIGServerRoutine: 8829 handleMIGServerRoutineAttr(S, D, AL); 8830 break; 8831 8832 case ParsedAttr::AT_MSAllocator: 8833 handleMSAllocatorAttr(S, D, AL); 8834 break; 8835 8836 case ParsedAttr::AT_ArmBuiltinAlias: 8837 handleArmBuiltinAliasAttr(S, D, AL); 8838 break; 8839 8840 case ParsedAttr::AT_AcquireHandle: 8841 handleAcquireHandleAttr(S, D, AL); 8842 break; 8843 8844 case ParsedAttr::AT_ReleaseHandle: 8845 handleHandleAttr<ReleaseHandleAttr>(S, D, AL); 8846 break; 8847 8848 case ParsedAttr::AT_UseHandle: 8849 handleHandleAttr<UseHandleAttr>(S, D, AL); 8850 break; 8851 8852 case ParsedAttr::AT_EnforceTCB: 8853 handleEnforceTCBAttr<EnforceTCBAttr, EnforceTCBLeafAttr>(S, D, AL); 8854 break; 8855 8856 case ParsedAttr::AT_EnforceTCBLeaf: 8857 handleEnforceTCBAttr<EnforceTCBLeafAttr, EnforceTCBAttr>(S, D, AL); 8858 break; 8859 8860 case ParsedAttr::AT_BuiltinAlias: 8861 handleBuiltinAliasAttr(S, D, AL); 8862 break; 8863 8864 case ParsedAttr::AT_UsingIfExists: 8865 handleSimpleAttribute<UsingIfExistsAttr>(S, D, AL); 8866 break; 8867 } 8868 } 8869 8870 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified 8871 /// attribute list to the specified decl, ignoring any type attributes. 8872 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, 8873 const ParsedAttributesView &AttrList, 8874 bool IncludeCXX11Attributes) { 8875 if (AttrList.empty()) 8876 return; 8877 8878 for (const ParsedAttr &AL : AttrList) 8879 ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes); 8880 8881 // FIXME: We should be able to handle these cases in TableGen. 8882 // GCC accepts 8883 // static int a9 __attribute__((weakref)); 8884 // but that looks really pointless. We reject it. 8885 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) { 8886 Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias) 8887 << cast<NamedDecl>(D); 8888 D->dropAttr<WeakRefAttr>(); 8889 return; 8890 } 8891 8892 // FIXME: We should be able to handle this in TableGen as well. It would be 8893 // good to have a way to specify "these attributes must appear as a group", 8894 // for these. Additionally, it would be good to have a way to specify "these 8895 // attribute must never appear as a group" for attributes like cold and hot. 8896 if (!D->hasAttr<OpenCLKernelAttr>()) { 8897 // These attributes cannot be applied to a non-kernel function. 8898 if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) { 8899 // FIXME: This emits a different error message than 8900 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction. 8901 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 8902 D->setInvalidDecl(); 8903 } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) { 8904 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 8905 D->setInvalidDecl(); 8906 } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) { 8907 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 8908 D->setInvalidDecl(); 8909 } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) { 8910 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 8911 D->setInvalidDecl(); 8912 } else if (!D->hasAttr<CUDAGlobalAttr>()) { 8913 if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) { 8914 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 8915 << A << ExpectedKernelFunction; 8916 D->setInvalidDecl(); 8917 } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) { 8918 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 8919 << A << ExpectedKernelFunction; 8920 D->setInvalidDecl(); 8921 } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) { 8922 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 8923 << A << ExpectedKernelFunction; 8924 D->setInvalidDecl(); 8925 } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) { 8926 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 8927 << A << ExpectedKernelFunction; 8928 D->setInvalidDecl(); 8929 } 8930 } 8931 } 8932 8933 // Do this check after processing D's attributes because the attribute 8934 // objc_method_family can change whether the given method is in the init 8935 // family, and it can be applied after objc_designated_initializer. This is a 8936 // bit of a hack, but we need it to be compatible with versions of clang that 8937 // processed the attribute list in the wrong order. 8938 if (D->hasAttr<ObjCDesignatedInitializerAttr>() && 8939 cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) { 8940 Diag(D->getLocation(), diag::err_designated_init_attr_non_init); 8941 D->dropAttr<ObjCDesignatedInitializerAttr>(); 8942 } 8943 } 8944 8945 // Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr 8946 // attribute. 8947 void Sema::ProcessDeclAttributeDelayed(Decl *D, 8948 const ParsedAttributesView &AttrList) { 8949 for (const ParsedAttr &AL : AttrList) 8950 if (AL.getKind() == ParsedAttr::AT_TransparentUnion) { 8951 handleTransparentUnionAttr(*this, D, AL); 8952 break; 8953 } 8954 8955 // For BPFPreserveAccessIndexAttr, we want to populate the attributes 8956 // to fields and inner records as well. 8957 if (D && D->hasAttr<BPFPreserveAccessIndexAttr>()) 8958 handleBPFPreserveAIRecord(*this, cast<RecordDecl>(D)); 8959 } 8960 8961 // Annotation attributes are the only attributes allowed after an access 8962 // specifier. 8963 bool Sema::ProcessAccessDeclAttributeList( 8964 AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) { 8965 for (const ParsedAttr &AL : AttrList) { 8966 if (AL.getKind() == ParsedAttr::AT_Annotate) { 8967 ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute()); 8968 } else { 8969 Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec); 8970 return true; 8971 } 8972 } 8973 return false; 8974 } 8975 8976 /// checkUnusedDeclAttributes - Check a list of attributes to see if it 8977 /// contains any decl attributes that we should warn about. 8978 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) { 8979 for (const ParsedAttr &AL : A) { 8980 // Only warn if the attribute is an unignored, non-type attribute. 8981 if (AL.isUsedAsTypeAttr() || AL.isInvalid()) 8982 continue; 8983 if (AL.getKind() == ParsedAttr::IgnoredAttribute) 8984 continue; 8985 8986 if (AL.getKind() == ParsedAttr::UnknownAttribute) { 8987 S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) 8988 << AL << AL.getRange(); 8989 } else { 8990 S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL 8991 << AL.getRange(); 8992 } 8993 } 8994 } 8995 8996 /// checkUnusedDeclAttributes - Given a declarator which is not being 8997 /// used to build a declaration, complain about any decl attributes 8998 /// which might be lying around on it. 8999 void Sema::checkUnusedDeclAttributes(Declarator &D) { 9000 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes()); 9001 ::checkUnusedDeclAttributes(*this, D.getAttributes()); 9002 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) 9003 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs()); 9004 } 9005 9006 /// DeclClonePragmaWeak - clone existing decl (maybe definition), 9007 /// \#pragma weak needs a non-definition decl and source may not have one. 9008 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 9009 SourceLocation Loc) { 9010 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND)); 9011 NamedDecl *NewD = nullptr; 9012 if (auto *FD = dyn_cast<FunctionDecl>(ND)) { 9013 FunctionDecl *NewFD; 9014 // FIXME: Missing call to CheckFunctionDeclaration(). 9015 // FIXME: Mangling? 9016 // FIXME: Is the qualifier info correct? 9017 // FIXME: Is the DeclContext correct? 9018 NewFD = FunctionDecl::Create( 9019 FD->getASTContext(), FD->getDeclContext(), Loc, Loc, 9020 DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None, 9021 getCurFPFeatures().isFPConstrained(), false /*isInlineSpecified*/, 9022 FD->hasPrototype(), ConstexprSpecKind::Unspecified, 9023 FD->getTrailingRequiresClause()); 9024 NewD = NewFD; 9025 9026 if (FD->getQualifier()) 9027 NewFD->setQualifierInfo(FD->getQualifierLoc()); 9028 9029 // Fake up parameter variables; they are declared as if this were 9030 // a typedef. 9031 QualType FDTy = FD->getType(); 9032 if (const auto *FT = FDTy->getAs<FunctionProtoType>()) { 9033 SmallVector<ParmVarDecl*, 16> Params; 9034 for (const auto &AI : FT->param_types()) { 9035 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI); 9036 Param->setScopeInfo(0, Params.size()); 9037 Params.push_back(Param); 9038 } 9039 NewFD->setParams(Params); 9040 } 9041 } else if (auto *VD = dyn_cast<VarDecl>(ND)) { 9042 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(), 9043 VD->getInnerLocStart(), VD->getLocation(), II, 9044 VD->getType(), VD->getTypeSourceInfo(), 9045 VD->getStorageClass()); 9046 if (VD->getQualifier()) 9047 cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc()); 9048 } 9049 return NewD; 9050 } 9051 9052 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak 9053 /// applied to it, possibly with an alias. 9054 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) { 9055 if (W.getUsed()) return; // only do this once 9056 W.setUsed(true); 9057 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...)) 9058 IdentifierInfo *NDId = ND->getIdentifier(); 9059 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation()); 9060 NewD->addAttr( 9061 AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation())); 9062 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(), 9063 AttributeCommonInfo::AS_Pragma)); 9064 WeakTopLevelDecl.push_back(NewD); 9065 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin 9066 // to insert Decl at TU scope, sorry. 9067 DeclContext *SavedContext = CurContext; 9068 CurContext = Context.getTranslationUnitDecl(); 9069 NewD->setDeclContext(CurContext); 9070 NewD->setLexicalDeclContext(CurContext); 9071 PushOnScopeChains(NewD, S); 9072 CurContext = SavedContext; 9073 } else { // just add weak to existing 9074 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(), 9075 AttributeCommonInfo::AS_Pragma)); 9076 } 9077 } 9078 9079 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) { 9080 // It's valid to "forward-declare" #pragma weak, in which case we 9081 // have to do this. 9082 LoadExternalWeakUndeclaredIdentifiers(); 9083 if (!WeakUndeclaredIdentifiers.empty()) { 9084 NamedDecl *ND = nullptr; 9085 if (auto *VD = dyn_cast<VarDecl>(D)) 9086 if (VD->isExternC()) 9087 ND = VD; 9088 if (auto *FD = dyn_cast<FunctionDecl>(D)) 9089 if (FD->isExternC()) 9090 ND = FD; 9091 if (ND) { 9092 if (IdentifierInfo *Id = ND->getIdentifier()) { 9093 auto I = WeakUndeclaredIdentifiers.find(Id); 9094 if (I != WeakUndeclaredIdentifiers.end()) { 9095 WeakInfo W = I->second; 9096 DeclApplyPragmaWeak(S, ND, W); 9097 WeakUndeclaredIdentifiers[Id] = W; 9098 } 9099 } 9100 } 9101 } 9102 } 9103 9104 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in 9105 /// it, apply them to D. This is a bit tricky because PD can have attributes 9106 /// specified in many different places, and we need to find and apply them all. 9107 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) { 9108 // Apply decl attributes from the DeclSpec if present. 9109 if (!PD.getDeclSpec().getAttributes().empty()) 9110 ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes()); 9111 9112 // Walk the declarator structure, applying decl attributes that were in a type 9113 // position to the decl itself. This handles cases like: 9114 // int *__attr__(x)** D; 9115 // when X is a decl attribute. 9116 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) 9117 ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(), 9118 /*IncludeCXX11Attributes=*/false); 9119 9120 // Finally, apply any attributes on the decl itself. 9121 ProcessDeclAttributeList(S, D, PD.getAttributes()); 9122 9123 // Apply additional attributes specified by '#pragma clang attribute'. 9124 AddPragmaAttributes(S, D); 9125 } 9126 9127 /// Is the given declaration allowed to use a forbidden type? 9128 /// If so, it'll still be annotated with an attribute that makes it 9129 /// illegal to actually use. 9130 static bool isForbiddenTypeAllowed(Sema &S, Decl *D, 9131 const DelayedDiagnostic &diag, 9132 UnavailableAttr::ImplicitReason &reason) { 9133 // Private ivars are always okay. Unfortunately, people don't 9134 // always properly make their ivars private, even in system headers. 9135 // Plus we need to make fields okay, too. 9136 if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) && 9137 !isa<FunctionDecl>(D)) 9138 return false; 9139 9140 // Silently accept unsupported uses of __weak in both user and system 9141 // declarations when it's been disabled, for ease of integration with 9142 // -fno-objc-arc files. We do have to take some care against attempts 9143 // to define such things; for now, we've only done that for ivars 9144 // and properties. 9145 if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) { 9146 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled || 9147 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) { 9148 reason = UnavailableAttr::IR_ForbiddenWeak; 9149 return true; 9150 } 9151 } 9152 9153 // Allow all sorts of things in system headers. 9154 if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) { 9155 // Currently, all the failures dealt with this way are due to ARC 9156 // restrictions. 9157 reason = UnavailableAttr::IR_ARCForbiddenType; 9158 return true; 9159 } 9160 9161 return false; 9162 } 9163 9164 /// Handle a delayed forbidden-type diagnostic. 9165 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD, 9166 Decl *D) { 9167 auto Reason = UnavailableAttr::IR_None; 9168 if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) { 9169 assert(Reason && "didn't set reason?"); 9170 D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc)); 9171 return; 9172 } 9173 if (S.getLangOpts().ObjCAutoRefCount) 9174 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 9175 // FIXME: we may want to suppress diagnostics for all 9176 // kind of forbidden type messages on unavailable functions. 9177 if (FD->hasAttr<UnavailableAttr>() && 9178 DD.getForbiddenTypeDiagnostic() == 9179 diag::err_arc_array_param_no_ownership) { 9180 DD.Triggered = true; 9181 return; 9182 } 9183 } 9184 9185 S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic()) 9186 << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument(); 9187 DD.Triggered = true; 9188 } 9189 9190 9191 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) { 9192 assert(DelayedDiagnostics.getCurrentPool()); 9193 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool(); 9194 DelayedDiagnostics.popWithoutEmitting(state); 9195 9196 // When delaying diagnostics to run in the context of a parsed 9197 // declaration, we only want to actually emit anything if parsing 9198 // succeeds. 9199 if (!decl) return; 9200 9201 // We emit all the active diagnostics in this pool or any of its 9202 // parents. In general, we'll get one pool for the decl spec 9203 // and a child pool for each declarator; in a decl group like: 9204 // deprecated_typedef foo, *bar, baz(); 9205 // only the declarator pops will be passed decls. This is correct; 9206 // we really do need to consider delayed diagnostics from the decl spec 9207 // for each of the different declarations. 9208 const DelayedDiagnosticPool *pool = &poppedPool; 9209 do { 9210 bool AnyAccessFailures = false; 9211 for (DelayedDiagnosticPool::pool_iterator 9212 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) { 9213 // This const_cast is a bit lame. Really, Triggered should be mutable. 9214 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i); 9215 if (diag.Triggered) 9216 continue; 9217 9218 switch (diag.Kind) { 9219 case DelayedDiagnostic::Availability: 9220 // Don't bother giving deprecation/unavailable diagnostics if 9221 // the decl is invalid. 9222 if (!decl->isInvalidDecl()) 9223 handleDelayedAvailabilityCheck(diag, decl); 9224 break; 9225 9226 case DelayedDiagnostic::Access: 9227 // Only produce one access control diagnostic for a structured binding 9228 // declaration: we don't need to tell the user that all the fields are 9229 // inaccessible one at a time. 9230 if (AnyAccessFailures && isa<DecompositionDecl>(decl)) 9231 continue; 9232 HandleDelayedAccessCheck(diag, decl); 9233 if (diag.Triggered) 9234 AnyAccessFailures = true; 9235 break; 9236 9237 case DelayedDiagnostic::ForbiddenType: 9238 handleDelayedForbiddenType(*this, diag, decl); 9239 break; 9240 } 9241 } 9242 } while ((pool = pool->getParent())); 9243 } 9244 9245 /// Given a set of delayed diagnostics, re-emit them as if they had 9246 /// been delayed in the current context instead of in the given pool. 9247 /// Essentially, this just moves them to the current pool. 9248 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) { 9249 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool(); 9250 assert(curPool && "re-emitting in undelayed context not supported"); 9251 curPool->steal(pool); 9252 } 9253