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