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