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