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