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/Sema/SemaInternal.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/DeclTemplate.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/Mangle.h" 23 #include "clang/AST/ASTMutationListener.h" 24 #include "clang/Basic/CharInfo.h" 25 #include "clang/Basic/SourceManager.h" 26 #include "clang/Basic/TargetInfo.h" 27 #include "clang/Lex/Preprocessor.h" 28 #include "clang/Sema/DeclSpec.h" 29 #include "clang/Sema/DelayedDiagnostic.h" 30 #include "clang/Sema/Lookup.h" 31 #include "clang/Sema/Scope.h" 32 #include "llvm/ADT/StringExtras.h" 33 #include "llvm/Support/MathExtras.h" 34 using namespace clang; 35 using namespace sema; 36 37 namespace AttributeLangSupport { 38 enum LANG { 39 C, 40 Cpp, 41 ObjC 42 }; 43 } 44 45 //===----------------------------------------------------------------------===// 46 // Helper functions 47 //===----------------------------------------------------------------------===// 48 49 /// isFunctionOrMethod - Return true if the given decl has function 50 /// type (function or function-typed variable) or an Objective-C 51 /// method. 52 static bool isFunctionOrMethod(const Decl *D) { 53 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D); 54 } 55 /// \brief Return true if the given decl has function type (function or 56 /// function-typed variable) or an Objective-C method or a block. 57 static bool isFunctionOrMethodOrBlock(const Decl *D) { 58 return isFunctionOrMethod(D) || isa<BlockDecl>(D); 59 } 60 61 /// Return true if the given decl has a declarator that should have 62 /// been processed by Sema::GetTypeForDeclarator. 63 static bool hasDeclarator(const Decl *D) { 64 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl. 65 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) || 66 isa<ObjCPropertyDecl>(D); 67 } 68 69 /// hasFunctionProto - Return true if the given decl has a argument 70 /// information. This decl should have already passed 71 /// isFunctionOrMethod or isFunctionOrMethodOrBlock. 72 static bool hasFunctionProto(const Decl *D) { 73 if (const FunctionType *FnTy = D->getFunctionType()) 74 return isa<FunctionProtoType>(FnTy); 75 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D); 76 } 77 78 /// getFunctionOrMethodNumParams - Return number of function or method 79 /// parameters. It is an error to call this on a K&R function (use 80 /// hasFunctionProto first). 81 static unsigned getFunctionOrMethodNumParams(const Decl *D) { 82 if (const FunctionType *FnTy = D->getFunctionType()) 83 return cast<FunctionProtoType>(FnTy)->getNumParams(); 84 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 85 return BD->getNumParams(); 86 return cast<ObjCMethodDecl>(D)->param_size(); 87 } 88 89 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) { 90 if (const FunctionType *FnTy = D->getFunctionType()) 91 return cast<FunctionProtoType>(FnTy)->getParamType(Idx); 92 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 93 return BD->getParamDecl(Idx)->getType(); 94 95 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType(); 96 } 97 98 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) { 99 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 100 return FD->getParamDecl(Idx)->getSourceRange(); 101 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 102 return MD->parameters()[Idx]->getSourceRange(); 103 if (const auto *BD = dyn_cast<BlockDecl>(D)) 104 return BD->getParamDecl(Idx)->getSourceRange(); 105 return SourceRange(); 106 } 107 108 static QualType getFunctionOrMethodResultType(const Decl *D) { 109 if (const FunctionType *FnTy = D->getFunctionType()) 110 return cast<FunctionType>(FnTy)->getReturnType(); 111 return cast<ObjCMethodDecl>(D)->getReturnType(); 112 } 113 114 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) { 115 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 116 return FD->getReturnTypeSourceRange(); 117 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 118 return MD->getReturnTypeSourceRange(); 119 return SourceRange(); 120 } 121 122 static bool isFunctionOrMethodVariadic(const Decl *D) { 123 if (const FunctionType *FnTy = D->getFunctionType()) { 124 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy); 125 return proto->isVariadic(); 126 } 127 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 128 return BD->isVariadic(); 129 130 return cast<ObjCMethodDecl>(D)->isVariadic(); 131 } 132 133 static bool isInstanceMethod(const Decl *D) { 134 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) 135 return MethodDecl->isInstance(); 136 return false; 137 } 138 139 static inline bool isNSStringType(QualType T, ASTContext &Ctx) { 140 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>(); 141 if (!PT) 142 return false; 143 144 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface(); 145 if (!Cls) 146 return false; 147 148 IdentifierInfo* ClsName = Cls->getIdentifier(); 149 150 // FIXME: Should we walk the chain of classes? 151 return ClsName == &Ctx.Idents.get("NSString") || 152 ClsName == &Ctx.Idents.get("NSMutableString"); 153 } 154 155 static inline bool isCFStringType(QualType T, ASTContext &Ctx) { 156 const PointerType *PT = T->getAs<PointerType>(); 157 if (!PT) 158 return false; 159 160 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>(); 161 if (!RT) 162 return false; 163 164 const RecordDecl *RD = RT->getDecl(); 165 if (RD->getTagKind() != TTK_Struct) 166 return false; 167 168 return RD->getIdentifier() == &Ctx.Idents.get("__CFString"); 169 } 170 171 static unsigned getNumAttributeArgs(const AttributeList &Attr) { 172 // FIXME: Include the type in the argument list. 173 return Attr.getNumArgs() + Attr.hasParsedType(); 174 } 175 176 template <typename Compare> 177 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr, 178 unsigned Num, unsigned Diag, 179 Compare Comp) { 180 if (Comp(getNumAttributeArgs(Attr), Num)) { 181 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num; 182 return false; 183 } 184 185 return true; 186 } 187 188 /// \brief Check if the attribute has exactly as many args as Num. May 189 /// output an error. 190 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr, 191 unsigned Num) { 192 return checkAttributeNumArgsImpl(S, Attr, Num, 193 diag::err_attribute_wrong_number_arguments, 194 std::not_equal_to<unsigned>()); 195 } 196 197 /// \brief Check if the attribute has at least as many args as Num. May 198 /// output an error. 199 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr, 200 unsigned Num) { 201 return checkAttributeNumArgsImpl(S, Attr, Num, 202 diag::err_attribute_too_few_arguments, 203 std::less<unsigned>()); 204 } 205 206 /// \brief Check if the attribute has at most as many args as Num. May 207 /// output an error. 208 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr, 209 unsigned Num) { 210 return checkAttributeNumArgsImpl(S, Attr, Num, 211 diag::err_attribute_too_many_arguments, 212 std::greater<unsigned>()); 213 } 214 215 /// \brief If Expr is a valid integer constant, get the value of the integer 216 /// expression and return success or failure. May output an error. 217 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr, 218 const Expr *Expr, uint32_t &Val, 219 unsigned Idx = UINT_MAX) { 220 llvm::APSInt I(32); 221 if (Expr->isTypeDependent() || Expr->isValueDependent() || 222 !Expr->isIntegerConstantExpr(I, S.Context)) { 223 if (Idx != UINT_MAX) 224 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 225 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant 226 << Expr->getSourceRange(); 227 else 228 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 229 << Attr.getName() << AANT_ArgumentIntegerConstant 230 << Expr->getSourceRange(); 231 return false; 232 } 233 234 if (!I.isIntN(32)) { 235 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) 236 << I.toString(10, false) << 32 << /* Unsigned */ 1; 237 return false; 238 } 239 240 Val = (uint32_t)I.getZExtValue(); 241 return true; 242 } 243 244 /// \brief Diagnose mutually exclusive attributes when present on a given 245 /// declaration. Returns true if diagnosed. 246 template <typename AttrTy> 247 static bool checkAttrMutualExclusion(Sema &S, Decl *D, 248 const AttributeList &Attr) { 249 if (AttrTy *A = D->getAttr<AttrTy>()) { 250 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 251 << Attr.getName() << A; 252 return true; 253 } 254 return false; 255 } 256 257 /// \brief Check if IdxExpr is a valid parameter index for a function or 258 /// instance method D. May output an error. 259 /// 260 /// \returns true if IdxExpr is a valid index. 261 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D, 262 const AttributeList &Attr, 263 unsigned AttrArgNum, 264 const Expr *IdxExpr, 265 uint64_t &Idx) { 266 assert(isFunctionOrMethodOrBlock(D)); 267 268 // In C++ the implicit 'this' function parameter also counts. 269 // Parameters are counted from one. 270 bool HP = hasFunctionProto(D); 271 bool HasImplicitThisParam = isInstanceMethod(D); 272 bool IV = HP && isFunctionOrMethodVariadic(D); 273 unsigned NumParams = 274 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam; 275 276 llvm::APSInt IdxInt; 277 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() || 278 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) { 279 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 280 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant 281 << IdxExpr->getSourceRange(); 282 return false; 283 } 284 285 Idx = IdxInt.getLimitedValue(); 286 if (Idx < 1 || (!IV && Idx > NumParams)) { 287 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 288 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange(); 289 return false; 290 } 291 Idx--; // Convert to zero-based. 292 if (HasImplicitThisParam) { 293 if (Idx == 0) { 294 S.Diag(Attr.getLoc(), 295 diag::err_attribute_invalid_implicit_this_argument) 296 << Attr.getName() << IdxExpr->getSourceRange(); 297 return false; 298 } 299 --Idx; 300 } 301 302 return true; 303 } 304 305 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal. 306 /// If not emit an error and return false. If the argument is an identifier it 307 /// will emit an error with a fixit hint and treat it as if it was a string 308 /// literal. 309 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr, 310 unsigned ArgNum, StringRef &Str, 311 SourceLocation *ArgLocation) { 312 // Look for identifiers. If we have one emit a hint to fix it to a literal. 313 if (Attr.isArgIdent(ArgNum)) { 314 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum); 315 Diag(Loc->Loc, diag::err_attribute_argument_type) 316 << Attr.getName() << AANT_ArgumentString 317 << FixItHint::CreateInsertion(Loc->Loc, "\"") 318 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(Loc->Loc), "\""); 319 Str = Loc->Ident->getName(); 320 if (ArgLocation) 321 *ArgLocation = Loc->Loc; 322 return true; 323 } 324 325 // Now check for an actual string literal. 326 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum); 327 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts()); 328 if (ArgLocation) 329 *ArgLocation = ArgExpr->getLocStart(); 330 331 if (!Literal || !Literal->isAscii()) { 332 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type) 333 << Attr.getName() << AANT_ArgumentString; 334 return false; 335 } 336 337 Str = Literal->getString(); 338 return true; 339 } 340 341 /// \brief Applies the given attribute to the Decl without performing any 342 /// additional semantic checking. 343 template <typename AttrType> 344 static void handleSimpleAttribute(Sema &S, Decl *D, 345 const AttributeList &Attr) { 346 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context, 347 Attr.getAttributeSpellingListIndex())); 348 } 349 350 /// \brief Check if the passed-in expression is of type int or bool. 351 static bool isIntOrBool(Expr *Exp) { 352 QualType QT = Exp->getType(); 353 return QT->isBooleanType() || QT->isIntegerType(); 354 } 355 356 357 // Check to see if the type is a smart pointer of some kind. We assume 358 // it's a smart pointer if it defines both operator-> and operator*. 359 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) { 360 DeclContextLookupResult Res1 = RT->getDecl()->lookup( 361 S.Context.DeclarationNames.getCXXOperatorName(OO_Star)); 362 if (Res1.empty()) 363 return false; 364 365 DeclContextLookupResult Res2 = RT->getDecl()->lookup( 366 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow)); 367 if (Res2.empty()) 368 return false; 369 370 return true; 371 } 372 373 /// \brief Check if passed in Decl is a pointer type. 374 /// Note that this function may produce an error message. 375 /// \return true if the Decl is a pointer type; false otherwise 376 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D, 377 const AttributeList &Attr) { 378 const ValueDecl *vd = cast<ValueDecl>(D); 379 QualType QT = vd->getType(); 380 if (QT->isAnyPointerType()) 381 return true; 382 383 if (const RecordType *RT = QT->getAs<RecordType>()) { 384 // If it's an incomplete type, it could be a smart pointer; skip it. 385 // (We don't want to force template instantiation if we can avoid it, 386 // since that would alter the order in which templates are instantiated.) 387 if (RT->isIncompleteType()) 388 return true; 389 390 if (threadSafetyCheckIsSmartPointer(S, RT)) 391 return true; 392 } 393 394 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer) 395 << Attr.getName() << QT; 396 return false; 397 } 398 399 /// \brief Checks that the passed in QualType either is of RecordType or points 400 /// to RecordType. Returns the relevant RecordType, null if it does not exit. 401 static const RecordType *getRecordType(QualType QT) { 402 if (const RecordType *RT = QT->getAs<RecordType>()) 403 return RT; 404 405 // Now check if we point to record type. 406 if (const PointerType *PT = QT->getAs<PointerType>()) 407 return PT->getPointeeType()->getAs<RecordType>(); 408 409 return nullptr; 410 } 411 412 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) { 413 const RecordType *RT = getRecordType(Ty); 414 415 if (!RT) 416 return false; 417 418 // Don't check for the capability if the class hasn't been defined yet. 419 if (RT->isIncompleteType()) 420 return true; 421 422 // Allow smart pointers to be used as capability objects. 423 // FIXME -- Check the type that the smart pointer points to. 424 if (threadSafetyCheckIsSmartPointer(S, RT)) 425 return true; 426 427 // Check if the record itself has a capability. 428 RecordDecl *RD = RT->getDecl(); 429 if (RD->hasAttr<CapabilityAttr>()) 430 return true; 431 432 // Else check if any base classes have a capability. 433 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 434 CXXBasePaths BPaths(false, false); 435 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &P, 436 void *) { 437 return BS->getType()->getAs<RecordType>() 438 ->getDecl()->hasAttr<CapabilityAttr>(); 439 }, nullptr, BPaths)) 440 return true; 441 } 442 return false; 443 } 444 445 static bool checkTypedefTypeForCapability(QualType Ty) { 446 const auto *TD = Ty->getAs<TypedefType>(); 447 if (!TD) 448 return false; 449 450 TypedefNameDecl *TN = TD->getDecl(); 451 if (!TN) 452 return false; 453 454 return TN->hasAttr<CapabilityAttr>(); 455 } 456 457 static bool typeHasCapability(Sema &S, QualType Ty) { 458 if (checkTypedefTypeForCapability(Ty)) 459 return true; 460 461 if (checkRecordTypeForCapability(S, Ty)) 462 return true; 463 464 return false; 465 } 466 467 static bool isCapabilityExpr(Sema &S, const Expr *Ex) { 468 // Capability expressions are simple expressions involving the boolean logic 469 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once 470 // a DeclRefExpr is found, its type should be checked to determine whether it 471 // is a capability or not. 472 473 if (const auto *E = dyn_cast<DeclRefExpr>(Ex)) 474 return typeHasCapability(S, E->getType()); 475 else if (const auto *E = dyn_cast<CastExpr>(Ex)) 476 return isCapabilityExpr(S, E->getSubExpr()); 477 else if (const auto *E = dyn_cast<ParenExpr>(Ex)) 478 return isCapabilityExpr(S, E->getSubExpr()); 479 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) { 480 if (E->getOpcode() == UO_LNot) 481 return isCapabilityExpr(S, E->getSubExpr()); 482 return false; 483 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) { 484 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr) 485 return isCapabilityExpr(S, E->getLHS()) && 486 isCapabilityExpr(S, E->getRHS()); 487 return false; 488 } 489 490 return false; 491 } 492 493 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to 494 /// a capability object. 495 /// \param Sidx The attribute argument index to start checking with. 496 /// \param ParamIdxOk Whether an argument can be indexing into a function 497 /// parameter list. 498 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D, 499 const AttributeList &Attr, 500 SmallVectorImpl<Expr *> &Args, 501 int Sidx = 0, 502 bool ParamIdxOk = false) { 503 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) { 504 Expr *ArgExp = Attr.getArgAsExpr(Idx); 505 506 if (ArgExp->isTypeDependent()) { 507 // FIXME -- need to check this again on template instantiation 508 Args.push_back(ArgExp); 509 continue; 510 } 511 512 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) { 513 if (StrLit->getLength() == 0 || 514 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) { 515 // Pass empty strings to the analyzer without warnings. 516 // Treat "*" as the universal lock. 517 Args.push_back(ArgExp); 518 continue; 519 } 520 521 // We allow constant strings to be used as a placeholder for expressions 522 // that are not valid C++ syntax, but warn that they are ignored. 523 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) << 524 Attr.getName(); 525 Args.push_back(ArgExp); 526 continue; 527 } 528 529 QualType ArgTy = ArgExp->getType(); 530 531 // A pointer to member expression of the form &MyClass::mu is treated 532 // specially -- we need to look at the type of the member. 533 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp)) 534 if (UOp->getOpcode() == UO_AddrOf) 535 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr())) 536 if (DRE->getDecl()->isCXXInstanceMember()) 537 ArgTy = DRE->getDecl()->getType(); 538 539 // First see if we can just cast to record type, or pointer to record type. 540 const RecordType *RT = getRecordType(ArgTy); 541 542 // Now check if we index into a record type function param. 543 if(!RT && ParamIdxOk) { 544 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 545 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp); 546 if(FD && IL) { 547 unsigned int NumParams = FD->getNumParams(); 548 llvm::APInt ArgValue = IL->getValue(); 549 uint64_t ParamIdxFromOne = ArgValue.getZExtValue(); 550 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1; 551 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) { 552 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range) 553 << Attr.getName() << Idx + 1 << NumParams; 554 continue; 555 } 556 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType(); 557 } 558 } 559 560 // If the type does not have a capability, see if the components of the 561 // expression have capabilities. This allows for writing C code where the 562 // capability may be on the type, and the expression is a capability 563 // boolean logic expression. Eg) requires_capability(A || B && !C) 564 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp)) 565 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable) 566 << Attr.getName() << ArgTy; 567 568 Args.push_back(ArgExp); 569 } 570 } 571 572 //===----------------------------------------------------------------------===// 573 // Attribute Implementations 574 //===----------------------------------------------------------------------===// 575 576 static void handlePtGuardedVarAttr(Sema &S, Decl *D, 577 const AttributeList &Attr) { 578 if (!threadSafetyCheckIsPointer(S, D, Attr)) 579 return; 580 581 D->addAttr(::new (S.Context) 582 PtGuardedVarAttr(Attr.getRange(), S.Context, 583 Attr.getAttributeSpellingListIndex())); 584 } 585 586 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, 587 const AttributeList &Attr, 588 Expr* &Arg) { 589 SmallVector<Expr*, 1> Args; 590 // check that all arguments are lockable objects 591 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 592 unsigned Size = Args.size(); 593 if (Size != 1) 594 return false; 595 596 Arg = Args[0]; 597 598 return true; 599 } 600 601 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) { 602 Expr *Arg = nullptr; 603 if (!checkGuardedByAttrCommon(S, D, Attr, Arg)) 604 return; 605 606 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg, 607 Attr.getAttributeSpellingListIndex())); 608 } 609 610 static void handlePtGuardedByAttr(Sema &S, Decl *D, 611 const AttributeList &Attr) { 612 Expr *Arg = nullptr; 613 if (!checkGuardedByAttrCommon(S, D, Attr, Arg)) 614 return; 615 616 if (!threadSafetyCheckIsPointer(S, D, Attr)) 617 return; 618 619 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(), 620 S.Context, Arg, 621 Attr.getAttributeSpellingListIndex())); 622 } 623 624 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, 625 const AttributeList &Attr, 626 SmallVectorImpl<Expr *> &Args) { 627 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 628 return false; 629 630 // Check that this attribute only applies to lockable types. 631 QualType QT = cast<ValueDecl>(D)->getType(); 632 if (!QT->isDependentType()) { 633 const RecordType *RT = getRecordType(QT); 634 if (!RT || !RT->getDecl()->hasAttr<CapabilityAttr>()) { 635 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable) 636 << Attr.getName(); 637 return false; 638 } 639 } 640 641 // Check that all arguments are lockable objects. 642 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 643 if (Args.empty()) 644 return false; 645 646 return true; 647 } 648 649 static void handleAcquiredAfterAttr(Sema &S, Decl *D, 650 const AttributeList &Attr) { 651 SmallVector<Expr*, 1> Args; 652 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args)) 653 return; 654 655 Expr **StartArg = &Args[0]; 656 D->addAttr(::new (S.Context) 657 AcquiredAfterAttr(Attr.getRange(), S.Context, 658 StartArg, Args.size(), 659 Attr.getAttributeSpellingListIndex())); 660 } 661 662 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, 663 const AttributeList &Attr) { 664 SmallVector<Expr*, 1> Args; 665 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args)) 666 return; 667 668 Expr **StartArg = &Args[0]; 669 D->addAttr(::new (S.Context) 670 AcquiredBeforeAttr(Attr.getRange(), S.Context, 671 StartArg, Args.size(), 672 Attr.getAttributeSpellingListIndex())); 673 } 674 675 static bool checkLockFunAttrCommon(Sema &S, Decl *D, 676 const AttributeList &Attr, 677 SmallVectorImpl<Expr *> &Args) { 678 // zero or more arguments ok 679 // check that all arguments are lockable objects 680 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true); 681 682 return true; 683 } 684 685 static void handleAssertSharedLockAttr(Sema &S, Decl *D, 686 const AttributeList &Attr) { 687 SmallVector<Expr*, 1> Args; 688 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 689 return; 690 691 unsigned Size = Args.size(); 692 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 693 D->addAttr(::new (S.Context) 694 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size, 695 Attr.getAttributeSpellingListIndex())); 696 } 697 698 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D, 699 const AttributeList &Attr) { 700 SmallVector<Expr*, 1> Args; 701 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 702 return; 703 704 unsigned Size = Args.size(); 705 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 706 D->addAttr(::new (S.Context) 707 AssertExclusiveLockAttr(Attr.getRange(), S.Context, 708 StartArg, Size, 709 Attr.getAttributeSpellingListIndex())); 710 } 711 712 713 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, 714 const AttributeList &Attr, 715 SmallVectorImpl<Expr *> &Args) { 716 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 717 return false; 718 719 if (!isIntOrBool(Attr.getArgAsExpr(0))) { 720 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 721 << Attr.getName() << 1 << AANT_ArgumentIntOrBool; 722 return false; 723 } 724 725 // check that all arguments are lockable objects 726 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1); 727 728 return true; 729 } 730 731 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D, 732 const AttributeList &Attr) { 733 SmallVector<Expr*, 2> Args; 734 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 735 return; 736 737 D->addAttr(::new (S.Context) 738 SharedTrylockFunctionAttr(Attr.getRange(), S.Context, 739 Attr.getArgAsExpr(0), 740 Args.data(), Args.size(), 741 Attr.getAttributeSpellingListIndex())); 742 } 743 744 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D, 745 const AttributeList &Attr) { 746 SmallVector<Expr*, 2> Args; 747 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 748 return; 749 750 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr( 751 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(), 752 Args.size(), Attr.getAttributeSpellingListIndex())); 753 } 754 755 static void handleLockReturnedAttr(Sema &S, Decl *D, 756 const AttributeList &Attr) { 757 // check that the argument is lockable object 758 SmallVector<Expr*, 1> Args; 759 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 760 unsigned Size = Args.size(); 761 if (Size == 0) 762 return; 763 764 D->addAttr(::new (S.Context) 765 LockReturnedAttr(Attr.getRange(), S.Context, Args[0], 766 Attr.getAttributeSpellingListIndex())); 767 } 768 769 static void handleLocksExcludedAttr(Sema &S, Decl *D, 770 const AttributeList &Attr) { 771 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 772 return; 773 774 // check that all arguments are lockable objects 775 SmallVector<Expr*, 1> Args; 776 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 777 unsigned Size = Args.size(); 778 if (Size == 0) 779 return; 780 Expr **StartArg = &Args[0]; 781 782 D->addAttr(::new (S.Context) 783 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size, 784 Attr.getAttributeSpellingListIndex())); 785 } 786 787 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) { 788 Expr *Cond = Attr.getArgAsExpr(0); 789 if (!Cond->isTypeDependent()) { 790 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); 791 if (Converted.isInvalid()) 792 return; 793 Cond = Converted.get(); 794 } 795 796 StringRef Msg; 797 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg)) 798 return; 799 800 SmallVector<PartialDiagnosticAt, 8> Diags; 801 if (!Cond->isValueDependent() && 802 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D), 803 Diags)) { 804 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr); 805 for (int I = 0, N = Diags.size(); I != N; ++I) 806 S.Diag(Diags[I].first, Diags[I].second); 807 return; 808 } 809 810 D->addAttr(::new (S.Context) 811 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg, 812 Attr.getAttributeSpellingListIndex())); 813 } 814 815 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) { 816 ConsumableAttr::ConsumedState DefaultState; 817 818 if (Attr.isArgIdent(0)) { 819 IdentifierLoc *IL = Attr.getArgAsIdent(0); 820 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(), 821 DefaultState)) { 822 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) 823 << Attr.getName() << IL->Ident; 824 return; 825 } 826 } else { 827 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 828 << Attr.getName() << AANT_ArgumentIdentifier; 829 return; 830 } 831 832 D->addAttr(::new (S.Context) 833 ConsumableAttr(Attr.getRange(), S.Context, DefaultState, 834 Attr.getAttributeSpellingListIndex())); 835 } 836 837 838 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD, 839 const AttributeList &Attr) { 840 ASTContext &CurrContext = S.getASTContext(); 841 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType(); 842 843 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) { 844 if (!RD->hasAttr<ConsumableAttr>()) { 845 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) << 846 RD->getNameAsString(); 847 848 return false; 849 } 850 } 851 852 return true; 853 } 854 855 856 static void handleCallableWhenAttr(Sema &S, Decl *D, 857 const AttributeList &Attr) { 858 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 859 return; 860 861 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 862 return; 863 864 SmallVector<CallableWhenAttr::ConsumedState, 3> States; 865 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) { 866 CallableWhenAttr::ConsumedState CallableState; 867 868 StringRef StateString; 869 SourceLocation Loc; 870 if (Attr.isArgIdent(ArgIndex)) { 871 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex); 872 StateString = Ident->Ident->getName(); 873 Loc = Ident->Loc; 874 } else { 875 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc)) 876 return; 877 } 878 879 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString, 880 CallableState)) { 881 S.Diag(Loc, diag::warn_attribute_type_not_supported) 882 << Attr.getName() << StateString; 883 return; 884 } 885 886 States.push_back(CallableState); 887 } 888 889 D->addAttr(::new (S.Context) 890 CallableWhenAttr(Attr.getRange(), S.Context, States.data(), 891 States.size(), Attr.getAttributeSpellingListIndex())); 892 } 893 894 895 static void handleParamTypestateAttr(Sema &S, Decl *D, 896 const AttributeList &Attr) { 897 ParamTypestateAttr::ConsumedState ParamState; 898 899 if (Attr.isArgIdent(0)) { 900 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 901 StringRef StateString = Ident->Ident->getName(); 902 903 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString, 904 ParamState)) { 905 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 906 << Attr.getName() << StateString; 907 return; 908 } 909 } else { 910 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 911 Attr.getName() << AANT_ArgumentIdentifier; 912 return; 913 } 914 915 // FIXME: This check is currently being done in the analysis. It can be 916 // enabled here only after the parser propagates attributes at 917 // template specialization definition, not declaration. 918 //QualType ReturnType = cast<ParmVarDecl>(D)->getType(); 919 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 920 // 921 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 922 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << 923 // ReturnType.getAsString(); 924 // return; 925 //} 926 927 D->addAttr(::new (S.Context) 928 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState, 929 Attr.getAttributeSpellingListIndex())); 930 } 931 932 933 static void handleReturnTypestateAttr(Sema &S, Decl *D, 934 const AttributeList &Attr) { 935 ReturnTypestateAttr::ConsumedState ReturnState; 936 937 if (Attr.isArgIdent(0)) { 938 IdentifierLoc *IL = Attr.getArgAsIdent(0); 939 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(), 940 ReturnState)) { 941 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) 942 << Attr.getName() << IL->Ident; 943 return; 944 } 945 } else { 946 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 947 Attr.getName() << AANT_ArgumentIdentifier; 948 return; 949 } 950 951 // FIXME: This check is currently being done in the analysis. It can be 952 // enabled here only after the parser propagates attributes at 953 // template specialization definition, not declaration. 954 //QualType ReturnType; 955 // 956 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) { 957 // ReturnType = Param->getType(); 958 // 959 //} else if (const CXXConstructorDecl *Constructor = 960 // dyn_cast<CXXConstructorDecl>(D)) { 961 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType(); 962 // 963 //} else { 964 // 965 // ReturnType = cast<FunctionDecl>(D)->getCallResultType(); 966 //} 967 // 968 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 969 // 970 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 971 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << 972 // ReturnType.getAsString(); 973 // return; 974 //} 975 976 D->addAttr(::new (S.Context) 977 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState, 978 Attr.getAttributeSpellingListIndex())); 979 } 980 981 982 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) { 983 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 984 return; 985 986 SetTypestateAttr::ConsumedState NewState; 987 if (Attr.isArgIdent(0)) { 988 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 989 StringRef Param = Ident->Ident->getName(); 990 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) { 991 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 992 << Attr.getName() << Param; 993 return; 994 } 995 } else { 996 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 997 Attr.getName() << AANT_ArgumentIdentifier; 998 return; 999 } 1000 1001 D->addAttr(::new (S.Context) 1002 SetTypestateAttr(Attr.getRange(), S.Context, NewState, 1003 Attr.getAttributeSpellingListIndex())); 1004 } 1005 1006 static void handleTestTypestateAttr(Sema &S, Decl *D, 1007 const AttributeList &Attr) { 1008 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 1009 return; 1010 1011 TestTypestateAttr::ConsumedState TestState; 1012 if (Attr.isArgIdent(0)) { 1013 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 1014 StringRef Param = Ident->Ident->getName(); 1015 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) { 1016 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 1017 << Attr.getName() << Param; 1018 return; 1019 } 1020 } else { 1021 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 1022 Attr.getName() << AANT_ArgumentIdentifier; 1023 return; 1024 } 1025 1026 D->addAttr(::new (S.Context) 1027 TestTypestateAttr(Attr.getRange(), S.Context, TestState, 1028 Attr.getAttributeSpellingListIndex())); 1029 } 1030 1031 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D, 1032 const AttributeList &Attr) { 1033 // Remember this typedef decl, we will need it later for diagnostics. 1034 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D)); 1035 } 1036 1037 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1038 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1039 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context, 1040 Attr.getAttributeSpellingListIndex())); 1041 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1042 // If the alignment is less than or equal to 8 bits, the packed attribute 1043 // has no effect. 1044 if (!FD->getType()->isDependentType() && 1045 !FD->getType()->isIncompleteType() && 1046 S.Context.getTypeAlign(FD->getType()) <= 8) 1047 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type) 1048 << Attr.getName() << FD->getType(); 1049 else 1050 FD->addAttr(::new (S.Context) 1051 PackedAttr(Attr.getRange(), S.Context, 1052 Attr.getAttributeSpellingListIndex())); 1053 } else 1054 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1055 } 1056 1057 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) { 1058 // The IBOutlet/IBOutletCollection attributes only apply to instance 1059 // variables or properties of Objective-C classes. The outlet must also 1060 // have an object reference type. 1061 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) { 1062 if (!VD->getType()->getAs<ObjCObjectPointerType>()) { 1063 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type) 1064 << Attr.getName() << VD->getType() << 0; 1065 return false; 1066 } 1067 } 1068 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) { 1069 if (!PD->getType()->getAs<ObjCObjectPointerType>()) { 1070 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type) 1071 << Attr.getName() << PD->getType() << 1; 1072 return false; 1073 } 1074 } 1075 else { 1076 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName(); 1077 return false; 1078 } 1079 1080 return true; 1081 } 1082 1083 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) { 1084 if (!checkIBOutletCommon(S, D, Attr)) 1085 return; 1086 1087 D->addAttr(::new (S.Context) 1088 IBOutletAttr(Attr.getRange(), S.Context, 1089 Attr.getAttributeSpellingListIndex())); 1090 } 1091 1092 static void handleIBOutletCollection(Sema &S, Decl *D, 1093 const AttributeList &Attr) { 1094 1095 // The iboutletcollection attribute can have zero or one arguments. 1096 if (Attr.getNumArgs() > 1) { 1097 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 1098 << Attr.getName() << 1; 1099 return; 1100 } 1101 1102 if (!checkIBOutletCommon(S, D, Attr)) 1103 return; 1104 1105 ParsedType PT; 1106 1107 if (Attr.hasParsedType()) 1108 PT = Attr.getTypeArg(); 1109 else { 1110 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(), 1111 S.getScopeForContext(D->getDeclContext()->getParent())); 1112 if (!PT) { 1113 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject"; 1114 return; 1115 } 1116 } 1117 1118 TypeSourceInfo *QTLoc = nullptr; 1119 QualType QT = S.GetTypeFromParser(PT, &QTLoc); 1120 if (!QTLoc) 1121 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc()); 1122 1123 // Diagnose use of non-object type in iboutletcollection attribute. 1124 // FIXME. Gnu attribute extension ignores use of builtin types in 1125 // attributes. So, __attribute__((iboutletcollection(char))) will be 1126 // treated as __attribute__((iboutletcollection())). 1127 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) { 1128 S.Diag(Attr.getLoc(), 1129 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype 1130 : diag::err_iboutletcollection_type) << QT; 1131 return; 1132 } 1133 1134 D->addAttr(::new (S.Context) 1135 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc, 1136 Attr.getAttributeSpellingListIndex())); 1137 } 1138 1139 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) { 1140 if (RefOkay) { 1141 if (T->isReferenceType()) 1142 return true; 1143 } else { 1144 T = T.getNonReferenceType(); 1145 } 1146 1147 // The nonnull attribute, and other similar attributes, can be applied to a 1148 // transparent union that contains a pointer type. 1149 if (const RecordType *UT = T->getAsUnionType()) { 1150 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) { 1151 RecordDecl *UD = UT->getDecl(); 1152 for (const auto *I : UD->fields()) { 1153 QualType QT = I->getType(); 1154 if (QT->isAnyPointerType() || QT->isBlockPointerType()) 1155 return true; 1156 } 1157 } 1158 } 1159 1160 return T->isAnyPointerType() || T->isBlockPointerType(); 1161 } 1162 1163 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr, 1164 SourceRange AttrParmRange, 1165 SourceRange TypeRange, 1166 bool isReturnValue = false) { 1167 if (!S.isValidPointerAttrType(T)) { 1168 S.Diag(Attr.getLoc(), isReturnValue 1169 ? diag::warn_attribute_return_pointers_only 1170 : diag::warn_attribute_pointers_only) 1171 << Attr.getName() << AttrParmRange << TypeRange; 1172 return false; 1173 } 1174 return true; 1175 } 1176 1177 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1178 SmallVector<unsigned, 8> NonNullArgs; 1179 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) { 1180 Expr *Ex = Attr.getArgAsExpr(I); 1181 uint64_t Idx; 1182 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx)) 1183 return; 1184 1185 // Is the function argument a pointer type? 1186 if (Idx < getFunctionOrMethodNumParams(D) && 1187 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr, 1188 Ex->getSourceRange(), 1189 getFunctionOrMethodParamRange(D, Idx))) 1190 continue; 1191 1192 NonNullArgs.push_back(Idx); 1193 } 1194 1195 // If no arguments were specified to __attribute__((nonnull)) then all pointer 1196 // arguments have a nonnull attribute; warn if there aren't any. Skip this 1197 // check if the attribute came from a macro expansion or a template 1198 // instantiation. 1199 if (NonNullArgs.empty() && Attr.getLoc().isFileID() && 1200 S.ActiveTemplateInstantiations.empty()) { 1201 bool AnyPointers = isFunctionOrMethodVariadic(D); 1202 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); 1203 I != E && !AnyPointers; ++I) { 1204 QualType T = getFunctionOrMethodParamType(D, I); 1205 if (T->isDependentType() || S.isValidPointerAttrType(T)) 1206 AnyPointers = true; 1207 } 1208 1209 if (!AnyPointers) 1210 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers); 1211 } 1212 1213 unsigned *Start = NonNullArgs.data(); 1214 unsigned Size = NonNullArgs.size(); 1215 llvm::array_pod_sort(Start, Start + Size); 1216 D->addAttr(::new (S.Context) 1217 NonNullAttr(Attr.getRange(), S.Context, Start, Size, 1218 Attr.getAttributeSpellingListIndex())); 1219 } 1220 1221 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D, 1222 const AttributeList &Attr) { 1223 if (Attr.getNumArgs() > 0) { 1224 if (D->getFunctionType()) { 1225 handleNonNullAttr(S, D, Attr); 1226 } else { 1227 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args) 1228 << D->getSourceRange(); 1229 } 1230 return; 1231 } 1232 1233 // Is the argument a pointer type? 1234 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(), 1235 D->getSourceRange())) 1236 return; 1237 1238 D->addAttr(::new (S.Context) 1239 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0, 1240 Attr.getAttributeSpellingListIndex())); 1241 } 1242 1243 static void handleReturnsNonNullAttr(Sema &S, Decl *D, 1244 const AttributeList &Attr) { 1245 QualType ResultType = getFunctionOrMethodResultType(D); 1246 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1247 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR, 1248 /* isReturnValue */ true)) 1249 return; 1250 1251 D->addAttr(::new (S.Context) 1252 ReturnsNonNullAttr(Attr.getRange(), S.Context, 1253 Attr.getAttributeSpellingListIndex())); 1254 } 1255 1256 static void handleAssumeAlignedAttr(Sema &S, Decl *D, 1257 const AttributeList &Attr) { 1258 Expr *E = Attr.getArgAsExpr(0), 1259 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr; 1260 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE, 1261 Attr.getAttributeSpellingListIndex()); 1262 } 1263 1264 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 1265 Expr *OE, unsigned SpellingListIndex) { 1266 QualType ResultType = getFunctionOrMethodResultType(D); 1267 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1268 1269 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex); 1270 SourceLocation AttrLoc = AttrRange.getBegin(); 1271 1272 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) { 1273 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) 1274 << &TmpAttr << AttrRange << SR; 1275 return; 1276 } 1277 1278 if (!E->isValueDependent()) { 1279 llvm::APSInt I(64); 1280 if (!E->isIntegerConstantExpr(I, Context)) { 1281 if (OE) 1282 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1283 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant 1284 << E->getSourceRange(); 1285 else 1286 Diag(AttrLoc, diag::err_attribute_argument_type) 1287 << &TmpAttr << AANT_ArgumentIntegerConstant 1288 << E->getSourceRange(); 1289 return; 1290 } 1291 1292 if (!I.isPowerOf2()) { 1293 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 1294 << E->getSourceRange(); 1295 return; 1296 } 1297 } 1298 1299 if (OE) { 1300 if (!OE->isValueDependent()) { 1301 llvm::APSInt I(64); 1302 if (!OE->isIntegerConstantExpr(I, Context)) { 1303 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1304 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant 1305 << OE->getSourceRange(); 1306 return; 1307 } 1308 } 1309 } 1310 1311 D->addAttr(::new (Context) 1312 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex)); 1313 } 1314 1315 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) { 1316 // This attribute must be applied to a function declaration. The first 1317 // argument to the attribute must be an identifier, the name of the resource, 1318 // for example: malloc. The following arguments must be argument indexes, the 1319 // arguments must be of integer type for Returns, otherwise of pointer type. 1320 // The difference between Holds and Takes is that a pointer may still be used 1321 // after being held. free() should be __attribute((ownership_takes)), whereas 1322 // a list append function may well be __attribute((ownership_holds)). 1323 1324 if (!AL.isArgIdent(0)) { 1325 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 1326 << AL.getName() << 1 << AANT_ArgumentIdentifier; 1327 return; 1328 } 1329 1330 // Figure out our Kind. 1331 OwnershipAttr::OwnershipKind K = 1332 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0, 1333 AL.getAttributeSpellingListIndex()).getOwnKind(); 1334 1335 // Check arguments. 1336 switch (K) { 1337 case OwnershipAttr::Takes: 1338 case OwnershipAttr::Holds: 1339 if (AL.getNumArgs() < 2) { 1340 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) 1341 << AL.getName() << 2; 1342 return; 1343 } 1344 break; 1345 case OwnershipAttr::Returns: 1346 if (AL.getNumArgs() > 2) { 1347 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) 1348 << AL.getName() << 1; 1349 return; 1350 } 1351 break; 1352 } 1353 1354 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident; 1355 1356 // Normalize the argument, __foo__ becomes foo. 1357 StringRef ModuleName = Module->getName(); 1358 if (ModuleName.startswith("__") && ModuleName.endswith("__") && 1359 ModuleName.size() > 4) { 1360 ModuleName = ModuleName.drop_front(2).drop_back(2); 1361 Module = &S.PP.getIdentifierTable().get(ModuleName); 1362 } 1363 1364 SmallVector<unsigned, 8> OwnershipArgs; 1365 for (unsigned i = 1; i < AL.getNumArgs(); ++i) { 1366 Expr *Ex = AL.getArgAsExpr(i); 1367 uint64_t Idx; 1368 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx)) 1369 return; 1370 1371 // Is the function argument a pointer type? 1372 QualType T = getFunctionOrMethodParamType(D, Idx); 1373 int Err = -1; // No error 1374 switch (K) { 1375 case OwnershipAttr::Takes: 1376 case OwnershipAttr::Holds: 1377 if (!T->isAnyPointerType() && !T->isBlockPointerType()) 1378 Err = 0; 1379 break; 1380 case OwnershipAttr::Returns: 1381 if (!T->isIntegerType()) 1382 Err = 1; 1383 break; 1384 } 1385 if (-1 != Err) { 1386 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err 1387 << Ex->getSourceRange(); 1388 return; 1389 } 1390 1391 // Check we don't have a conflict with another ownership attribute. 1392 for (const auto *I : D->specific_attrs<OwnershipAttr>()) { 1393 // Cannot have two ownership attributes of different kinds for the same 1394 // index. 1395 if (I->getOwnKind() != K && I->args_end() != 1396 std::find(I->args_begin(), I->args_end(), Idx)) { 1397 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) 1398 << AL.getName() << I; 1399 return; 1400 } else if (K == OwnershipAttr::Returns && 1401 I->getOwnKind() == OwnershipAttr::Returns) { 1402 // A returns attribute conflicts with any other returns attribute using 1403 // a different index. Note, diagnostic reporting is 1-based, but stored 1404 // argument indexes are 0-based. 1405 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) { 1406 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch) 1407 << *(I->args_begin()) + 1; 1408 if (I->args_size()) 1409 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch) 1410 << (unsigned)Idx + 1 << Ex->getSourceRange(); 1411 return; 1412 } 1413 } 1414 } 1415 OwnershipArgs.push_back(Idx); 1416 } 1417 1418 unsigned* start = OwnershipArgs.data(); 1419 unsigned size = OwnershipArgs.size(); 1420 llvm::array_pod_sort(start, start + size); 1421 1422 D->addAttr(::new (S.Context) 1423 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size, 1424 AL.getAttributeSpellingListIndex())); 1425 } 1426 1427 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1428 // Check the attribute arguments. 1429 if (Attr.getNumArgs() > 1) { 1430 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 1431 << Attr.getName() << 1; 1432 return; 1433 } 1434 1435 NamedDecl *nd = cast<NamedDecl>(D); 1436 1437 // gcc rejects 1438 // class c { 1439 // static int a __attribute__((weakref ("v2"))); 1440 // static int b() __attribute__((weakref ("f3"))); 1441 // }; 1442 // and ignores the attributes of 1443 // void f(void) { 1444 // static int a __attribute__((weakref ("v2"))); 1445 // } 1446 // we reject them 1447 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext(); 1448 if (!Ctx->isFileContext()) { 1449 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) 1450 << nd; 1451 return; 1452 } 1453 1454 // The GCC manual says 1455 // 1456 // At present, a declaration to which `weakref' is attached can only 1457 // be `static'. 1458 // 1459 // It also says 1460 // 1461 // Without a TARGET, 1462 // given as an argument to `weakref' or to `alias', `weakref' is 1463 // equivalent to `weak'. 1464 // 1465 // gcc 4.4.1 will accept 1466 // int a7 __attribute__((weakref)); 1467 // as 1468 // int a7 __attribute__((weak)); 1469 // This looks like a bug in gcc. We reject that for now. We should revisit 1470 // it if this behaviour is actually used. 1471 1472 // GCC rejects 1473 // static ((alias ("y"), weakref)). 1474 // Should we? How to check that weakref is before or after alias? 1475 1476 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead 1477 // of transforming it into an AliasAttr. The WeakRefAttr never uses the 1478 // StringRef parameter it was given anyway. 1479 StringRef Str; 1480 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1481 // GCC will accept anything as the argument of weakref. Should we 1482 // check for an existing decl? 1483 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str, 1484 Attr.getAttributeSpellingListIndex())); 1485 1486 D->addAttr(::new (S.Context) 1487 WeakRefAttr(Attr.getRange(), S.Context, 1488 Attr.getAttributeSpellingListIndex())); 1489 } 1490 1491 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1492 StringRef Str; 1493 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1494 return; 1495 1496 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 1497 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin); 1498 return; 1499 } 1500 1501 // Aliases should be on declarations, not definitions. 1502 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 1503 if (FD->isThisDeclarationADefinition()) { 1504 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD; 1505 return; 1506 } 1507 } else { 1508 const auto *VD = cast<VarDecl>(D); 1509 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) { 1510 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD; 1511 return; 1512 } 1513 } 1514 1515 // FIXME: check if target symbol exists in current file 1516 1517 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str, 1518 Attr.getAttributeSpellingListIndex())); 1519 } 1520 1521 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1522 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr)) 1523 return; 1524 1525 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context, 1526 Attr.getAttributeSpellingListIndex())); 1527 } 1528 1529 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1530 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr)) 1531 return; 1532 1533 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context, 1534 Attr.getAttributeSpellingListIndex())); 1535 } 1536 1537 static void handleTLSModelAttr(Sema &S, Decl *D, 1538 const AttributeList &Attr) { 1539 StringRef Model; 1540 SourceLocation LiteralLoc; 1541 // Check that it is a string. 1542 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc)) 1543 return; 1544 1545 // Check that the value. 1546 if (Model != "global-dynamic" && Model != "local-dynamic" 1547 && Model != "initial-exec" && Model != "local-exec") { 1548 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg); 1549 return; 1550 } 1551 1552 D->addAttr(::new (S.Context) 1553 TLSModelAttr(Attr.getRange(), S.Context, Model, 1554 Attr.getAttributeSpellingListIndex())); 1555 } 1556 1557 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1558 QualType ResultType = getFunctionOrMethodResultType(D); 1559 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) { 1560 D->addAttr(::new (S.Context) RestrictAttr( 1561 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1562 return; 1563 } 1564 1565 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only) 1566 << Attr.getName() << getFunctionOrMethodResultSourceRange(D); 1567 } 1568 1569 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1570 if (S.LangOpts.CPlusPlus) { 1571 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 1572 << Attr.getName() << AttributeLangSupport::Cpp; 1573 return; 1574 } 1575 1576 D->addAttr(::new (S.Context) CommonAttr(Attr.getRange(), S.Context, 1577 Attr.getAttributeSpellingListIndex())); 1578 } 1579 1580 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) { 1581 if (hasDeclarator(D)) return; 1582 1583 if (S.CheckNoReturnAttr(attr)) return; 1584 1585 if (!isa<ObjCMethodDecl>(D)) { 1586 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type) 1587 << attr.getName() << ExpectedFunctionOrMethod; 1588 return; 1589 } 1590 1591 D->addAttr(::new (S.Context) 1592 NoReturnAttr(attr.getRange(), S.Context, 1593 attr.getAttributeSpellingListIndex())); 1594 } 1595 1596 bool Sema::CheckNoReturnAttr(const AttributeList &attr) { 1597 if (!checkAttributeNumArgs(*this, attr, 0)) { 1598 attr.setInvalid(); 1599 return true; 1600 } 1601 1602 return false; 1603 } 1604 1605 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, 1606 const AttributeList &Attr) { 1607 1608 // The checking path for 'noreturn' and 'analyzer_noreturn' are different 1609 // because 'analyzer_noreturn' does not impact the type. 1610 if (!isFunctionOrMethodOrBlock(D)) { 1611 ValueDecl *VD = dyn_cast<ValueDecl>(D); 1612 if (!VD || (!VD->getType()->isBlockPointerType() && 1613 !VD->getType()->isFunctionPointerType())) { 1614 S.Diag(Attr.getLoc(), 1615 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type 1616 : diag::warn_attribute_wrong_decl_type) 1617 << Attr.getName() << ExpectedFunctionMethodOrBlock; 1618 return; 1619 } 1620 } 1621 1622 D->addAttr(::new (S.Context) 1623 AnalyzerNoReturnAttr(Attr.getRange(), S.Context, 1624 Attr.getAttributeSpellingListIndex())); 1625 } 1626 1627 // PS3 PPU-specific. 1628 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1629 /* 1630 Returning a Vector Class in Registers 1631 1632 According to the PPU ABI specifications, a class with a single member of 1633 vector type is returned in memory when used as the return value of a function. 1634 This results in inefficient code when implementing vector classes. To return 1635 the value in a single vector register, add the vecreturn attribute to the 1636 class definition. This attribute is also applicable to struct types. 1637 1638 Example: 1639 1640 struct Vector 1641 { 1642 __vector float xyzw; 1643 } __attribute__((vecreturn)); 1644 1645 Vector Add(Vector lhs, Vector rhs) 1646 { 1647 Vector result; 1648 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw); 1649 return result; // This will be returned in a register 1650 } 1651 */ 1652 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) { 1653 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A; 1654 return; 1655 } 1656 1657 RecordDecl *record = cast<RecordDecl>(D); 1658 int count = 0; 1659 1660 if (!isa<CXXRecordDecl>(record)) { 1661 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 1662 return; 1663 } 1664 1665 if (!cast<CXXRecordDecl>(record)->isPOD()) { 1666 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record); 1667 return; 1668 } 1669 1670 for (const auto *I : record->fields()) { 1671 if ((count == 1) || !I->getType()->isVectorType()) { 1672 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 1673 return; 1674 } 1675 count++; 1676 } 1677 1678 D->addAttr(::new (S.Context) 1679 VecReturnAttr(Attr.getRange(), S.Context, 1680 Attr.getAttributeSpellingListIndex())); 1681 } 1682 1683 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D, 1684 const AttributeList &Attr) { 1685 if (isa<ParmVarDecl>(D)) { 1686 // [[carries_dependency]] can only be applied to a parameter if it is a 1687 // parameter of a function declaration or lambda. 1688 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) { 1689 S.Diag(Attr.getLoc(), 1690 diag::err_carries_dependency_param_not_function_decl); 1691 return; 1692 } 1693 } 1694 1695 D->addAttr(::new (S.Context) CarriesDependencyAttr( 1696 Attr.getRange(), S.Context, 1697 Attr.getAttributeSpellingListIndex())); 1698 } 1699 1700 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1701 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1702 if (VD->hasLocalStorage()) { 1703 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1704 return; 1705 } 1706 } else if (!isFunctionOrMethod(D)) { 1707 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 1708 << Attr.getName() << ExpectedVariableOrFunction; 1709 return; 1710 } 1711 1712 D->addAttr(::new (S.Context) 1713 UsedAttr(Attr.getRange(), S.Context, 1714 Attr.getAttributeSpellingListIndex())); 1715 } 1716 1717 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1718 uint32_t priority = ConstructorAttr::DefaultPriority; 1719 if (Attr.getNumArgs() && 1720 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority)) 1721 return; 1722 1723 D->addAttr(::new (S.Context) 1724 ConstructorAttr(Attr.getRange(), S.Context, priority, 1725 Attr.getAttributeSpellingListIndex())); 1726 } 1727 1728 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1729 uint32_t priority = DestructorAttr::DefaultPriority; 1730 if (Attr.getNumArgs() && 1731 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority)) 1732 return; 1733 1734 D->addAttr(::new (S.Context) 1735 DestructorAttr(Attr.getRange(), S.Context, priority, 1736 Attr.getAttributeSpellingListIndex())); 1737 } 1738 1739 template <typename AttrTy> 1740 static void handleAttrWithMessage(Sema &S, Decl *D, 1741 const AttributeList &Attr) { 1742 // Handle the case where the attribute has a text message. 1743 StringRef Str; 1744 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1745 return; 1746 1747 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str, 1748 Attr.getAttributeSpellingListIndex())); 1749 } 1750 1751 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D, 1752 const AttributeList &Attr) { 1753 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) { 1754 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition) 1755 << Attr.getName() << Attr.getRange(); 1756 return; 1757 } 1758 1759 D->addAttr(::new (S.Context) 1760 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context, 1761 Attr.getAttributeSpellingListIndex())); 1762 } 1763 1764 static bool checkAvailabilityAttr(Sema &S, SourceRange Range, 1765 IdentifierInfo *Platform, 1766 VersionTuple Introduced, 1767 VersionTuple Deprecated, 1768 VersionTuple Obsoleted) { 1769 StringRef PlatformName 1770 = AvailabilityAttr::getPrettyPlatformName(Platform->getName()); 1771 if (PlatformName.empty()) 1772 PlatformName = Platform->getName(); 1773 1774 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all 1775 // of these steps are needed). 1776 if (!Introduced.empty() && !Deprecated.empty() && 1777 !(Introduced <= Deprecated)) { 1778 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 1779 << 1 << PlatformName << Deprecated.getAsString() 1780 << 0 << Introduced.getAsString(); 1781 return true; 1782 } 1783 1784 if (!Introduced.empty() && !Obsoleted.empty() && 1785 !(Introduced <= Obsoleted)) { 1786 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 1787 << 2 << PlatformName << Obsoleted.getAsString() 1788 << 0 << Introduced.getAsString(); 1789 return true; 1790 } 1791 1792 if (!Deprecated.empty() && !Obsoleted.empty() && 1793 !(Deprecated <= Obsoleted)) { 1794 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 1795 << 2 << PlatformName << Obsoleted.getAsString() 1796 << 1 << Deprecated.getAsString(); 1797 return true; 1798 } 1799 1800 return false; 1801 } 1802 1803 /// \brief Check whether the two versions match. 1804 /// 1805 /// If either version tuple is empty, then they are assumed to match. If 1806 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y. 1807 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y, 1808 bool BeforeIsOkay) { 1809 if (X.empty() || Y.empty()) 1810 return true; 1811 1812 if (X == Y) 1813 return true; 1814 1815 if (BeforeIsOkay && X < Y) 1816 return true; 1817 1818 return false; 1819 } 1820 1821 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, 1822 IdentifierInfo *Platform, 1823 VersionTuple Introduced, 1824 VersionTuple Deprecated, 1825 VersionTuple Obsoleted, 1826 bool IsUnavailable, 1827 StringRef Message, 1828 bool Override, 1829 unsigned AttrSpellingListIndex) { 1830 VersionTuple MergedIntroduced = Introduced; 1831 VersionTuple MergedDeprecated = Deprecated; 1832 VersionTuple MergedObsoleted = Obsoleted; 1833 bool FoundAny = false; 1834 1835 if (D->hasAttrs()) { 1836 AttrVec &Attrs = D->getAttrs(); 1837 for (unsigned i = 0, e = Attrs.size(); i != e;) { 1838 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]); 1839 if (!OldAA) { 1840 ++i; 1841 continue; 1842 } 1843 1844 IdentifierInfo *OldPlatform = OldAA->getPlatform(); 1845 if (OldPlatform != Platform) { 1846 ++i; 1847 continue; 1848 } 1849 1850 FoundAny = true; 1851 VersionTuple OldIntroduced = OldAA->getIntroduced(); 1852 VersionTuple OldDeprecated = OldAA->getDeprecated(); 1853 VersionTuple OldObsoleted = OldAA->getObsoleted(); 1854 bool OldIsUnavailable = OldAA->getUnavailable(); 1855 1856 if (!versionsMatch(OldIntroduced, Introduced, Override) || 1857 !versionsMatch(Deprecated, OldDeprecated, Override) || 1858 !versionsMatch(Obsoleted, OldObsoleted, Override) || 1859 !(OldIsUnavailable == IsUnavailable || 1860 (Override && !OldIsUnavailable && IsUnavailable))) { 1861 if (Override) { 1862 int Which = -1; 1863 VersionTuple FirstVersion; 1864 VersionTuple SecondVersion; 1865 if (!versionsMatch(OldIntroduced, Introduced, Override)) { 1866 Which = 0; 1867 FirstVersion = OldIntroduced; 1868 SecondVersion = Introduced; 1869 } else if (!versionsMatch(Deprecated, OldDeprecated, Override)) { 1870 Which = 1; 1871 FirstVersion = Deprecated; 1872 SecondVersion = OldDeprecated; 1873 } else if (!versionsMatch(Obsoleted, OldObsoleted, Override)) { 1874 Which = 2; 1875 FirstVersion = Obsoleted; 1876 SecondVersion = OldObsoleted; 1877 } 1878 1879 if (Which == -1) { 1880 Diag(OldAA->getLocation(), 1881 diag::warn_mismatched_availability_override_unavail) 1882 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()); 1883 } else { 1884 Diag(OldAA->getLocation(), 1885 diag::warn_mismatched_availability_override) 1886 << Which 1887 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 1888 << FirstVersion.getAsString() << SecondVersion.getAsString(); 1889 } 1890 Diag(Range.getBegin(), diag::note_overridden_method); 1891 } else { 1892 Diag(OldAA->getLocation(), diag::warn_mismatched_availability); 1893 Diag(Range.getBegin(), diag::note_previous_attribute); 1894 } 1895 1896 Attrs.erase(Attrs.begin() + i); 1897 --e; 1898 continue; 1899 } 1900 1901 VersionTuple MergedIntroduced2 = MergedIntroduced; 1902 VersionTuple MergedDeprecated2 = MergedDeprecated; 1903 VersionTuple MergedObsoleted2 = MergedObsoleted; 1904 1905 if (MergedIntroduced2.empty()) 1906 MergedIntroduced2 = OldIntroduced; 1907 if (MergedDeprecated2.empty()) 1908 MergedDeprecated2 = OldDeprecated; 1909 if (MergedObsoleted2.empty()) 1910 MergedObsoleted2 = OldObsoleted; 1911 1912 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform, 1913 MergedIntroduced2, MergedDeprecated2, 1914 MergedObsoleted2)) { 1915 Attrs.erase(Attrs.begin() + i); 1916 --e; 1917 continue; 1918 } 1919 1920 MergedIntroduced = MergedIntroduced2; 1921 MergedDeprecated = MergedDeprecated2; 1922 MergedObsoleted = MergedObsoleted2; 1923 ++i; 1924 } 1925 } 1926 1927 if (FoundAny && 1928 MergedIntroduced == Introduced && 1929 MergedDeprecated == Deprecated && 1930 MergedObsoleted == Obsoleted) 1931 return nullptr; 1932 1933 // Only create a new attribute if !Override, but we want to do 1934 // the checking. 1935 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced, 1936 MergedDeprecated, MergedObsoleted) && 1937 !Override) { 1938 return ::new (Context) AvailabilityAttr(Range, Context, Platform, 1939 Introduced, Deprecated, 1940 Obsoleted, IsUnavailable, Message, 1941 AttrSpellingListIndex); 1942 } 1943 return nullptr; 1944 } 1945 1946 static void handleAvailabilityAttr(Sema &S, Decl *D, 1947 const AttributeList &Attr) { 1948 if (!checkAttributeNumArgs(S, Attr, 1)) 1949 return; 1950 IdentifierLoc *Platform = Attr.getArgAsIdent(0); 1951 unsigned Index = Attr.getAttributeSpellingListIndex(); 1952 1953 IdentifierInfo *II = Platform->Ident; 1954 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty()) 1955 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform) 1956 << Platform->Ident; 1957 1958 NamedDecl *ND = dyn_cast<NamedDecl>(D); 1959 if (!ND) { 1960 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1961 return; 1962 } 1963 1964 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced(); 1965 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated(); 1966 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted(); 1967 bool IsUnavailable = Attr.getUnavailableLoc().isValid(); 1968 StringRef Str; 1969 if (const StringLiteral *SE = 1970 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr())) 1971 Str = SE->getString(); 1972 1973 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II, 1974 Introduced.Version, 1975 Deprecated.Version, 1976 Obsoleted.Version, 1977 IsUnavailable, Str, 1978 /*Override=*/false, 1979 Index); 1980 if (NewAttr) 1981 D->addAttr(NewAttr); 1982 } 1983 1984 template <class T> 1985 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range, 1986 typename T::VisibilityType value, 1987 unsigned attrSpellingListIndex) { 1988 T *existingAttr = D->getAttr<T>(); 1989 if (existingAttr) { 1990 typename T::VisibilityType existingValue = existingAttr->getVisibility(); 1991 if (existingValue == value) 1992 return nullptr; 1993 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility); 1994 S.Diag(range.getBegin(), diag::note_previous_attribute); 1995 D->dropAttr<T>(); 1996 } 1997 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex); 1998 } 1999 2000 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range, 2001 VisibilityAttr::VisibilityType Vis, 2002 unsigned AttrSpellingListIndex) { 2003 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis, 2004 AttrSpellingListIndex); 2005 } 2006 2007 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range, 2008 TypeVisibilityAttr::VisibilityType Vis, 2009 unsigned AttrSpellingListIndex) { 2010 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis, 2011 AttrSpellingListIndex); 2012 } 2013 2014 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr, 2015 bool isTypeVisibility) { 2016 // Visibility attributes don't mean anything on a typedef. 2017 if (isa<TypedefNameDecl>(D)) { 2018 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored) 2019 << Attr.getName(); 2020 return; 2021 } 2022 2023 // 'type_visibility' can only go on a type or namespace. 2024 if (isTypeVisibility && 2025 !(isa<TagDecl>(D) || 2026 isa<ObjCInterfaceDecl>(D) || 2027 isa<NamespaceDecl>(D))) { 2028 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type) 2029 << Attr.getName() << ExpectedTypeOrNamespace; 2030 return; 2031 } 2032 2033 // Check that the argument is a string literal. 2034 StringRef TypeStr; 2035 SourceLocation LiteralLoc; 2036 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc)) 2037 return; 2038 2039 VisibilityAttr::VisibilityType type; 2040 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) { 2041 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) 2042 << Attr.getName() << TypeStr; 2043 return; 2044 } 2045 2046 // Complain about attempts to use protected visibility on targets 2047 // (like Darwin) that don't support it. 2048 if (type == VisibilityAttr::Protected && 2049 !S.Context.getTargetInfo().hasProtectedVisibility()) { 2050 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility); 2051 type = VisibilityAttr::Default; 2052 } 2053 2054 unsigned Index = Attr.getAttributeSpellingListIndex(); 2055 clang::Attr *newAttr; 2056 if (isTypeVisibility) { 2057 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(), 2058 (TypeVisibilityAttr::VisibilityType) type, 2059 Index); 2060 } else { 2061 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index); 2062 } 2063 if (newAttr) 2064 D->addAttr(newAttr); 2065 } 2066 2067 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl, 2068 const AttributeList &Attr) { 2069 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl); 2070 if (!Attr.isArgIdent(0)) { 2071 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2072 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2073 return; 2074 } 2075 2076 IdentifierLoc *IL = Attr.getArgAsIdent(0); 2077 ObjCMethodFamilyAttr::FamilyKind F; 2078 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) { 2079 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() 2080 << IL->Ident; 2081 return; 2082 } 2083 2084 if (F == ObjCMethodFamilyAttr::OMF_init && 2085 !method->getReturnType()->isObjCObjectPointerType()) { 2086 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type) 2087 << method->getReturnType(); 2088 // Ignore the attribute. 2089 return; 2090 } 2091 2092 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(), 2093 S.Context, F, 2094 Attr.getAttributeSpellingListIndex())); 2095 } 2096 2097 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) { 2098 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 2099 QualType T = TD->getUnderlyingType(); 2100 if (!T->isCARCBridgableType()) { 2101 S.Diag(TD->getLocation(), diag::err_nsobject_attribute); 2102 return; 2103 } 2104 } 2105 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) { 2106 QualType T = PD->getType(); 2107 if (!T->isCARCBridgableType()) { 2108 S.Diag(PD->getLocation(), diag::err_nsobject_attribute); 2109 return; 2110 } 2111 } 2112 else { 2113 // It is okay to include this attribute on properties, e.g.: 2114 // 2115 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); 2116 // 2117 // In this case it follows tradition and suppresses an error in the above 2118 // case. 2119 S.Diag(D->getLocation(), diag::warn_nsobject_attribute); 2120 } 2121 D->addAttr(::new (S.Context) 2122 ObjCNSObjectAttr(Attr.getRange(), S.Context, 2123 Attr.getAttributeSpellingListIndex())); 2124 } 2125 2126 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) { 2127 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 2128 QualType T = TD->getUnderlyingType(); 2129 if (!T->isObjCObjectPointerType()) { 2130 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute); 2131 return; 2132 } 2133 } else { 2134 S.Diag(D->getLocation(), diag::warn_independentclass_attribute); 2135 return; 2136 } 2137 D->addAttr(::new (S.Context) 2138 ObjCIndependentClassAttr(Attr.getRange(), S.Context, 2139 Attr.getAttributeSpellingListIndex())); 2140 } 2141 2142 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2143 if (!Attr.isArgIdent(0)) { 2144 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2145 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2146 return; 2147 } 2148 2149 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident; 2150 BlocksAttr::BlockType type; 2151 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) { 2152 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 2153 << Attr.getName() << II; 2154 return; 2155 } 2156 2157 D->addAttr(::new (S.Context) 2158 BlocksAttr(Attr.getRange(), S.Context, type, 2159 Attr.getAttributeSpellingListIndex())); 2160 } 2161 2162 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2163 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel; 2164 if (Attr.getNumArgs() > 0) { 2165 Expr *E = Attr.getArgAsExpr(0); 2166 llvm::APSInt Idx(32); 2167 if (E->isTypeDependent() || E->isValueDependent() || 2168 !E->isIntegerConstantExpr(Idx, S.Context)) { 2169 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2170 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant 2171 << E->getSourceRange(); 2172 return; 2173 } 2174 2175 if (Idx.isSigned() && Idx.isNegative()) { 2176 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero) 2177 << E->getSourceRange(); 2178 return; 2179 } 2180 2181 sentinel = Idx.getZExtValue(); 2182 } 2183 2184 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos; 2185 if (Attr.getNumArgs() > 1) { 2186 Expr *E = Attr.getArgAsExpr(1); 2187 llvm::APSInt Idx(32); 2188 if (E->isTypeDependent() || E->isValueDependent() || 2189 !E->isIntegerConstantExpr(Idx, S.Context)) { 2190 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2191 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant 2192 << E->getSourceRange(); 2193 return; 2194 } 2195 nullPos = Idx.getZExtValue(); 2196 2197 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) { 2198 // FIXME: This error message could be improved, it would be nice 2199 // to say what the bounds actually are. 2200 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one) 2201 << E->getSourceRange(); 2202 return; 2203 } 2204 } 2205 2206 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2207 const FunctionType *FT = FD->getType()->castAs<FunctionType>(); 2208 if (isa<FunctionNoProtoType>(FT)) { 2209 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments); 2210 return; 2211 } 2212 2213 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2214 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2215 return; 2216 } 2217 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 2218 if (!MD->isVariadic()) { 2219 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2220 return; 2221 } 2222 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 2223 if (!BD->isVariadic()) { 2224 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1; 2225 return; 2226 } 2227 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) { 2228 QualType Ty = V->getType(); 2229 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 2230 const FunctionType *FT = Ty->isFunctionPointerType() 2231 ? D->getFunctionType() 2232 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 2233 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2234 int m = Ty->isFunctionPointerType() ? 0 : 1; 2235 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m; 2236 return; 2237 } 2238 } else { 2239 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2240 << Attr.getName() << ExpectedFunctionMethodOrBlock; 2241 return; 2242 } 2243 } else { 2244 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2245 << Attr.getName() << ExpectedFunctionMethodOrBlock; 2246 return; 2247 } 2248 D->addAttr(::new (S.Context) 2249 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos, 2250 Attr.getAttributeSpellingListIndex())); 2251 } 2252 2253 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) { 2254 if (D->getFunctionType() && 2255 D->getFunctionType()->getReturnType()->isVoidType()) { 2256 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method) 2257 << Attr.getName() << 0; 2258 return; 2259 } 2260 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 2261 if (MD->getReturnType()->isVoidType()) { 2262 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method) 2263 << Attr.getName() << 1; 2264 return; 2265 } 2266 2267 D->addAttr(::new (S.Context) 2268 WarnUnusedResultAttr(Attr.getRange(), S.Context, 2269 Attr.getAttributeSpellingListIndex())); 2270 } 2271 2272 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2273 // weak_import only applies to variable & function declarations. 2274 bool isDef = false; 2275 if (!D->canBeWeakImported(isDef)) { 2276 if (isDef) 2277 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition) 2278 << "weak_import"; 2279 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) || 2280 (S.Context.getTargetInfo().getTriple().isOSDarwin() && 2281 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) { 2282 // Nothing to warn about here. 2283 } else 2284 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2285 << Attr.getName() << ExpectedVariableOrFunction; 2286 2287 return; 2288 } 2289 2290 D->addAttr(::new (S.Context) 2291 WeakImportAttr(Attr.getRange(), S.Context, 2292 Attr.getAttributeSpellingListIndex())); 2293 } 2294 2295 // Handles reqd_work_group_size and work_group_size_hint. 2296 template <typename WorkGroupAttr> 2297 static void handleWorkGroupSize(Sema &S, Decl *D, 2298 const AttributeList &Attr) { 2299 uint32_t WGSize[3]; 2300 for (unsigned i = 0; i < 3; ++i) { 2301 const Expr *E = Attr.getArgAsExpr(i); 2302 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i)) 2303 return; 2304 if (WGSize[i] == 0) { 2305 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero) 2306 << Attr.getName() << E->getSourceRange(); 2307 return; 2308 } 2309 } 2310 2311 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>(); 2312 if (Existing && !(Existing->getXDim() == WGSize[0] && 2313 Existing->getYDim() == WGSize[1] && 2314 Existing->getZDim() == WGSize[2])) 2315 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); 2316 2317 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context, 2318 WGSize[0], WGSize[1], WGSize[2], 2319 Attr.getAttributeSpellingListIndex())); 2320 } 2321 2322 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) { 2323 if (!Attr.hasParsedType()) { 2324 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 2325 << Attr.getName() << 1; 2326 return; 2327 } 2328 2329 TypeSourceInfo *ParmTSI = nullptr; 2330 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI); 2331 assert(ParmTSI && "no type source info for attribute argument"); 2332 2333 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() && 2334 (ParmType->isBooleanType() || 2335 !ParmType->isIntegralType(S.getASTContext()))) { 2336 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint) 2337 << ParmType; 2338 return; 2339 } 2340 2341 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) { 2342 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) { 2343 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); 2344 return; 2345 } 2346 } 2347 2348 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context, 2349 ParmTSI, 2350 Attr.getAttributeSpellingListIndex())); 2351 } 2352 2353 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range, 2354 StringRef Name, 2355 unsigned AttrSpellingListIndex) { 2356 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) { 2357 if (ExistingAttr->getName() == Name) 2358 return nullptr; 2359 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section); 2360 Diag(Range.getBegin(), diag::note_previous_attribute); 2361 return nullptr; 2362 } 2363 return ::new (Context) SectionAttr(Range, Context, Name, 2364 AttrSpellingListIndex); 2365 } 2366 2367 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) { 2368 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName); 2369 if (!Error.empty()) { 2370 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error; 2371 return false; 2372 } 2373 return true; 2374 } 2375 2376 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2377 // Make sure that there is a string literal as the sections's single 2378 // argument. 2379 StringRef Str; 2380 SourceLocation LiteralLoc; 2381 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc)) 2382 return; 2383 2384 if (!S.checkSectionName(LiteralLoc, Str)) 2385 return; 2386 2387 // If the target wants to validate the section specifier, make it happen. 2388 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str); 2389 if (!Error.empty()) { 2390 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) 2391 << Error; 2392 return; 2393 } 2394 2395 unsigned Index = Attr.getAttributeSpellingListIndex(); 2396 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index); 2397 if (NewAttr) 2398 D->addAttr(NewAttr); 2399 } 2400 2401 // Check for things we'd like to warn about, no errors or validation for now. 2402 // TODO: Validation should use a backend target library that specifies 2403 // the allowable subtarget features and cpus. We could use something like a 2404 // TargetCodeGenInfo hook here to do validation. 2405 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) { 2406 for (auto Str : {"tune=", "fpmath="}) 2407 if (AttrStr.find(Str) != StringRef::npos) 2408 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str; 2409 } 2410 2411 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2412 StringRef Str; 2413 SourceLocation LiteralLoc; 2414 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc)) 2415 return; 2416 S.checkTargetAttr(LiteralLoc, Str); 2417 unsigned Index = Attr.getAttributeSpellingListIndex(); 2418 TargetAttr *NewAttr = 2419 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index); 2420 D->addAttr(NewAttr); 2421 } 2422 2423 2424 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2425 VarDecl *VD = cast<VarDecl>(D); 2426 if (!VD->hasLocalStorage()) { 2427 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 2428 return; 2429 } 2430 2431 Expr *E = Attr.getArgAsExpr(0); 2432 SourceLocation Loc = E->getExprLoc(); 2433 FunctionDecl *FD = nullptr; 2434 DeclarationNameInfo NI; 2435 2436 // gcc only allows for simple identifiers. Since we support more than gcc, we 2437 // will warn the user. 2438 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 2439 if (DRE->hasQualifier()) 2440 S.Diag(Loc, diag::warn_cleanup_ext); 2441 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 2442 NI = DRE->getNameInfo(); 2443 if (!FD) { 2444 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1 2445 << NI.getName(); 2446 return; 2447 } 2448 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 2449 if (ULE->hasExplicitTemplateArgs()) 2450 S.Diag(Loc, diag::warn_cleanup_ext); 2451 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true); 2452 NI = ULE->getNameInfo(); 2453 if (!FD) { 2454 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2 2455 << NI.getName(); 2456 if (ULE->getType() == S.Context.OverloadTy) 2457 S.NoteAllOverloadCandidates(ULE); 2458 return; 2459 } 2460 } else { 2461 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0; 2462 return; 2463 } 2464 2465 if (FD->getNumParams() != 1) { 2466 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg) 2467 << NI.getName(); 2468 return; 2469 } 2470 2471 // We're currently more strict than GCC about what function types we accept. 2472 // If this ever proves to be a problem it should be easy to fix. 2473 QualType Ty = S.Context.getPointerType(VD->getType()); 2474 QualType ParamTy = FD->getParamDecl(0)->getType(); 2475 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), 2476 ParamTy, Ty) != Sema::Compatible) { 2477 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type) 2478 << NI.getName() << ParamTy << Ty; 2479 return; 2480 } 2481 2482 D->addAttr(::new (S.Context) 2483 CleanupAttr(Attr.getRange(), S.Context, FD, 2484 Attr.getAttributeSpellingListIndex())); 2485 } 2486 2487 /// Handle __attribute__((format_arg((idx)))) attribute based on 2488 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 2489 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2490 Expr *IdxExpr = Attr.getArgAsExpr(0); 2491 uint64_t Idx; 2492 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx)) 2493 return; 2494 2495 // make sure the format string is really a string 2496 QualType Ty = getFunctionOrMethodParamType(D, Idx); 2497 2498 bool not_nsstring_type = !isNSStringType(Ty, S.Context); 2499 if (not_nsstring_type && 2500 !isCFStringType(Ty, S.Context) && 2501 (!Ty->isPointerType() || 2502 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { 2503 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2504 << (not_nsstring_type ? "a string type" : "an NSString") 2505 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); 2506 return; 2507 } 2508 Ty = getFunctionOrMethodResultType(D); 2509 if (!isNSStringType(Ty, S.Context) && 2510 !isCFStringType(Ty, S.Context) && 2511 (!Ty->isPointerType() || 2512 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { 2513 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not) 2514 << (not_nsstring_type ? "string type" : "NSString") 2515 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); 2516 return; 2517 } 2518 2519 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex 2520 // because that has corrected for the implicit this parameter, and is zero- 2521 // based. The attribute expects what the user wrote explicitly. 2522 llvm::APSInt Val; 2523 IdxExpr->EvaluateAsInt(Val, S.Context); 2524 2525 D->addAttr(::new (S.Context) 2526 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(), 2527 Attr.getAttributeSpellingListIndex())); 2528 } 2529 2530 enum FormatAttrKind { 2531 CFStringFormat, 2532 NSStringFormat, 2533 StrftimeFormat, 2534 SupportedFormat, 2535 IgnoredFormat, 2536 InvalidFormat 2537 }; 2538 2539 /// getFormatAttrKind - Map from format attribute names to supported format 2540 /// types. 2541 static FormatAttrKind getFormatAttrKind(StringRef Format) { 2542 return llvm::StringSwitch<FormatAttrKind>(Format) 2543 // Check for formats that get handled specially. 2544 .Case("NSString", NSStringFormat) 2545 .Case("CFString", CFStringFormat) 2546 .Case("strftime", StrftimeFormat) 2547 2548 // Otherwise, check for supported formats. 2549 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat) 2550 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat) 2551 .Case("kprintf", SupportedFormat) // OpenBSD. 2552 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD. 2553 .Case("os_trace", SupportedFormat) 2554 2555 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat) 2556 .Default(InvalidFormat); 2557 } 2558 2559 /// Handle __attribute__((init_priority(priority))) attributes based on 2560 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html 2561 static void handleInitPriorityAttr(Sema &S, Decl *D, 2562 const AttributeList &Attr) { 2563 if (!S.getLangOpts().CPlusPlus) { 2564 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 2565 return; 2566 } 2567 2568 if (S.getCurFunctionOrMethodDecl()) { 2569 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr); 2570 Attr.setInvalid(); 2571 return; 2572 } 2573 QualType T = cast<VarDecl>(D)->getType(); 2574 if (S.Context.getAsArrayType(T)) 2575 T = S.Context.getBaseElementType(T); 2576 if (!T->getAs<RecordType>()) { 2577 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr); 2578 Attr.setInvalid(); 2579 return; 2580 } 2581 2582 Expr *E = Attr.getArgAsExpr(0); 2583 uint32_t prioritynum; 2584 if (!checkUInt32Argument(S, Attr, E, prioritynum)) { 2585 Attr.setInvalid(); 2586 return; 2587 } 2588 2589 if (prioritynum < 101 || prioritynum > 65535) { 2590 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range) 2591 << E->getSourceRange(); 2592 Attr.setInvalid(); 2593 return; 2594 } 2595 D->addAttr(::new (S.Context) 2596 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum, 2597 Attr.getAttributeSpellingListIndex())); 2598 } 2599 2600 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range, 2601 IdentifierInfo *Format, int FormatIdx, 2602 int FirstArg, 2603 unsigned AttrSpellingListIndex) { 2604 // Check whether we already have an equivalent format attribute. 2605 for (auto *F : D->specific_attrs<FormatAttr>()) { 2606 if (F->getType() == Format && 2607 F->getFormatIdx() == FormatIdx && 2608 F->getFirstArg() == FirstArg) { 2609 // If we don't have a valid location for this attribute, adopt the 2610 // location. 2611 if (F->getLocation().isInvalid()) 2612 F->setRange(Range); 2613 return nullptr; 2614 } 2615 } 2616 2617 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx, 2618 FirstArg, AttrSpellingListIndex); 2619 } 2620 2621 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on 2622 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 2623 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2624 if (!Attr.isArgIdent(0)) { 2625 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2626 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2627 return; 2628 } 2629 2630 // In C++ the implicit 'this' function parameter also counts, and they are 2631 // counted from one. 2632 bool HasImplicitThisParam = isInstanceMethod(D); 2633 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam; 2634 2635 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident; 2636 StringRef Format = II->getName(); 2637 2638 // Normalize the argument, __foo__ becomes foo. 2639 if (Format.startswith("__") && Format.endswith("__")) { 2640 Format = Format.substr(2, Format.size() - 4); 2641 // If we've modified the string name, we need a new identifier for it. 2642 II = &S.Context.Idents.get(Format); 2643 } 2644 2645 // Check for supported formats. 2646 FormatAttrKind Kind = getFormatAttrKind(Format); 2647 2648 if (Kind == IgnoredFormat) 2649 return; 2650 2651 if (Kind == InvalidFormat) { 2652 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 2653 << Attr.getName() << II->getName(); 2654 return; 2655 } 2656 2657 // checks for the 2nd argument 2658 Expr *IdxExpr = Attr.getArgAsExpr(1); 2659 uint32_t Idx; 2660 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2)) 2661 return; 2662 2663 if (Idx < 1 || Idx > NumArgs) { 2664 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 2665 << Attr.getName() << 2 << IdxExpr->getSourceRange(); 2666 return; 2667 } 2668 2669 // FIXME: Do we need to bounds check? 2670 unsigned ArgIdx = Idx - 1; 2671 2672 if (HasImplicitThisParam) { 2673 if (ArgIdx == 0) { 2674 S.Diag(Attr.getLoc(), 2675 diag::err_format_attribute_implicit_this_format_string) 2676 << IdxExpr->getSourceRange(); 2677 return; 2678 } 2679 ArgIdx--; 2680 } 2681 2682 // make sure the format string is really a string 2683 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx); 2684 2685 if (Kind == CFStringFormat) { 2686 if (!isCFStringType(Ty, S.Context)) { 2687 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2688 << "a CFString" << IdxExpr->getSourceRange() 2689 << getFunctionOrMethodParamRange(D, ArgIdx); 2690 return; 2691 } 2692 } else if (Kind == NSStringFormat) { 2693 // FIXME: do we need to check if the type is NSString*? What are the 2694 // semantics? 2695 if (!isNSStringType(Ty, S.Context)) { 2696 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2697 << "an NSString" << IdxExpr->getSourceRange() 2698 << getFunctionOrMethodParamRange(D, ArgIdx); 2699 return; 2700 } 2701 } else if (!Ty->isPointerType() || 2702 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) { 2703 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2704 << "a string type" << IdxExpr->getSourceRange() 2705 << getFunctionOrMethodParamRange(D, ArgIdx); 2706 return; 2707 } 2708 2709 // check the 3rd argument 2710 Expr *FirstArgExpr = Attr.getArgAsExpr(2); 2711 uint32_t FirstArg; 2712 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3)) 2713 return; 2714 2715 // check if the function is variadic if the 3rd argument non-zero 2716 if (FirstArg != 0) { 2717 if (isFunctionOrMethodVariadic(D)) { 2718 ++NumArgs; // +1 for ... 2719 } else { 2720 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic); 2721 return; 2722 } 2723 } 2724 2725 // strftime requires FirstArg to be 0 because it doesn't read from any 2726 // variable the input is just the current time + the format string. 2727 if (Kind == StrftimeFormat) { 2728 if (FirstArg != 0) { 2729 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter) 2730 << FirstArgExpr->getSourceRange(); 2731 return; 2732 } 2733 // if 0 it disables parameter checking (to use with e.g. va_list) 2734 } else if (FirstArg != 0 && FirstArg != NumArgs) { 2735 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 2736 << Attr.getName() << 3 << FirstArgExpr->getSourceRange(); 2737 return; 2738 } 2739 2740 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II, 2741 Idx, FirstArg, 2742 Attr.getAttributeSpellingListIndex()); 2743 if (NewAttr) 2744 D->addAttr(NewAttr); 2745 } 2746 2747 static void handleTransparentUnionAttr(Sema &S, Decl *D, 2748 const AttributeList &Attr) { 2749 // Try to find the underlying union declaration. 2750 RecordDecl *RD = nullptr; 2751 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D); 2752 if (TD && TD->getUnderlyingType()->isUnionType()) 2753 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl(); 2754 else 2755 RD = dyn_cast<RecordDecl>(D); 2756 2757 if (!RD || !RD->isUnion()) { 2758 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2759 << Attr.getName() << ExpectedUnion; 2760 return; 2761 } 2762 2763 if (!RD->isCompleteDefinition()) { 2764 S.Diag(Attr.getLoc(), 2765 diag::warn_transparent_union_attribute_not_definition); 2766 return; 2767 } 2768 2769 RecordDecl::field_iterator Field = RD->field_begin(), 2770 FieldEnd = RD->field_end(); 2771 if (Field == FieldEnd) { 2772 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields); 2773 return; 2774 } 2775 2776 FieldDecl *FirstField = *Field; 2777 QualType FirstType = FirstField->getType(); 2778 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) { 2779 S.Diag(FirstField->getLocation(), 2780 diag::warn_transparent_union_attribute_floating) 2781 << FirstType->isVectorType() << FirstType; 2782 return; 2783 } 2784 2785 uint64_t FirstSize = S.Context.getTypeSize(FirstType); 2786 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType); 2787 for (; Field != FieldEnd; ++Field) { 2788 QualType FieldType = Field->getType(); 2789 // FIXME: this isn't fully correct; we also need to test whether the 2790 // members of the union would all have the same calling convention as the 2791 // first member of the union. Checking just the size and alignment isn't 2792 // sufficient (consider structs passed on the stack instead of in registers 2793 // as an example). 2794 if (S.Context.getTypeSize(FieldType) != FirstSize || 2795 S.Context.getTypeAlign(FieldType) > FirstAlign) { 2796 // Warn if we drop the attribute. 2797 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize; 2798 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType) 2799 : S.Context.getTypeAlign(FieldType); 2800 S.Diag(Field->getLocation(), 2801 diag::warn_transparent_union_attribute_field_size_align) 2802 << isSize << Field->getDeclName() << FieldBits; 2803 unsigned FirstBits = isSize? FirstSize : FirstAlign; 2804 S.Diag(FirstField->getLocation(), 2805 diag::note_transparent_union_first_field_size_align) 2806 << isSize << FirstBits; 2807 return; 2808 } 2809 } 2810 2811 RD->addAttr(::new (S.Context) 2812 TransparentUnionAttr(Attr.getRange(), S.Context, 2813 Attr.getAttributeSpellingListIndex())); 2814 } 2815 2816 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2817 // Make sure that there is a string literal as the annotation's single 2818 // argument. 2819 StringRef Str; 2820 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 2821 return; 2822 2823 // Don't duplicate annotations that are already set. 2824 for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 2825 if (I->getAnnotation() == Str) 2826 return; 2827 } 2828 2829 D->addAttr(::new (S.Context) 2830 AnnotateAttr(Attr.getRange(), S.Context, Str, 2831 Attr.getAttributeSpellingListIndex())); 2832 } 2833 2834 static void handleAlignValueAttr(Sema &S, Decl *D, 2835 const AttributeList &Attr) { 2836 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0), 2837 Attr.getAttributeSpellingListIndex()); 2838 } 2839 2840 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, 2841 unsigned SpellingListIndex) { 2842 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex); 2843 SourceLocation AttrLoc = AttrRange.getBegin(); 2844 2845 QualType T; 2846 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 2847 T = TD->getUnderlyingType(); 2848 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) 2849 T = VD->getType(); 2850 else 2851 llvm_unreachable("Unknown decl type for align_value"); 2852 2853 if (!T->isDependentType() && !T->isAnyPointerType() && 2854 !T->isReferenceType() && !T->isMemberPointerType()) { 2855 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only) 2856 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange(); 2857 return; 2858 } 2859 2860 if (!E->isValueDependent()) { 2861 llvm::APSInt Alignment(32); 2862 ExprResult ICE 2863 = VerifyIntegerConstantExpression(E, &Alignment, 2864 diag::err_align_value_attribute_argument_not_int, 2865 /*AllowFold*/ false); 2866 if (ICE.isInvalid()) 2867 return; 2868 2869 if (!Alignment.isPowerOf2()) { 2870 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 2871 << E->getSourceRange(); 2872 return; 2873 } 2874 2875 D->addAttr(::new (Context) 2876 AlignValueAttr(AttrRange, Context, ICE.get(), 2877 SpellingListIndex)); 2878 return; 2879 } 2880 2881 // Save dependent expressions in the AST to be instantiated. 2882 D->addAttr(::new (Context) AlignValueAttr(TmpAttr)); 2883 return; 2884 } 2885 2886 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2887 // check the attribute arguments. 2888 if (Attr.getNumArgs() > 1) { 2889 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 2890 << Attr.getName() << 1; 2891 return; 2892 } 2893 2894 if (Attr.getNumArgs() == 0) { 2895 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context, 2896 true, nullptr, Attr.getAttributeSpellingListIndex())); 2897 return; 2898 } 2899 2900 Expr *E = Attr.getArgAsExpr(0); 2901 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) { 2902 S.Diag(Attr.getEllipsisLoc(), 2903 diag::err_pack_expansion_without_parameter_packs); 2904 return; 2905 } 2906 2907 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E)) 2908 return; 2909 2910 if (E->isValueDependent()) { 2911 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) { 2912 if (!TND->getUnderlyingType()->isDependentType()) { 2913 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name) 2914 << E->getSourceRange(); 2915 return; 2916 } 2917 } 2918 } 2919 2920 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(), 2921 Attr.isPackExpansion()); 2922 } 2923 2924 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 2925 unsigned SpellingListIndex, bool IsPackExpansion) { 2926 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex); 2927 SourceLocation AttrLoc = AttrRange.getBegin(); 2928 2929 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements. 2930 if (TmpAttr.isAlignas()) { 2931 // C++11 [dcl.align]p1: 2932 // An alignment-specifier may be applied to a variable or to a class 2933 // data member, but it shall not be applied to a bit-field, a function 2934 // parameter, the formal parameter of a catch clause, or a variable 2935 // declared with the register storage class specifier. An 2936 // alignment-specifier may also be applied to the declaration of a class 2937 // or enumeration type. 2938 // C11 6.7.5/2: 2939 // An alignment attribute shall not be specified in a declaration of 2940 // a typedef, or a bit-field, or a function, or a parameter, or an 2941 // object declared with the register storage-class specifier. 2942 int DiagKind = -1; 2943 if (isa<ParmVarDecl>(D)) { 2944 DiagKind = 0; 2945 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2946 if (VD->getStorageClass() == SC_Register) 2947 DiagKind = 1; 2948 if (VD->isExceptionVariable()) 2949 DiagKind = 2; 2950 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 2951 if (FD->isBitField()) 2952 DiagKind = 3; 2953 } else if (!isa<TagDecl>(D)) { 2954 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr 2955 << (TmpAttr.isC11() ? ExpectedVariableOrField 2956 : ExpectedVariableFieldOrTag); 2957 return; 2958 } 2959 if (DiagKind != -1) { 2960 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type) 2961 << &TmpAttr << DiagKind; 2962 return; 2963 } 2964 } 2965 2966 if (E->isTypeDependent() || E->isValueDependent()) { 2967 // Save dependent expressions in the AST to be instantiated. 2968 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr); 2969 AA->setPackExpansion(IsPackExpansion); 2970 D->addAttr(AA); 2971 return; 2972 } 2973 2974 // FIXME: Cache the number on the Attr object? 2975 llvm::APSInt Alignment(32); 2976 ExprResult ICE 2977 = VerifyIntegerConstantExpression(E, &Alignment, 2978 diag::err_aligned_attribute_argument_not_int, 2979 /*AllowFold*/ false); 2980 if (ICE.isInvalid()) 2981 return; 2982 2983 // C++11 [dcl.align]p2: 2984 // -- if the constant expression evaluates to zero, the alignment 2985 // specifier shall have no effect 2986 // C11 6.7.5p6: 2987 // An alignment specification of zero has no effect. 2988 if (!(TmpAttr.isAlignas() && !Alignment) && 2989 !llvm::isPowerOf2_64(Alignment.getZExtValue())) { 2990 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 2991 << E->getSourceRange(); 2992 return; 2993 } 2994 2995 // Alignment calculations can wrap around if it's greater than 2**28. 2996 unsigned MaxValidAlignment = TmpAttr.isDeclspec() ? 8192 : 268435456; 2997 if (Alignment.getZExtValue() > MaxValidAlignment) { 2998 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment 2999 << E->getSourceRange(); 3000 return; 3001 } 3002 3003 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true, 3004 ICE.get(), SpellingListIndex); 3005 AA->setPackExpansion(IsPackExpansion); 3006 D->addAttr(AA); 3007 } 3008 3009 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS, 3010 unsigned SpellingListIndex, bool IsPackExpansion) { 3011 // FIXME: Cache the number on the Attr object if non-dependent? 3012 // FIXME: Perform checking of type validity 3013 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS, 3014 SpellingListIndex); 3015 AA->setPackExpansion(IsPackExpansion); 3016 D->addAttr(AA); 3017 } 3018 3019 void Sema::CheckAlignasUnderalignment(Decl *D) { 3020 assert(D->hasAttrs() && "no attributes on decl"); 3021 3022 QualType UnderlyingTy, DiagTy; 3023 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 3024 UnderlyingTy = DiagTy = VD->getType(); 3025 } else { 3026 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D)); 3027 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) 3028 UnderlyingTy = ED->getIntegerType(); 3029 } 3030 if (DiagTy->isDependentType() || DiagTy->isIncompleteType()) 3031 return; 3032 3033 // C++11 [dcl.align]p5, C11 6.7.5/4: 3034 // The combined effect of all alignment attributes in a declaration shall 3035 // not specify an alignment that is less strict than the alignment that 3036 // would otherwise be required for the entity being declared. 3037 AlignedAttr *AlignasAttr = nullptr; 3038 unsigned Align = 0; 3039 for (auto *I : D->specific_attrs<AlignedAttr>()) { 3040 if (I->isAlignmentDependent()) 3041 return; 3042 if (I->isAlignas()) 3043 AlignasAttr = I; 3044 Align = std::max(Align, I->getAlignment(Context)); 3045 } 3046 3047 if (AlignasAttr && Align) { 3048 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align); 3049 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy); 3050 if (NaturalAlign > RequestedAlign) 3051 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned) 3052 << DiagTy << (unsigned)NaturalAlign.getQuantity(); 3053 } 3054 } 3055 3056 bool Sema::checkMSInheritanceAttrOnDefinition( 3057 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 3058 MSInheritanceAttr::Spelling SemanticSpelling) { 3059 assert(RD->hasDefinition() && "RD has no definition!"); 3060 3061 // We may not have seen base specifiers or any virtual methods yet. We will 3062 // have to wait until the record is defined to catch any mismatches. 3063 if (!RD->getDefinition()->isCompleteDefinition()) 3064 return false; 3065 3066 // The unspecified model never matches what a definition could need. 3067 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance) 3068 return false; 3069 3070 if (BestCase) { 3071 if (RD->calculateInheritanceModel() == SemanticSpelling) 3072 return false; 3073 } else { 3074 if (RD->calculateInheritanceModel() <= SemanticSpelling) 3075 return false; 3076 } 3077 3078 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance) 3079 << 0 /*definition*/; 3080 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) 3081 << RD->getNameAsString(); 3082 return true; 3083 } 3084 3085 /// handleModeAttr - This attribute modifies the width of a decl with primitive 3086 /// type. 3087 /// 3088 /// Despite what would be logical, the mode attribute is a decl attribute, not a 3089 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be 3090 /// HImode, not an intermediate pointer. 3091 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3092 // This attribute isn't documented, but glibc uses it. It changes 3093 // the width of an int or unsigned int to the specified size. 3094 if (!Attr.isArgIdent(0)) { 3095 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() 3096 << AANT_ArgumentIdentifier; 3097 return; 3098 } 3099 3100 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident; 3101 StringRef Str = Name->getName(); 3102 3103 // Normalize the attribute name, __foo__ becomes foo. 3104 if (Str.startswith("__") && Str.endswith("__")) 3105 Str = Str.substr(2, Str.size() - 4); 3106 3107 unsigned DestWidth = 0; 3108 bool IntegerMode = true; 3109 bool ComplexMode = false; 3110 switch (Str.size()) { 3111 case 2: 3112 switch (Str[0]) { 3113 case 'Q': DestWidth = 8; break; 3114 case 'H': DestWidth = 16; break; 3115 case 'S': DestWidth = 32; break; 3116 case 'D': DestWidth = 64; break; 3117 case 'X': DestWidth = 96; break; 3118 case 'T': DestWidth = 128; break; 3119 } 3120 if (Str[1] == 'F') { 3121 IntegerMode = false; 3122 } else if (Str[1] == 'C') { 3123 IntegerMode = false; 3124 ComplexMode = true; 3125 } else if (Str[1] != 'I') { 3126 DestWidth = 0; 3127 } 3128 break; 3129 case 4: 3130 // FIXME: glibc uses 'word' to define register_t; this is narrower than a 3131 // pointer on PIC16 and other embedded platforms. 3132 if (Str == "word") 3133 DestWidth = S.Context.getTargetInfo().getPointerWidth(0); 3134 else if (Str == "byte") 3135 DestWidth = S.Context.getTargetInfo().getCharWidth(); 3136 break; 3137 case 7: 3138 if (Str == "pointer") 3139 DestWidth = S.Context.getTargetInfo().getPointerWidth(0); 3140 break; 3141 case 11: 3142 if (Str == "unwind_word") 3143 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth(); 3144 break; 3145 } 3146 3147 QualType OldTy; 3148 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 3149 OldTy = TD->getUnderlyingType(); 3150 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) 3151 OldTy = VD->getType(); 3152 else { 3153 S.Diag(D->getLocation(), diag::err_attr_wrong_decl) 3154 << Attr.getName() << Attr.getRange(); 3155 return; 3156 } 3157 3158 // Base type can also be a vector type (see PR17453). 3159 // Distinguish between base type and base element type. 3160 QualType OldElemTy = OldTy; 3161 if (const VectorType *VT = OldTy->getAs<VectorType>()) 3162 OldElemTy = VT->getElementType(); 3163 3164 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType()) 3165 S.Diag(Attr.getLoc(), diag::err_mode_not_primitive); 3166 else if (IntegerMode) { 3167 if (!OldElemTy->isIntegralOrEnumerationType()) 3168 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type); 3169 } else if (ComplexMode) { 3170 if (!OldElemTy->isComplexType()) 3171 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type); 3172 } else { 3173 if (!OldElemTy->isFloatingType()) 3174 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type); 3175 } 3176 3177 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t 3178 // and friends, at least with glibc. 3179 // FIXME: Make sure floating-point mappings are accurate 3180 // FIXME: Support XF and TF types 3181 if (!DestWidth) { 3182 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 0 /*Unknown*/ << Name; 3183 return; 3184 } 3185 3186 QualType NewElemTy; 3187 3188 if (IntegerMode) 3189 NewElemTy = S.Context.getIntTypeForBitwidth( 3190 DestWidth, OldElemTy->isSignedIntegerType()); 3191 else 3192 NewElemTy = S.Context.getRealTypeForBitwidth(DestWidth); 3193 3194 if (NewElemTy.isNull()) { 3195 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 1 /*Unsupported*/ << Name; 3196 return; 3197 } 3198 3199 if (ComplexMode) { 3200 NewElemTy = S.Context.getComplexType(NewElemTy); 3201 } 3202 3203 QualType NewTy = NewElemTy; 3204 if (const VectorType *OldVT = OldTy->getAs<VectorType>()) { 3205 // Complex machine mode does not support base vector types. 3206 if (ComplexMode) { 3207 S.Diag(Attr.getLoc(), diag::err_complex_mode_vector_type); 3208 return; 3209 } 3210 unsigned NumElements = S.Context.getTypeSize(OldElemTy) * 3211 OldVT->getNumElements() / 3212 S.Context.getTypeSize(NewElemTy); 3213 NewTy = 3214 S.Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind()); 3215 } 3216 3217 if (NewTy.isNull()) { 3218 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type); 3219 return; 3220 } 3221 3222 // Install the new type. 3223 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 3224 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy); 3225 else 3226 cast<ValueDecl>(D)->setType(NewTy); 3227 3228 D->addAttr(::new (S.Context) 3229 ModeAttr(Attr.getRange(), S.Context, Name, 3230 Attr.getAttributeSpellingListIndex())); 3231 } 3232 3233 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3234 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 3235 if (!VD->hasGlobalStorage()) 3236 S.Diag(Attr.getLoc(), 3237 diag::warn_attribute_requires_functions_or_static_globals) 3238 << Attr.getName(); 3239 } else if (!isFunctionOrMethod(D)) { 3240 S.Diag(Attr.getLoc(), 3241 diag::warn_attribute_requires_functions_or_static_globals) 3242 << Attr.getName(); 3243 return; 3244 } 3245 3246 D->addAttr(::new (S.Context) 3247 NoDebugAttr(Attr.getRange(), S.Context, 3248 Attr.getAttributeSpellingListIndex())); 3249 } 3250 3251 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range, 3252 IdentifierInfo *Ident, 3253 unsigned AttrSpellingListIndex) { 3254 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 3255 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident; 3256 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 3257 return nullptr; 3258 } 3259 3260 if (D->hasAttr<AlwaysInlineAttr>()) 3261 return nullptr; 3262 3263 return ::new (Context) AlwaysInlineAttr(Range, Context, 3264 AttrSpellingListIndex); 3265 } 3266 3267 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range, 3268 unsigned AttrSpellingListIndex) { 3269 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 3270 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'"; 3271 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 3272 return nullptr; 3273 } 3274 3275 if (D->hasAttr<MinSizeAttr>()) 3276 return nullptr; 3277 3278 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex); 3279 } 3280 3281 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range, 3282 unsigned AttrSpellingListIndex) { 3283 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) { 3284 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline; 3285 Diag(Range.getBegin(), diag::note_conflicting_attribute); 3286 D->dropAttr<AlwaysInlineAttr>(); 3287 } 3288 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) { 3289 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize; 3290 Diag(Range.getBegin(), diag::note_conflicting_attribute); 3291 D->dropAttr<MinSizeAttr>(); 3292 } 3293 3294 if (D->hasAttr<OptimizeNoneAttr>()) 3295 return nullptr; 3296 3297 return ::new (Context) OptimizeNoneAttr(Range, Context, 3298 AttrSpellingListIndex); 3299 } 3300 3301 static void handleAlwaysInlineAttr(Sema &S, Decl *D, 3302 const AttributeList &Attr) { 3303 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr( 3304 D, Attr.getRange(), Attr.getName(), 3305 Attr.getAttributeSpellingListIndex())) 3306 D->addAttr(Inline); 3307 } 3308 3309 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3310 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr( 3311 D, Attr.getRange(), Attr.getAttributeSpellingListIndex())) 3312 D->addAttr(MinSize); 3313 } 3314 3315 static void handleOptimizeNoneAttr(Sema &S, Decl *D, 3316 const AttributeList &Attr) { 3317 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr( 3318 D, Attr.getRange(), Attr.getAttributeSpellingListIndex())) 3319 D->addAttr(Optnone); 3320 } 3321 3322 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3323 FunctionDecl *FD = cast<FunctionDecl>(D); 3324 if (!FD->getReturnType()->isVoidType()) { 3325 SourceRange RTRange = FD->getReturnTypeSourceRange(); 3326 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return) 3327 << FD->getType() 3328 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 3329 : FixItHint()); 3330 return; 3331 } 3332 3333 D->addAttr(::new (S.Context) 3334 CUDAGlobalAttr(Attr.getRange(), S.Context, 3335 Attr.getAttributeSpellingListIndex())); 3336 } 3337 3338 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3339 FunctionDecl *Fn = cast<FunctionDecl>(D); 3340 if (!Fn->isInlineSpecified()) { 3341 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline); 3342 return; 3343 } 3344 3345 D->addAttr(::new (S.Context) 3346 GNUInlineAttr(Attr.getRange(), S.Context, 3347 Attr.getAttributeSpellingListIndex())); 3348 } 3349 3350 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3351 if (hasDeclarator(D)) return; 3352 3353 // Diagnostic is emitted elsewhere: here we store the (valid) Attr 3354 // in the Decl node for syntactic reasoning, e.g., pretty-printing. 3355 CallingConv CC; 3356 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr)) 3357 return; 3358 3359 if (!isa<ObjCMethodDecl>(D)) { 3360 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 3361 << Attr.getName() << ExpectedFunctionOrMethod; 3362 return; 3363 } 3364 3365 switch (Attr.getKind()) { 3366 case AttributeList::AT_FastCall: 3367 D->addAttr(::new (S.Context) 3368 FastCallAttr(Attr.getRange(), S.Context, 3369 Attr.getAttributeSpellingListIndex())); 3370 return; 3371 case AttributeList::AT_StdCall: 3372 D->addAttr(::new (S.Context) 3373 StdCallAttr(Attr.getRange(), S.Context, 3374 Attr.getAttributeSpellingListIndex())); 3375 return; 3376 case AttributeList::AT_ThisCall: 3377 D->addAttr(::new (S.Context) 3378 ThisCallAttr(Attr.getRange(), S.Context, 3379 Attr.getAttributeSpellingListIndex())); 3380 return; 3381 case AttributeList::AT_CDecl: 3382 D->addAttr(::new (S.Context) 3383 CDeclAttr(Attr.getRange(), S.Context, 3384 Attr.getAttributeSpellingListIndex())); 3385 return; 3386 case AttributeList::AT_Pascal: 3387 D->addAttr(::new (S.Context) 3388 PascalAttr(Attr.getRange(), S.Context, 3389 Attr.getAttributeSpellingListIndex())); 3390 return; 3391 case AttributeList::AT_VectorCall: 3392 D->addAttr(::new (S.Context) 3393 VectorCallAttr(Attr.getRange(), S.Context, 3394 Attr.getAttributeSpellingListIndex())); 3395 return; 3396 case AttributeList::AT_MSABI: 3397 D->addAttr(::new (S.Context) 3398 MSABIAttr(Attr.getRange(), S.Context, 3399 Attr.getAttributeSpellingListIndex())); 3400 return; 3401 case AttributeList::AT_SysVABI: 3402 D->addAttr(::new (S.Context) 3403 SysVABIAttr(Attr.getRange(), S.Context, 3404 Attr.getAttributeSpellingListIndex())); 3405 return; 3406 case AttributeList::AT_Pcs: { 3407 PcsAttr::PCSType PCS; 3408 switch (CC) { 3409 case CC_AAPCS: 3410 PCS = PcsAttr::AAPCS; 3411 break; 3412 case CC_AAPCS_VFP: 3413 PCS = PcsAttr::AAPCS_VFP; 3414 break; 3415 default: 3416 llvm_unreachable("unexpected calling convention in pcs attribute"); 3417 } 3418 3419 D->addAttr(::new (S.Context) 3420 PcsAttr(Attr.getRange(), S.Context, PCS, 3421 Attr.getAttributeSpellingListIndex())); 3422 return; 3423 } 3424 case AttributeList::AT_IntelOclBicc: 3425 D->addAttr(::new (S.Context) 3426 IntelOclBiccAttr(Attr.getRange(), S.Context, 3427 Attr.getAttributeSpellingListIndex())); 3428 return; 3429 3430 default: 3431 llvm_unreachable("unexpected attribute kind"); 3432 } 3433 } 3434 3435 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, 3436 const FunctionDecl *FD) { 3437 if (attr.isInvalid()) 3438 return true; 3439 3440 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0; 3441 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) { 3442 attr.setInvalid(); 3443 return true; 3444 } 3445 3446 // TODO: diagnose uses of these conventions on the wrong target. 3447 switch (attr.getKind()) { 3448 case AttributeList::AT_CDecl: CC = CC_C; break; 3449 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break; 3450 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break; 3451 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break; 3452 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break; 3453 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break; 3454 case AttributeList::AT_MSABI: 3455 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : 3456 CC_X86_64Win64; 3457 break; 3458 case AttributeList::AT_SysVABI: 3459 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV : 3460 CC_C; 3461 break; 3462 case AttributeList::AT_Pcs: { 3463 StringRef StrRef; 3464 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) { 3465 attr.setInvalid(); 3466 return true; 3467 } 3468 if (StrRef == "aapcs") { 3469 CC = CC_AAPCS; 3470 break; 3471 } else if (StrRef == "aapcs-vfp") { 3472 CC = CC_AAPCS_VFP; 3473 break; 3474 } 3475 3476 attr.setInvalid(); 3477 Diag(attr.getLoc(), diag::err_invalid_pcs); 3478 return true; 3479 } 3480 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break; 3481 default: llvm_unreachable("unexpected attribute kind"); 3482 } 3483 3484 const TargetInfo &TI = Context.getTargetInfo(); 3485 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC); 3486 if (A != TargetInfo::CCCR_OK) { 3487 if (A == TargetInfo::CCCR_Warning) 3488 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName(); 3489 3490 // This convention is not valid for the target. Use the default function or 3491 // method calling convention. 3492 TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown; 3493 if (FD) 3494 MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member : 3495 TargetInfo::CCMT_NonMember; 3496 CC = TI.getDefaultCallingConv(MT); 3497 } 3498 3499 return false; 3500 } 3501 3502 /// Checks a regparm attribute, returning true if it is ill-formed and 3503 /// otherwise setting numParams to the appropriate value. 3504 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) { 3505 if (Attr.isInvalid()) 3506 return true; 3507 3508 if (!checkAttributeNumArgs(*this, Attr, 1)) { 3509 Attr.setInvalid(); 3510 return true; 3511 } 3512 3513 uint32_t NP; 3514 Expr *NumParamsExpr = Attr.getArgAsExpr(0); 3515 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) { 3516 Attr.setInvalid(); 3517 return true; 3518 } 3519 3520 if (Context.getTargetInfo().getRegParmMax() == 0) { 3521 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform) 3522 << NumParamsExpr->getSourceRange(); 3523 Attr.setInvalid(); 3524 return true; 3525 } 3526 3527 numParams = NP; 3528 if (numParams > Context.getTargetInfo().getRegParmMax()) { 3529 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number) 3530 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange(); 3531 Attr.setInvalid(); 3532 return true; 3533 } 3534 3535 return false; 3536 } 3537 3538 // Checks whether an argument of launch_bounds attribute is acceptable 3539 // May output an error. 3540 static bool checkLaunchBoundsArgument(Sema &S, Expr *E, 3541 const CUDALaunchBoundsAttr &Attr, 3542 const unsigned Idx) { 3543 3544 if (S.DiagnoseUnexpandedParameterPack(E)) 3545 return false; 3546 3547 // Accept template arguments for now as they depend on something else. 3548 // We'll get to check them when they eventually get instantiated. 3549 if (E->isValueDependent()) 3550 return true; 3551 3552 llvm::APSInt I(64); 3553 if (!E->isIntegerConstantExpr(I, S.Context)) { 3554 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type) 3555 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange(); 3556 return false; 3557 } 3558 // Make sure we can fit it in 32 bits. 3559 if (!I.isIntN(32)) { 3560 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false) 3561 << 32 << /* Unsigned */ 1; 3562 return false; 3563 } 3564 if (I < 0) 3565 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative) 3566 << &Attr << Idx << E->getSourceRange(); 3567 3568 return true; 3569 } 3570 3571 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, 3572 Expr *MinBlocks, unsigned SpellingListIndex) { 3573 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks, 3574 SpellingListIndex); 3575 3576 if (!checkLaunchBoundsArgument(*this, MaxThreads, TmpAttr, 0)) 3577 return; 3578 3579 if (MinBlocks && !checkLaunchBoundsArgument(*this, MinBlocks, TmpAttr, 1)) 3580 return; 3581 3582 D->addAttr(::new (Context) CUDALaunchBoundsAttr( 3583 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex)); 3584 } 3585 3586 static void handleLaunchBoundsAttr(Sema &S, Decl *D, 3587 const AttributeList &Attr) { 3588 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) || 3589 !checkAttributeAtMostNumArgs(S, Attr, 2)) 3590 return; 3591 3592 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0), 3593 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr, 3594 Attr.getAttributeSpellingListIndex()); 3595 } 3596 3597 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D, 3598 const AttributeList &Attr) { 3599 if (!Attr.isArgIdent(0)) { 3600 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 3601 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier; 3602 return; 3603 } 3604 3605 if (!checkAttributeNumArgs(S, Attr, 3)) 3606 return; 3607 3608 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident; 3609 3610 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) { 3611 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type) 3612 << Attr.getName() << ExpectedFunctionOrMethod; 3613 return; 3614 } 3615 3616 uint64_t ArgumentIdx; 3617 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1), 3618 ArgumentIdx)) 3619 return; 3620 3621 uint64_t TypeTagIdx; 3622 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2), 3623 TypeTagIdx)) 3624 return; 3625 3626 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag"); 3627 if (IsPointer) { 3628 // Ensure that buffer has a pointer type. 3629 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx); 3630 if (!BufferTy->isPointerType()) { 3631 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only) 3632 << Attr.getName(); 3633 } 3634 } 3635 3636 D->addAttr(::new (S.Context) 3637 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind, 3638 ArgumentIdx, TypeTagIdx, IsPointer, 3639 Attr.getAttributeSpellingListIndex())); 3640 } 3641 3642 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D, 3643 const AttributeList &Attr) { 3644 if (!Attr.isArgIdent(0)) { 3645 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 3646 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 3647 return; 3648 } 3649 3650 if (!checkAttributeNumArgs(S, Attr, 1)) 3651 return; 3652 3653 if (!isa<VarDecl>(D)) { 3654 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type) 3655 << Attr.getName() << ExpectedVariable; 3656 return; 3657 } 3658 3659 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident; 3660 TypeSourceInfo *MatchingCTypeLoc = nullptr; 3661 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc); 3662 assert(MatchingCTypeLoc && "no type source info for attribute argument"); 3663 3664 D->addAttr(::new (S.Context) 3665 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind, 3666 MatchingCTypeLoc, 3667 Attr.getLayoutCompatible(), 3668 Attr.getMustBeNull(), 3669 Attr.getAttributeSpellingListIndex())); 3670 } 3671 3672 //===----------------------------------------------------------------------===// 3673 // Checker-specific attribute handlers. 3674 //===----------------------------------------------------------------------===// 3675 3676 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) { 3677 return type->isDependentType() || 3678 type->isObjCRetainableType(); 3679 } 3680 3681 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) { 3682 return type->isDependentType() || 3683 type->isObjCObjectPointerType() || 3684 S.Context.isObjCNSObjectType(type); 3685 } 3686 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) { 3687 return type->isDependentType() || 3688 type->isPointerType() || 3689 isValidSubjectOfNSAttribute(S, type); 3690 } 3691 3692 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3693 ParmVarDecl *param = cast<ParmVarDecl>(D); 3694 bool typeOK, cf; 3695 3696 if (Attr.getKind() == AttributeList::AT_NSConsumed) { 3697 typeOK = isValidSubjectOfNSAttribute(S, param->getType()); 3698 cf = false; 3699 } else { 3700 typeOK = isValidSubjectOfCFAttribute(S, param->getType()); 3701 cf = true; 3702 } 3703 3704 if (!typeOK) { 3705 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) 3706 << Attr.getRange() << Attr.getName() << cf; 3707 return; 3708 } 3709 3710 if (cf) 3711 param->addAttr(::new (S.Context) 3712 CFConsumedAttr(Attr.getRange(), S.Context, 3713 Attr.getAttributeSpellingListIndex())); 3714 else 3715 param->addAttr(::new (S.Context) 3716 NSConsumedAttr(Attr.getRange(), S.Context, 3717 Attr.getAttributeSpellingListIndex())); 3718 } 3719 3720 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D, 3721 const AttributeList &Attr) { 3722 3723 QualType returnType; 3724 3725 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 3726 returnType = MD->getReturnType(); 3727 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) && 3728 (Attr.getKind() == AttributeList::AT_NSReturnsRetained)) 3729 return; // ignore: was handled as a type attribute 3730 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) 3731 returnType = PD->getType(); 3732 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 3733 returnType = FD->getReturnType(); 3734 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) { 3735 returnType = Param->getType()->getPointeeType(); 3736 if (returnType.isNull()) { 3737 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) 3738 << Attr.getName() << /*pointer-to-CF*/2 3739 << Attr.getRange(); 3740 return; 3741 } 3742 } else { 3743 AttributeDeclKind ExpectedDeclKind; 3744 switch (Attr.getKind()) { 3745 default: llvm_unreachable("invalid ownership attribute"); 3746 case AttributeList::AT_NSReturnsRetained: 3747 case AttributeList::AT_NSReturnsAutoreleased: 3748 case AttributeList::AT_NSReturnsNotRetained: 3749 ExpectedDeclKind = ExpectedFunctionOrMethod; 3750 break; 3751 3752 case AttributeList::AT_CFReturnsRetained: 3753 case AttributeList::AT_CFReturnsNotRetained: 3754 ExpectedDeclKind = ExpectedFunctionMethodOrParameter; 3755 break; 3756 } 3757 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type) 3758 << Attr.getRange() << Attr.getName() << ExpectedDeclKind; 3759 return; 3760 } 3761 3762 bool typeOK; 3763 bool cf; 3764 switch (Attr.getKind()) { 3765 default: llvm_unreachable("invalid ownership attribute"); 3766 case AttributeList::AT_NSReturnsRetained: 3767 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType); 3768 cf = false; 3769 break; 3770 3771 case AttributeList::AT_NSReturnsAutoreleased: 3772 case AttributeList::AT_NSReturnsNotRetained: 3773 typeOK = isValidSubjectOfNSAttribute(S, returnType); 3774 cf = false; 3775 break; 3776 3777 case AttributeList::AT_CFReturnsRetained: 3778 case AttributeList::AT_CFReturnsNotRetained: 3779 typeOK = isValidSubjectOfCFAttribute(S, returnType); 3780 cf = true; 3781 break; 3782 } 3783 3784 if (!typeOK) { 3785 if (isa<ParmVarDecl>(D)) { 3786 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) 3787 << Attr.getName() << /*pointer-to-CF*/2 3788 << Attr.getRange(); 3789 } else { 3790 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type. 3791 enum : unsigned { 3792 Function, 3793 Method, 3794 Property 3795 } SubjectKind = Function; 3796 if (isa<ObjCMethodDecl>(D)) 3797 SubjectKind = Method; 3798 else if (isa<ObjCPropertyDecl>(D)) 3799 SubjectKind = Property; 3800 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) 3801 << Attr.getName() << SubjectKind << cf 3802 << Attr.getRange(); 3803 } 3804 return; 3805 } 3806 3807 switch (Attr.getKind()) { 3808 default: 3809 llvm_unreachable("invalid ownership attribute"); 3810 case AttributeList::AT_NSReturnsAutoreleased: 3811 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr( 3812 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3813 return; 3814 case AttributeList::AT_CFReturnsNotRetained: 3815 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr( 3816 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3817 return; 3818 case AttributeList::AT_NSReturnsNotRetained: 3819 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr( 3820 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3821 return; 3822 case AttributeList::AT_CFReturnsRetained: 3823 D->addAttr(::new (S.Context) CFReturnsRetainedAttr( 3824 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3825 return; 3826 case AttributeList::AT_NSReturnsRetained: 3827 D->addAttr(::new (S.Context) NSReturnsRetainedAttr( 3828 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3829 return; 3830 }; 3831 } 3832 3833 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D, 3834 const AttributeList &attr) { 3835 const int EP_ObjCMethod = 1; 3836 const int EP_ObjCProperty = 2; 3837 3838 SourceLocation loc = attr.getLoc(); 3839 QualType resultType; 3840 if (isa<ObjCMethodDecl>(D)) 3841 resultType = cast<ObjCMethodDecl>(D)->getReturnType(); 3842 else 3843 resultType = cast<ObjCPropertyDecl>(D)->getType(); 3844 3845 if (!resultType->isReferenceType() && 3846 (!resultType->isPointerType() || resultType->isObjCRetainableType())) { 3847 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) 3848 << SourceRange(loc) 3849 << attr.getName() 3850 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty) 3851 << /*non-retainable pointer*/ 2; 3852 3853 // Drop the attribute. 3854 return; 3855 } 3856 3857 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr( 3858 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex())); 3859 } 3860 3861 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D, 3862 const AttributeList &attr) { 3863 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D); 3864 3865 DeclContext *DC = method->getDeclContext(); 3866 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) { 3867 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) 3868 << attr.getName() << 0; 3869 S.Diag(PDecl->getLocation(), diag::note_protocol_decl); 3870 return; 3871 } 3872 if (method->getMethodFamily() == OMF_dealloc) { 3873 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) 3874 << attr.getName() << 1; 3875 return; 3876 } 3877 3878 method->addAttr(::new (S.Context) 3879 ObjCRequiresSuperAttr(attr.getRange(), S.Context, 3880 attr.getAttributeSpellingListIndex())); 3881 } 3882 3883 static void handleCFAuditedTransferAttr(Sema &S, Decl *D, 3884 const AttributeList &Attr) { 3885 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr)) 3886 return; 3887 3888 D->addAttr(::new (S.Context) 3889 CFAuditedTransferAttr(Attr.getRange(), S.Context, 3890 Attr.getAttributeSpellingListIndex())); 3891 } 3892 3893 static void handleCFUnknownTransferAttr(Sema &S, Decl *D, 3894 const AttributeList &Attr) { 3895 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr)) 3896 return; 3897 3898 D->addAttr(::new (S.Context) 3899 CFUnknownTransferAttr(Attr.getRange(), S.Context, 3900 Attr.getAttributeSpellingListIndex())); 3901 } 3902 3903 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D, 3904 const AttributeList &Attr) { 3905 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr; 3906 3907 if (!Parm) { 3908 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 3909 return; 3910 } 3911 3912 // Typedefs only allow objc_bridge(id) and have some additional checking. 3913 if (auto TD = dyn_cast<TypedefNameDecl>(D)) { 3914 if (!Parm->Ident->isStr("id")) { 3915 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id) 3916 << Attr.getName(); 3917 return; 3918 } 3919 3920 // Only allow 'cv void *'. 3921 QualType T = TD->getUnderlyingType(); 3922 if (!T->isVoidPointerType()) { 3923 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer); 3924 return; 3925 } 3926 } 3927 3928 D->addAttr(::new (S.Context) 3929 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident, 3930 Attr.getAttributeSpellingListIndex())); 3931 } 3932 3933 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D, 3934 const AttributeList &Attr) { 3935 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr; 3936 3937 if (!Parm) { 3938 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 3939 return; 3940 } 3941 3942 D->addAttr(::new (S.Context) 3943 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident, 3944 Attr.getAttributeSpellingListIndex())); 3945 } 3946 3947 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D, 3948 const AttributeList &Attr) { 3949 IdentifierInfo *RelatedClass = 3950 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr; 3951 if (!RelatedClass) { 3952 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 3953 return; 3954 } 3955 IdentifierInfo *ClassMethod = 3956 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr; 3957 IdentifierInfo *InstanceMethod = 3958 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr; 3959 D->addAttr(::new (S.Context) 3960 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass, 3961 ClassMethod, InstanceMethod, 3962 Attr.getAttributeSpellingListIndex())); 3963 } 3964 3965 static void handleObjCDesignatedInitializer(Sema &S, Decl *D, 3966 const AttributeList &Attr) { 3967 ObjCInterfaceDecl *IFace; 3968 if (ObjCCategoryDecl *CatDecl = 3969 dyn_cast<ObjCCategoryDecl>(D->getDeclContext())) 3970 IFace = CatDecl->getClassInterface(); 3971 else 3972 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext()); 3973 3974 if (!IFace) 3975 return; 3976 3977 IFace->setHasDesignatedInitializers(); 3978 D->addAttr(::new (S.Context) 3979 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context, 3980 Attr.getAttributeSpellingListIndex())); 3981 } 3982 3983 static void handleObjCRuntimeName(Sema &S, Decl *D, 3984 const AttributeList &Attr) { 3985 StringRef MetaDataName; 3986 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName)) 3987 return; 3988 D->addAttr(::new (S.Context) 3989 ObjCRuntimeNameAttr(Attr.getRange(), S.Context, 3990 MetaDataName, 3991 Attr.getAttributeSpellingListIndex())); 3992 } 3993 3994 // when a user wants to use objc_boxable with a union or struct 3995 // but she doesn't have access to the declaration (legacy/third-party code) 3996 // then she can 'enable' this feature via trick with a typedef 3997 // e.g.: 3998 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct; 3999 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) { 4000 bool notify = false; 4001 4002 RecordDecl *RD = dyn_cast<RecordDecl>(D); 4003 if (RD && RD->getDefinition()) { 4004 RD = RD->getDefinition(); 4005 notify = true; 4006 } 4007 4008 if (RD) { 4009 ObjCBoxableAttr *BoxableAttr = ::new (S.Context) 4010 ObjCBoxableAttr(Attr.getRange(), S.Context, 4011 Attr.getAttributeSpellingListIndex()); 4012 RD->addAttr(BoxableAttr); 4013 if (notify) { 4014 // we need to notify ASTReader/ASTWriter about 4015 // modification of existing declaration 4016 if (ASTMutationListener *L = S.getASTMutationListener()) 4017 L->AddedAttributeToRecord(BoxableAttr, RD); 4018 } 4019 } 4020 } 4021 4022 static void handleObjCOwnershipAttr(Sema &S, Decl *D, 4023 const AttributeList &Attr) { 4024 if (hasDeclarator(D)) return; 4025 4026 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type) 4027 << Attr.getRange() << Attr.getName() << ExpectedVariable; 4028 } 4029 4030 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D, 4031 const AttributeList &Attr) { 4032 ValueDecl *vd = cast<ValueDecl>(D); 4033 QualType type = vd->getType(); 4034 4035 if (!type->isDependentType() && 4036 !type->isObjCLifetimeType()) { 4037 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type) 4038 << type; 4039 return; 4040 } 4041 4042 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4043 4044 // If we have no lifetime yet, check the lifetime we're presumably 4045 // going to infer. 4046 if (lifetime == Qualifiers::OCL_None && !type->isDependentType()) 4047 lifetime = type->getObjCARCImplicitLifetime(); 4048 4049 switch (lifetime) { 4050 case Qualifiers::OCL_None: 4051 assert(type->isDependentType() && 4052 "didn't infer lifetime for non-dependent type?"); 4053 break; 4054 4055 case Qualifiers::OCL_Weak: // meaningful 4056 case Qualifiers::OCL_Strong: // meaningful 4057 break; 4058 4059 case Qualifiers::OCL_ExplicitNone: 4060 case Qualifiers::OCL_Autoreleasing: 4061 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless) 4062 << (lifetime == Qualifiers::OCL_Autoreleasing); 4063 break; 4064 } 4065 4066 D->addAttr(::new (S.Context) 4067 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context, 4068 Attr.getAttributeSpellingListIndex())); 4069 } 4070 4071 //===----------------------------------------------------------------------===// 4072 // Microsoft specific attribute handlers. 4073 //===----------------------------------------------------------------------===// 4074 4075 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4076 if (!S.LangOpts.CPlusPlus) { 4077 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 4078 << Attr.getName() << AttributeLangSupport::C; 4079 return; 4080 } 4081 4082 if (!isa<CXXRecordDecl>(D)) { 4083 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 4084 << Attr.getName() << ExpectedClass; 4085 return; 4086 } 4087 4088 StringRef StrRef; 4089 SourceLocation LiteralLoc; 4090 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc)) 4091 return; 4092 4093 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or 4094 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former. 4095 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}') 4096 StrRef = StrRef.drop_front().drop_back(); 4097 4098 // Validate GUID length. 4099 if (StrRef.size() != 36) { 4100 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 4101 return; 4102 } 4103 4104 for (unsigned i = 0; i < 36; ++i) { 4105 if (i == 8 || i == 13 || i == 18 || i == 23) { 4106 if (StrRef[i] != '-') { 4107 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 4108 return; 4109 } 4110 } else if (!isHexDigit(StrRef[i])) { 4111 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 4112 return; 4113 } 4114 } 4115 4116 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef, 4117 Attr.getAttributeSpellingListIndex())); 4118 } 4119 4120 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4121 if (!S.LangOpts.CPlusPlus) { 4122 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 4123 << Attr.getName() << AttributeLangSupport::C; 4124 return; 4125 } 4126 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr( 4127 D, Attr.getRange(), /*BestCase=*/true, 4128 Attr.getAttributeSpellingListIndex(), 4129 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling()); 4130 if (IA) 4131 D->addAttr(IA); 4132 } 4133 4134 static void handleDeclspecThreadAttr(Sema &S, Decl *D, 4135 const AttributeList &Attr) { 4136 VarDecl *VD = cast<VarDecl>(D); 4137 if (!S.Context.getTargetInfo().isTLSSupported()) { 4138 S.Diag(Attr.getLoc(), diag::err_thread_unsupported); 4139 return; 4140 } 4141 if (VD->getTSCSpec() != TSCS_unspecified) { 4142 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable); 4143 return; 4144 } 4145 if (VD->hasLocalStorage()) { 4146 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)"; 4147 return; 4148 } 4149 VD->addAttr(::new (S.Context) ThreadAttr( 4150 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4151 } 4152 4153 static void handleARMInterruptAttr(Sema &S, Decl *D, 4154 const AttributeList &Attr) { 4155 // Check the attribute arguments. 4156 if (Attr.getNumArgs() > 1) { 4157 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) 4158 << Attr.getName() << 1; 4159 return; 4160 } 4161 4162 StringRef Str; 4163 SourceLocation ArgLoc; 4164 4165 if (Attr.getNumArgs() == 0) 4166 Str = ""; 4167 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc)) 4168 return; 4169 4170 ARMInterruptAttr::InterruptType Kind; 4171 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 4172 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 4173 << Attr.getName() << Str << ArgLoc; 4174 return; 4175 } 4176 4177 unsigned Index = Attr.getAttributeSpellingListIndex(); 4178 D->addAttr(::new (S.Context) 4179 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index)); 4180 } 4181 4182 static void handleMSP430InterruptAttr(Sema &S, Decl *D, 4183 const AttributeList &Attr) { 4184 if (!checkAttributeNumArgs(S, Attr, 1)) 4185 return; 4186 4187 if (!Attr.isArgExpr(0)) { 4188 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() 4189 << AANT_ArgumentIntegerConstant; 4190 return; 4191 } 4192 4193 // FIXME: Check for decl - it should be void ()(void). 4194 4195 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4196 llvm::APSInt NumParams(32); 4197 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) { 4198 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 4199 << Attr.getName() << AANT_ArgumentIntegerConstant 4200 << NumParamsExpr->getSourceRange(); 4201 return; 4202 } 4203 4204 unsigned Num = NumParams.getLimitedValue(255); 4205 if ((Num & 1) || Num > 30) { 4206 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 4207 << Attr.getName() << (int)NumParams.getSExtValue() 4208 << NumParamsExpr->getSourceRange(); 4209 return; 4210 } 4211 4212 D->addAttr(::new (S.Context) 4213 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num, 4214 Attr.getAttributeSpellingListIndex())); 4215 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 4216 } 4217 4218 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4219 // Dispatch the interrupt attribute based on the current target. 4220 if (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::msp430) 4221 handleMSP430InterruptAttr(S, D, Attr); 4222 else 4223 handleARMInterruptAttr(S, D, Attr); 4224 } 4225 4226 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, 4227 const AttributeList &Attr) { 4228 uint32_t NumRegs; 4229 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4230 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs)) 4231 return; 4232 4233 D->addAttr(::new (S.Context) 4234 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, 4235 NumRegs, 4236 Attr.getAttributeSpellingListIndex())); 4237 } 4238 4239 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, 4240 const AttributeList &Attr) { 4241 uint32_t NumRegs; 4242 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4243 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs)) 4244 return; 4245 4246 D->addAttr(::new (S.Context) 4247 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, 4248 NumRegs, 4249 Attr.getAttributeSpellingListIndex())); 4250 } 4251 4252 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D, 4253 const AttributeList& Attr) { 4254 // If we try to apply it to a function pointer, don't warn, but don't 4255 // do anything, either. It doesn't matter anyway, because there's nothing 4256 // special about calling a force_align_arg_pointer function. 4257 ValueDecl *VD = dyn_cast<ValueDecl>(D); 4258 if (VD && VD->getType()->isFunctionPointerType()) 4259 return; 4260 // Also don't warn on function pointer typedefs. 4261 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D); 4262 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() || 4263 TD->getUnderlyingType()->isFunctionType())) 4264 return; 4265 // Attribute can only be applied to function types. 4266 if (!isa<FunctionDecl>(D)) { 4267 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 4268 << Attr.getName() << /* function */0; 4269 return; 4270 } 4271 4272 D->addAttr(::new (S.Context) 4273 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context, 4274 Attr.getAttributeSpellingListIndex())); 4275 } 4276 4277 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range, 4278 unsigned AttrSpellingListIndex) { 4279 if (D->hasAttr<DLLExportAttr>()) { 4280 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'"; 4281 return nullptr; 4282 } 4283 4284 if (D->hasAttr<DLLImportAttr>()) 4285 return nullptr; 4286 4287 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex); 4288 } 4289 4290 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range, 4291 unsigned AttrSpellingListIndex) { 4292 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) { 4293 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import; 4294 D->dropAttr<DLLImportAttr>(); 4295 } 4296 4297 if (D->hasAttr<DLLExportAttr>()) 4298 return nullptr; 4299 4300 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex); 4301 } 4302 4303 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) { 4304 if (isa<ClassTemplatePartialSpecializationDecl>(D) && 4305 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4306 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) 4307 << A.getName(); 4308 return; 4309 } 4310 4311 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 4312 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport && 4313 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4314 // MinGW doesn't allow dllimport on inline functions. 4315 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline) 4316 << A.getName(); 4317 return; 4318 } 4319 } 4320 4321 unsigned Index = A.getAttributeSpellingListIndex(); 4322 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport 4323 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index) 4324 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index); 4325 if (NewAttr) 4326 D->addAttr(NewAttr); 4327 } 4328 4329 MSInheritanceAttr * 4330 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, 4331 unsigned AttrSpellingListIndex, 4332 MSInheritanceAttr::Spelling SemanticSpelling) { 4333 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) { 4334 if (IA->getSemanticSpelling() == SemanticSpelling) 4335 return nullptr; 4336 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance) 4337 << 1 /*previous declaration*/; 4338 Diag(Range.getBegin(), diag::note_previous_ms_inheritance); 4339 D->dropAttr<MSInheritanceAttr>(); 4340 } 4341 4342 CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 4343 if (RD->hasDefinition()) { 4344 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase, 4345 SemanticSpelling)) { 4346 return nullptr; 4347 } 4348 } else { 4349 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) { 4350 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) 4351 << 1 /*partial specialization*/; 4352 return nullptr; 4353 } 4354 if (RD->getDescribedClassTemplate()) { 4355 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) 4356 << 0 /*primary template*/; 4357 return nullptr; 4358 } 4359 } 4360 4361 return ::new (Context) 4362 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex); 4363 } 4364 4365 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4366 // The capability attributes take a single string parameter for the name of 4367 // the capability they represent. The lockable attribute does not take any 4368 // parameters. However, semantically, both attributes represent the same 4369 // concept, and so they use the same semantic attribute. Eventually, the 4370 // lockable attribute will be removed. 4371 // 4372 // For backward compatibility, any capability which has no specified string 4373 // literal will be considered a "mutex." 4374 StringRef N("mutex"); 4375 SourceLocation LiteralLoc; 4376 if (Attr.getKind() == AttributeList::AT_Capability && 4377 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc)) 4378 return; 4379 4380 // Currently, there are only two names allowed for a capability: role and 4381 // mutex (case insensitive). Diagnose other capability names. 4382 if (!N.equals_lower("mutex") && !N.equals_lower("role")) 4383 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N; 4384 4385 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N, 4386 Attr.getAttributeSpellingListIndex())); 4387 } 4388 4389 static void handleAssertCapabilityAttr(Sema &S, Decl *D, 4390 const AttributeList &Attr) { 4391 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context, 4392 Attr.getArgAsExpr(0), 4393 Attr.getAttributeSpellingListIndex())); 4394 } 4395 4396 static void handleAcquireCapabilityAttr(Sema &S, Decl *D, 4397 const AttributeList &Attr) { 4398 SmallVector<Expr*, 1> Args; 4399 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 4400 return; 4401 4402 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(), 4403 S.Context, 4404 Args.data(), Args.size(), 4405 Attr.getAttributeSpellingListIndex())); 4406 } 4407 4408 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D, 4409 const AttributeList &Attr) { 4410 SmallVector<Expr*, 2> Args; 4411 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 4412 return; 4413 4414 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(), 4415 S.Context, 4416 Attr.getArgAsExpr(0), 4417 Args.data(), 4418 Args.size(), 4419 Attr.getAttributeSpellingListIndex())); 4420 } 4421 4422 static void handleReleaseCapabilityAttr(Sema &S, Decl *D, 4423 const AttributeList &Attr) { 4424 // Check that all arguments are lockable objects. 4425 SmallVector<Expr *, 1> Args; 4426 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true); 4427 4428 D->addAttr(::new (S.Context) ReleaseCapabilityAttr( 4429 Attr.getRange(), S.Context, Args.data(), Args.size(), 4430 Attr.getAttributeSpellingListIndex())); 4431 } 4432 4433 static void handleRequiresCapabilityAttr(Sema &S, Decl *D, 4434 const AttributeList &Attr) { 4435 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 4436 return; 4437 4438 // check that all arguments are lockable objects 4439 SmallVector<Expr*, 1> Args; 4440 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 4441 if (Args.empty()) 4442 return; 4443 4444 RequiresCapabilityAttr *RCA = ::new (S.Context) 4445 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(), 4446 Args.size(), Attr.getAttributeSpellingListIndex()); 4447 4448 D->addAttr(RCA); 4449 } 4450 4451 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4452 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) { 4453 if (NSD->isAnonymousNamespace()) { 4454 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace); 4455 // Do not want to attach the attribute to the namespace because that will 4456 // cause confusing diagnostic reports for uses of declarations within the 4457 // namespace. 4458 return; 4459 } 4460 } 4461 4462 if (!S.getLangOpts().CPlusPlus14) 4463 if (Attr.isCXX11Attribute() && 4464 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu"))) 4465 S.Diag(Attr.getLoc(), diag::ext_deprecated_attr_is_a_cxx14_extension); 4466 4467 handleAttrWithMessage<DeprecatedAttr>(S, D, Attr); 4468 } 4469 4470 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4471 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 4472 return; 4473 4474 std::vector<std::string> Sanitizers; 4475 4476 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) { 4477 StringRef SanitizerName; 4478 SourceLocation LiteralLoc; 4479 4480 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc)) 4481 return; 4482 4483 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0) 4484 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName; 4485 4486 Sanitizers.push_back(SanitizerName); 4487 } 4488 4489 D->addAttr(::new (S.Context) NoSanitizeAttr( 4490 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(), 4491 Attr.getAttributeSpellingListIndex())); 4492 } 4493 4494 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D, 4495 const AttributeList &Attr) { 4496 std::string SanitizerName = 4497 llvm::StringSwitch<std::string>(Attr.getName()->getName()) 4498 .Case("no_address_safety_analysis", "address") 4499 .Case("no_sanitize_address", "address") 4500 .Case("no_sanitize_thread", "thread") 4501 .Case("no_sanitize_memory", "memory"); 4502 D->addAttr(::new (S.Context) 4503 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1, 4504 Attr.getAttributeSpellingListIndex())); 4505 } 4506 4507 /// Handles semantic checking for features that are common to all attributes, 4508 /// such as checking whether a parameter was properly specified, or the correct 4509 /// number of arguments were passed, etc. 4510 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D, 4511 const AttributeList &Attr) { 4512 // Several attributes carry different semantics than the parsing requires, so 4513 // those are opted out of the common handling. 4514 // 4515 // We also bail on unknown and ignored attributes because those are handled 4516 // as part of the target-specific handling logic. 4517 if (Attr.hasCustomParsing() || 4518 Attr.getKind() == AttributeList::UnknownAttribute) 4519 return false; 4520 4521 // Check whether the attribute requires specific language extensions to be 4522 // enabled. 4523 if (!Attr.diagnoseLangOpts(S)) 4524 return true; 4525 4526 if (Attr.getMinArgs() == Attr.getMaxArgs()) { 4527 // If there are no optional arguments, then checking for the argument count 4528 // is trivial. 4529 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs())) 4530 return true; 4531 } else { 4532 // There are optional arguments, so checking is slightly more involved. 4533 if (Attr.getMinArgs() && 4534 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs())) 4535 return true; 4536 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() && 4537 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs())) 4538 return true; 4539 } 4540 4541 // Check whether the attribute appertains to the given subject. 4542 if (!Attr.diagnoseAppertainsTo(S, D)) 4543 return true; 4544 4545 return false; 4546 } 4547 4548 //===----------------------------------------------------------------------===// 4549 // Top Level Sema Entry Points 4550 //===----------------------------------------------------------------------===// 4551 4552 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if 4553 /// the attribute applies to decls. If the attribute is a type attribute, just 4554 /// silently ignore it if a GNU attribute. 4555 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, 4556 const AttributeList &Attr, 4557 bool IncludeCXX11Attributes) { 4558 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute) 4559 return; 4560 4561 // Ignore C++11 attributes on declarator chunks: they appertain to the type 4562 // instead. 4563 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes) 4564 return; 4565 4566 // Unknown attributes are automatically warned on. Target-specific attributes 4567 // which do not apply to the current target architecture are treated as 4568 // though they were unknown attributes. 4569 if (Attr.getKind() == AttributeList::UnknownAttribute || 4570 !Attr.existsInTarget(S.Context.getTargetInfo().getTriple())) { 4571 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute() 4572 ? diag::warn_unhandled_ms_attribute_ignored 4573 : diag::warn_unknown_attribute_ignored) 4574 << Attr.getName(); 4575 return; 4576 } 4577 4578 if (handleCommonAttributeFeatures(S, scope, D, Attr)) 4579 return; 4580 4581 switch (Attr.getKind()) { 4582 default: 4583 // Type attributes are handled elsewhere; silently move on. 4584 assert(Attr.isTypeAttr() && "Non-type attribute not handled"); 4585 break; 4586 case AttributeList::AT_Interrupt: 4587 handleInterruptAttr(S, D, Attr); 4588 break; 4589 case AttributeList::AT_X86ForceAlignArgPointer: 4590 handleX86ForceAlignArgPointerAttr(S, D, Attr); 4591 break; 4592 case AttributeList::AT_DLLExport: 4593 case AttributeList::AT_DLLImport: 4594 handleDLLAttr(S, D, Attr); 4595 break; 4596 case AttributeList::AT_Mips16: 4597 handleSimpleAttribute<Mips16Attr>(S, D, Attr); 4598 break; 4599 case AttributeList::AT_NoMips16: 4600 handleSimpleAttribute<NoMips16Attr>(S, D, Attr); 4601 break; 4602 case AttributeList::AT_AMDGPUNumVGPR: 4603 handleAMDGPUNumVGPRAttr(S, D, Attr); 4604 break; 4605 case AttributeList::AT_AMDGPUNumSGPR: 4606 handleAMDGPUNumSGPRAttr(S, D, Attr); 4607 break; 4608 case AttributeList::AT_IBAction: 4609 handleSimpleAttribute<IBActionAttr>(S, D, Attr); 4610 break; 4611 case AttributeList::AT_IBOutlet: 4612 handleIBOutlet(S, D, Attr); 4613 break; 4614 case AttributeList::AT_IBOutletCollection: 4615 handleIBOutletCollection(S, D, Attr); 4616 break; 4617 case AttributeList::AT_Alias: 4618 handleAliasAttr(S, D, Attr); 4619 break; 4620 case AttributeList::AT_Aligned: 4621 handleAlignedAttr(S, D, Attr); 4622 break; 4623 case AttributeList::AT_AlignValue: 4624 handleAlignValueAttr(S, D, Attr); 4625 break; 4626 case AttributeList::AT_AlwaysInline: 4627 handleAlwaysInlineAttr(S, D, Attr); 4628 break; 4629 case AttributeList::AT_AnalyzerNoReturn: 4630 handleAnalyzerNoReturnAttr(S, D, Attr); 4631 break; 4632 case AttributeList::AT_TLSModel: 4633 handleTLSModelAttr(S, D, Attr); 4634 break; 4635 case AttributeList::AT_Annotate: 4636 handleAnnotateAttr(S, D, Attr); 4637 break; 4638 case AttributeList::AT_Availability: 4639 handleAvailabilityAttr(S, D, Attr); 4640 break; 4641 case AttributeList::AT_CarriesDependency: 4642 handleDependencyAttr(S, scope, D, Attr); 4643 break; 4644 case AttributeList::AT_Common: 4645 handleCommonAttr(S, D, Attr); 4646 break; 4647 case AttributeList::AT_CUDAConstant: 4648 handleSimpleAttribute<CUDAConstantAttr>(S, D, Attr); 4649 break; 4650 case AttributeList::AT_Constructor: 4651 handleConstructorAttr(S, D, Attr); 4652 break; 4653 case AttributeList::AT_CXX11NoReturn: 4654 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr); 4655 break; 4656 case AttributeList::AT_Deprecated: 4657 handleDeprecatedAttr(S, D, Attr); 4658 break; 4659 case AttributeList::AT_Destructor: 4660 handleDestructorAttr(S, D, Attr); 4661 break; 4662 case AttributeList::AT_EnableIf: 4663 handleEnableIfAttr(S, D, Attr); 4664 break; 4665 case AttributeList::AT_ExtVectorType: 4666 handleExtVectorTypeAttr(S, scope, D, Attr); 4667 break; 4668 case AttributeList::AT_MinSize: 4669 handleMinSizeAttr(S, D, Attr); 4670 break; 4671 case AttributeList::AT_OptimizeNone: 4672 handleOptimizeNoneAttr(S, D, Attr); 4673 break; 4674 case AttributeList::AT_FlagEnum: 4675 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr); 4676 break; 4677 case AttributeList::AT_Flatten: 4678 handleSimpleAttribute<FlattenAttr>(S, D, Attr); 4679 break; 4680 case AttributeList::AT_Format: 4681 handleFormatAttr(S, D, Attr); 4682 break; 4683 case AttributeList::AT_FormatArg: 4684 handleFormatArgAttr(S, D, Attr); 4685 break; 4686 case AttributeList::AT_CUDAGlobal: 4687 handleGlobalAttr(S, D, Attr); 4688 break; 4689 case AttributeList::AT_CUDADevice: 4690 handleSimpleAttribute<CUDADeviceAttr>(S, D, Attr); 4691 break; 4692 case AttributeList::AT_CUDAHost: 4693 handleSimpleAttribute<CUDAHostAttr>(S, D, Attr); 4694 break; 4695 case AttributeList::AT_GNUInline: 4696 handleGNUInlineAttr(S, D, Attr); 4697 break; 4698 case AttributeList::AT_CUDALaunchBounds: 4699 handleLaunchBoundsAttr(S, D, Attr); 4700 break; 4701 case AttributeList::AT_Restrict: 4702 handleRestrictAttr(S, D, Attr); 4703 break; 4704 case AttributeList::AT_MayAlias: 4705 handleSimpleAttribute<MayAliasAttr>(S, D, Attr); 4706 break; 4707 case AttributeList::AT_Mode: 4708 handleModeAttr(S, D, Attr); 4709 break; 4710 case AttributeList::AT_NoCommon: 4711 handleSimpleAttribute<NoCommonAttr>(S, D, Attr); 4712 break; 4713 case AttributeList::AT_NoSplitStack: 4714 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr); 4715 break; 4716 case AttributeList::AT_NonNull: 4717 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D)) 4718 handleNonNullAttrParameter(S, PVD, Attr); 4719 else 4720 handleNonNullAttr(S, D, Attr); 4721 break; 4722 case AttributeList::AT_ReturnsNonNull: 4723 handleReturnsNonNullAttr(S, D, Attr); 4724 break; 4725 case AttributeList::AT_AssumeAligned: 4726 handleAssumeAlignedAttr(S, D, Attr); 4727 break; 4728 case AttributeList::AT_Overloadable: 4729 handleSimpleAttribute<OverloadableAttr>(S, D, Attr); 4730 break; 4731 case AttributeList::AT_Ownership: 4732 handleOwnershipAttr(S, D, Attr); 4733 break; 4734 case AttributeList::AT_Cold: 4735 handleColdAttr(S, D, Attr); 4736 break; 4737 case AttributeList::AT_Hot: 4738 handleHotAttr(S, D, Attr); 4739 break; 4740 case AttributeList::AT_Naked: 4741 handleSimpleAttribute<NakedAttr>(S, D, Attr); 4742 break; 4743 case AttributeList::AT_NoReturn: 4744 handleNoReturnAttr(S, D, Attr); 4745 break; 4746 case AttributeList::AT_NoThrow: 4747 handleSimpleAttribute<NoThrowAttr>(S, D, Attr); 4748 break; 4749 case AttributeList::AT_CUDAShared: 4750 handleSimpleAttribute<CUDASharedAttr>(S, D, Attr); 4751 break; 4752 case AttributeList::AT_VecReturn: 4753 handleVecReturnAttr(S, D, Attr); 4754 break; 4755 4756 case AttributeList::AT_ObjCOwnership: 4757 handleObjCOwnershipAttr(S, D, Attr); 4758 break; 4759 case AttributeList::AT_ObjCPreciseLifetime: 4760 handleObjCPreciseLifetimeAttr(S, D, Attr); 4761 break; 4762 4763 case AttributeList::AT_ObjCReturnsInnerPointer: 4764 handleObjCReturnsInnerPointerAttr(S, D, Attr); 4765 break; 4766 4767 case AttributeList::AT_ObjCRequiresSuper: 4768 handleObjCRequiresSuperAttr(S, D, Attr); 4769 break; 4770 4771 case AttributeList::AT_ObjCBridge: 4772 handleObjCBridgeAttr(S, scope, D, Attr); 4773 break; 4774 4775 case AttributeList::AT_ObjCBridgeMutable: 4776 handleObjCBridgeMutableAttr(S, scope, D, Attr); 4777 break; 4778 4779 case AttributeList::AT_ObjCBridgeRelated: 4780 handleObjCBridgeRelatedAttr(S, scope, D, Attr); 4781 break; 4782 4783 case AttributeList::AT_ObjCDesignatedInitializer: 4784 handleObjCDesignatedInitializer(S, D, Attr); 4785 break; 4786 4787 case AttributeList::AT_ObjCRuntimeName: 4788 handleObjCRuntimeName(S, D, Attr); 4789 break; 4790 4791 case AttributeList::AT_ObjCBoxable: 4792 handleObjCBoxable(S, D, Attr); 4793 break; 4794 4795 case AttributeList::AT_CFAuditedTransfer: 4796 handleCFAuditedTransferAttr(S, D, Attr); 4797 break; 4798 case AttributeList::AT_CFUnknownTransfer: 4799 handleCFUnknownTransferAttr(S, D, Attr); 4800 break; 4801 4802 case AttributeList::AT_CFConsumed: 4803 case AttributeList::AT_NSConsumed: 4804 handleNSConsumedAttr(S, D, Attr); 4805 break; 4806 case AttributeList::AT_NSConsumesSelf: 4807 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr); 4808 break; 4809 4810 case AttributeList::AT_NSReturnsAutoreleased: 4811 case AttributeList::AT_NSReturnsNotRetained: 4812 case AttributeList::AT_CFReturnsNotRetained: 4813 case AttributeList::AT_NSReturnsRetained: 4814 case AttributeList::AT_CFReturnsRetained: 4815 handleNSReturnsRetainedAttr(S, D, Attr); 4816 break; 4817 case AttributeList::AT_WorkGroupSizeHint: 4818 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr); 4819 break; 4820 case AttributeList::AT_ReqdWorkGroupSize: 4821 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr); 4822 break; 4823 case AttributeList::AT_VecTypeHint: 4824 handleVecTypeHint(S, D, Attr); 4825 break; 4826 4827 case AttributeList::AT_InitPriority: 4828 handleInitPriorityAttr(S, D, Attr); 4829 break; 4830 4831 case AttributeList::AT_Packed: 4832 handlePackedAttr(S, D, Attr); 4833 break; 4834 case AttributeList::AT_Section: 4835 handleSectionAttr(S, D, Attr); 4836 break; 4837 case AttributeList::AT_Target: 4838 handleTargetAttr(S, D, Attr); 4839 break; 4840 case AttributeList::AT_Unavailable: 4841 handleAttrWithMessage<UnavailableAttr>(S, D, Attr); 4842 break; 4843 case AttributeList::AT_ArcWeakrefUnavailable: 4844 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr); 4845 break; 4846 case AttributeList::AT_ObjCRootClass: 4847 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr); 4848 break; 4849 case AttributeList::AT_ObjCExplicitProtocolImpl: 4850 handleObjCSuppresProtocolAttr(S, D, Attr); 4851 break; 4852 case AttributeList::AT_ObjCRequiresPropertyDefs: 4853 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr); 4854 break; 4855 case AttributeList::AT_Unused: 4856 handleSimpleAttribute<UnusedAttr>(S, D, Attr); 4857 break; 4858 case AttributeList::AT_ReturnsTwice: 4859 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr); 4860 break; 4861 case AttributeList::AT_Used: 4862 handleUsedAttr(S, D, Attr); 4863 break; 4864 case AttributeList::AT_Visibility: 4865 handleVisibilityAttr(S, D, Attr, false); 4866 break; 4867 case AttributeList::AT_TypeVisibility: 4868 handleVisibilityAttr(S, D, Attr, true); 4869 break; 4870 case AttributeList::AT_WarnUnused: 4871 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr); 4872 break; 4873 case AttributeList::AT_WarnUnusedResult: 4874 handleWarnUnusedResult(S, D, Attr); 4875 break; 4876 case AttributeList::AT_Weak: 4877 handleSimpleAttribute<WeakAttr>(S, D, Attr); 4878 break; 4879 case AttributeList::AT_WeakRef: 4880 handleWeakRefAttr(S, D, Attr); 4881 break; 4882 case AttributeList::AT_WeakImport: 4883 handleWeakImportAttr(S, D, Attr); 4884 break; 4885 case AttributeList::AT_TransparentUnion: 4886 handleTransparentUnionAttr(S, D, Attr); 4887 break; 4888 case AttributeList::AT_ObjCException: 4889 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr); 4890 break; 4891 case AttributeList::AT_ObjCMethodFamily: 4892 handleObjCMethodFamilyAttr(S, D, Attr); 4893 break; 4894 case AttributeList::AT_ObjCNSObject: 4895 handleObjCNSObject(S, D, Attr); 4896 break; 4897 case AttributeList::AT_ObjCIndependentClass: 4898 handleObjCIndependentClass(S, D, Attr); 4899 break; 4900 case AttributeList::AT_Blocks: 4901 handleBlocksAttr(S, D, Attr); 4902 break; 4903 case AttributeList::AT_Sentinel: 4904 handleSentinelAttr(S, D, Attr); 4905 break; 4906 case AttributeList::AT_Const: 4907 handleSimpleAttribute<ConstAttr>(S, D, Attr); 4908 break; 4909 case AttributeList::AT_Pure: 4910 handleSimpleAttribute<PureAttr>(S, D, Attr); 4911 break; 4912 case AttributeList::AT_Cleanup: 4913 handleCleanupAttr(S, D, Attr); 4914 break; 4915 case AttributeList::AT_NoDebug: 4916 handleNoDebugAttr(S, D, Attr); 4917 break; 4918 case AttributeList::AT_NoDuplicate: 4919 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr); 4920 break; 4921 case AttributeList::AT_NoInline: 4922 handleSimpleAttribute<NoInlineAttr>(S, D, Attr); 4923 break; 4924 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg. 4925 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr); 4926 break; 4927 case AttributeList::AT_StdCall: 4928 case AttributeList::AT_CDecl: 4929 case AttributeList::AT_FastCall: 4930 case AttributeList::AT_ThisCall: 4931 case AttributeList::AT_Pascal: 4932 case AttributeList::AT_VectorCall: 4933 case AttributeList::AT_MSABI: 4934 case AttributeList::AT_SysVABI: 4935 case AttributeList::AT_Pcs: 4936 case AttributeList::AT_IntelOclBicc: 4937 handleCallConvAttr(S, D, Attr); 4938 break; 4939 case AttributeList::AT_OpenCLKernel: 4940 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr); 4941 break; 4942 case AttributeList::AT_OpenCLImageAccess: 4943 handleSimpleAttribute<OpenCLImageAccessAttr>(S, D, Attr); 4944 break; 4945 4946 // Microsoft attributes: 4947 case AttributeList::AT_MSNoVTable: 4948 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr); 4949 break; 4950 case AttributeList::AT_MSStruct: 4951 handleSimpleAttribute<MSStructAttr>(S, D, Attr); 4952 break; 4953 case AttributeList::AT_Uuid: 4954 handleUuidAttr(S, D, Attr); 4955 break; 4956 case AttributeList::AT_MSInheritance: 4957 handleMSInheritanceAttr(S, D, Attr); 4958 break; 4959 case AttributeList::AT_SelectAny: 4960 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr); 4961 break; 4962 case AttributeList::AT_Thread: 4963 handleDeclspecThreadAttr(S, D, Attr); 4964 break; 4965 4966 // Thread safety attributes: 4967 case AttributeList::AT_AssertExclusiveLock: 4968 handleAssertExclusiveLockAttr(S, D, Attr); 4969 break; 4970 case AttributeList::AT_AssertSharedLock: 4971 handleAssertSharedLockAttr(S, D, Attr); 4972 break; 4973 case AttributeList::AT_GuardedVar: 4974 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr); 4975 break; 4976 case AttributeList::AT_PtGuardedVar: 4977 handlePtGuardedVarAttr(S, D, Attr); 4978 break; 4979 case AttributeList::AT_ScopedLockable: 4980 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr); 4981 break; 4982 case AttributeList::AT_NoSanitize: 4983 handleNoSanitizeAttr(S, D, Attr); 4984 break; 4985 case AttributeList::AT_NoSanitizeSpecific: 4986 handleNoSanitizeSpecificAttr(S, D, Attr); 4987 break; 4988 case AttributeList::AT_NoThreadSafetyAnalysis: 4989 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr); 4990 break; 4991 case AttributeList::AT_GuardedBy: 4992 handleGuardedByAttr(S, D, Attr); 4993 break; 4994 case AttributeList::AT_PtGuardedBy: 4995 handlePtGuardedByAttr(S, D, Attr); 4996 break; 4997 case AttributeList::AT_ExclusiveTrylockFunction: 4998 handleExclusiveTrylockFunctionAttr(S, D, Attr); 4999 break; 5000 case AttributeList::AT_LockReturned: 5001 handleLockReturnedAttr(S, D, Attr); 5002 break; 5003 case AttributeList::AT_LocksExcluded: 5004 handleLocksExcludedAttr(S, D, Attr); 5005 break; 5006 case AttributeList::AT_SharedTrylockFunction: 5007 handleSharedTrylockFunctionAttr(S, D, Attr); 5008 break; 5009 case AttributeList::AT_AcquiredBefore: 5010 handleAcquiredBeforeAttr(S, D, Attr); 5011 break; 5012 case AttributeList::AT_AcquiredAfter: 5013 handleAcquiredAfterAttr(S, D, Attr); 5014 break; 5015 5016 // Capability analysis attributes. 5017 case AttributeList::AT_Capability: 5018 case AttributeList::AT_Lockable: 5019 handleCapabilityAttr(S, D, Attr); 5020 break; 5021 case AttributeList::AT_RequiresCapability: 5022 handleRequiresCapabilityAttr(S, D, Attr); 5023 break; 5024 5025 case AttributeList::AT_AssertCapability: 5026 handleAssertCapabilityAttr(S, D, Attr); 5027 break; 5028 case AttributeList::AT_AcquireCapability: 5029 handleAcquireCapabilityAttr(S, D, Attr); 5030 break; 5031 case AttributeList::AT_ReleaseCapability: 5032 handleReleaseCapabilityAttr(S, D, Attr); 5033 break; 5034 case AttributeList::AT_TryAcquireCapability: 5035 handleTryAcquireCapabilityAttr(S, D, Attr); 5036 break; 5037 5038 // Consumed analysis attributes. 5039 case AttributeList::AT_Consumable: 5040 handleConsumableAttr(S, D, Attr); 5041 break; 5042 case AttributeList::AT_ConsumableAutoCast: 5043 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr); 5044 break; 5045 case AttributeList::AT_ConsumableSetOnRead: 5046 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr); 5047 break; 5048 case AttributeList::AT_CallableWhen: 5049 handleCallableWhenAttr(S, D, Attr); 5050 break; 5051 case AttributeList::AT_ParamTypestate: 5052 handleParamTypestateAttr(S, D, Attr); 5053 break; 5054 case AttributeList::AT_ReturnTypestate: 5055 handleReturnTypestateAttr(S, D, Attr); 5056 break; 5057 case AttributeList::AT_SetTypestate: 5058 handleSetTypestateAttr(S, D, Attr); 5059 break; 5060 case AttributeList::AT_TestTypestate: 5061 handleTestTypestateAttr(S, D, Attr); 5062 break; 5063 5064 // Type safety attributes. 5065 case AttributeList::AT_ArgumentWithTypeTag: 5066 handleArgumentWithTypeTagAttr(S, D, Attr); 5067 break; 5068 case AttributeList::AT_TypeTagForDatatype: 5069 handleTypeTagForDatatypeAttr(S, D, Attr); 5070 break; 5071 } 5072 } 5073 5074 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified 5075 /// attribute list to the specified decl, ignoring any type attributes. 5076 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, 5077 const AttributeList *AttrList, 5078 bool IncludeCXX11Attributes) { 5079 for (const AttributeList* l = AttrList; l; l = l->getNext()) 5080 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes); 5081 5082 // FIXME: We should be able to handle these cases in TableGen. 5083 // GCC accepts 5084 // static int a9 __attribute__((weakref)); 5085 // but that looks really pointless. We reject it. 5086 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) { 5087 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) 5088 << cast<NamedDecl>(D); 5089 D->dropAttr<WeakRefAttr>(); 5090 return; 5091 } 5092 5093 // FIXME: We should be able to handle this in TableGen as well. It would be 5094 // good to have a way to specify "these attributes must appear as a group", 5095 // for these. Additionally, it would be good to have a way to specify "these 5096 // attribute must never appear as a group" for attributes like cold and hot. 5097 if (!D->hasAttr<OpenCLKernelAttr>()) { 5098 // These attributes cannot be applied to a non-kernel function. 5099 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) { 5100 // FIXME: This emits a different error message than 5101 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction. 5102 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 5103 D->setInvalidDecl(); 5104 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) { 5105 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 5106 D->setInvalidDecl(); 5107 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) { 5108 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 5109 D->setInvalidDecl(); 5110 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) { 5111 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 5112 << A << ExpectedKernelFunction; 5113 D->setInvalidDecl(); 5114 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) { 5115 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 5116 << A << ExpectedKernelFunction; 5117 D->setInvalidDecl(); 5118 } 5119 } 5120 } 5121 5122 // Annotation attributes are the only attributes allowed after an access 5123 // specifier. 5124 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 5125 const AttributeList *AttrList) { 5126 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5127 if (l->getKind() == AttributeList::AT_Annotate) { 5128 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute()); 5129 } else { 5130 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec); 5131 return true; 5132 } 5133 } 5134 5135 return false; 5136 } 5137 5138 /// checkUnusedDeclAttributes - Check a list of attributes to see if it 5139 /// contains any decl attributes that we should warn about. 5140 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) { 5141 for ( ; A; A = A->getNext()) { 5142 // Only warn if the attribute is an unignored, non-type attribute. 5143 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue; 5144 if (A->getKind() == AttributeList::IgnoredAttribute) continue; 5145 5146 if (A->getKind() == AttributeList::UnknownAttribute) { 5147 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored) 5148 << A->getName() << A->getRange(); 5149 } else { 5150 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl) 5151 << A->getName() << A->getRange(); 5152 } 5153 } 5154 } 5155 5156 /// checkUnusedDeclAttributes - Given a declarator which is not being 5157 /// used to build a declaration, complain about any decl attributes 5158 /// which might be lying around on it. 5159 void Sema::checkUnusedDeclAttributes(Declarator &D) { 5160 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList()); 5161 ::checkUnusedDeclAttributes(*this, D.getAttributes()); 5162 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) 5163 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs()); 5164 } 5165 5166 /// DeclClonePragmaWeak - clone existing decl (maybe definition), 5167 /// \#pragma weak needs a non-definition decl and source may not have one. 5168 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 5169 SourceLocation Loc) { 5170 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND)); 5171 NamedDecl *NewD = nullptr; 5172 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 5173 FunctionDecl *NewFD; 5174 // FIXME: Missing call to CheckFunctionDeclaration(). 5175 // FIXME: Mangling? 5176 // FIXME: Is the qualifier info correct? 5177 // FIXME: Is the DeclContext correct? 5178 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(), 5179 Loc, Loc, DeclarationName(II), 5180 FD->getType(), FD->getTypeSourceInfo(), 5181 SC_None, false/*isInlineSpecified*/, 5182 FD->hasPrototype(), 5183 false/*isConstexprSpecified*/); 5184 NewD = NewFD; 5185 5186 if (FD->getQualifier()) 5187 NewFD->setQualifierInfo(FD->getQualifierLoc()); 5188 5189 // Fake up parameter variables; they are declared as if this were 5190 // a typedef. 5191 QualType FDTy = FD->getType(); 5192 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) { 5193 SmallVector<ParmVarDecl*, 16> Params; 5194 for (const auto &AI : FT->param_types()) { 5195 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI); 5196 Param->setScopeInfo(0, Params.size()); 5197 Params.push_back(Param); 5198 } 5199 NewFD->setParams(Params); 5200 } 5201 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) { 5202 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(), 5203 VD->getInnerLocStart(), VD->getLocation(), II, 5204 VD->getType(), VD->getTypeSourceInfo(), 5205 VD->getStorageClass()); 5206 if (VD->getQualifier()) { 5207 VarDecl *NewVD = cast<VarDecl>(NewD); 5208 NewVD->setQualifierInfo(VD->getQualifierLoc()); 5209 } 5210 } 5211 return NewD; 5212 } 5213 5214 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak 5215 /// applied to it, possibly with an alias. 5216 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) { 5217 if (W.getUsed()) return; // only do this once 5218 W.setUsed(true); 5219 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...)) 5220 IdentifierInfo *NDId = ND->getIdentifier(); 5221 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation()); 5222 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(), 5223 W.getLocation())); 5224 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); 5225 WeakTopLevelDecl.push_back(NewD); 5226 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin 5227 // to insert Decl at TU scope, sorry. 5228 DeclContext *SavedContext = CurContext; 5229 CurContext = Context.getTranslationUnitDecl(); 5230 NewD->setDeclContext(CurContext); 5231 NewD->setLexicalDeclContext(CurContext); 5232 PushOnScopeChains(NewD, S); 5233 CurContext = SavedContext; 5234 } else { // just add weak to existing 5235 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); 5236 } 5237 } 5238 5239 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) { 5240 // It's valid to "forward-declare" #pragma weak, in which case we 5241 // have to do this. 5242 LoadExternalWeakUndeclaredIdentifiers(); 5243 if (!WeakUndeclaredIdentifiers.empty()) { 5244 NamedDecl *ND = nullptr; 5245 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 5246 if (VD->isExternC()) 5247 ND = VD; 5248 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 5249 if (FD->isExternC()) 5250 ND = FD; 5251 if (ND) { 5252 if (IdentifierInfo *Id = ND->getIdentifier()) { 5253 auto I = WeakUndeclaredIdentifiers.find(Id); 5254 if (I != WeakUndeclaredIdentifiers.end()) { 5255 WeakInfo W = I->second; 5256 DeclApplyPragmaWeak(S, ND, W); 5257 WeakUndeclaredIdentifiers[Id] = W; 5258 } 5259 } 5260 } 5261 } 5262 } 5263 5264 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in 5265 /// it, apply them to D. This is a bit tricky because PD can have attributes 5266 /// specified in many different places, and we need to find and apply them all. 5267 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) { 5268 // Apply decl attributes from the DeclSpec if present. 5269 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList()) 5270 ProcessDeclAttributeList(S, D, Attrs); 5271 5272 // Walk the declarator structure, applying decl attributes that were in a type 5273 // position to the decl itself. This handles cases like: 5274 // int *__attr__(x)** D; 5275 // when X is a decl attribute. 5276 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) 5277 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs()) 5278 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false); 5279 5280 // Finally, apply any attributes on the decl itself. 5281 if (const AttributeList *Attrs = PD.getAttributes()) 5282 ProcessDeclAttributeList(S, D, Attrs); 5283 } 5284 5285 /// Is the given declaration allowed to use a forbidden type? 5286 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) { 5287 // Private ivars are always okay. Unfortunately, people don't 5288 // always properly make their ivars private, even in system headers. 5289 // Plus we need to make fields okay, too. 5290 // Function declarations in sys headers will be marked unavailable. 5291 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) && 5292 !isa<FunctionDecl>(decl)) 5293 return false; 5294 5295 // Require it to be declared in a system header. 5296 return S.Context.getSourceManager().isInSystemHeader(decl->getLocation()); 5297 } 5298 5299 /// Handle a delayed forbidden-type diagnostic. 5300 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag, 5301 Decl *decl) { 5302 if (decl && isForbiddenTypeAllowed(S, decl)) { 5303 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, 5304 "this system declaration uses an unsupported type", 5305 diag.Loc)); 5306 return; 5307 } 5308 if (S.getLangOpts().ObjCAutoRefCount) 5309 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) { 5310 // FIXME: we may want to suppress diagnostics for all 5311 // kind of forbidden type messages on unavailable functions. 5312 if (FD->hasAttr<UnavailableAttr>() && 5313 diag.getForbiddenTypeDiagnostic() == 5314 diag::err_arc_array_param_no_ownership) { 5315 diag.Triggered = true; 5316 return; 5317 } 5318 } 5319 5320 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic()) 5321 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument(); 5322 diag.Triggered = true; 5323 } 5324 5325 5326 static bool isDeclDeprecated(Decl *D) { 5327 do { 5328 if (D->isDeprecated()) 5329 return true; 5330 // A category implicitly has the availability of the interface. 5331 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D)) 5332 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface()) 5333 return Interface->isDeprecated(); 5334 } while ((D = cast_or_null<Decl>(D->getDeclContext()))); 5335 return false; 5336 } 5337 5338 static bool isDeclUnavailable(Decl *D) { 5339 do { 5340 if (D->isUnavailable()) 5341 return true; 5342 // A category implicitly has the availability of the interface. 5343 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D)) 5344 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface()) 5345 return Interface->isUnavailable(); 5346 } while ((D = cast_or_null<Decl>(D->getDeclContext()))); 5347 return false; 5348 } 5349 5350 static void DoEmitAvailabilityWarning(Sema &S, Sema::AvailabilityDiagnostic K, 5351 Decl *Ctx, const NamedDecl *D, 5352 StringRef Message, SourceLocation Loc, 5353 const ObjCInterfaceDecl *UnknownObjCClass, 5354 const ObjCPropertyDecl *ObjCProperty, 5355 bool ObjCPropertyAccess) { 5356 // Diagnostics for deprecated or unavailable. 5357 unsigned diag, diag_message, diag_fwdclass_message; 5358 5359 // Matches 'diag::note_property_attribute' options. 5360 unsigned property_note_select; 5361 5362 // Matches diag::note_availability_specified_here. 5363 unsigned available_here_select_kind; 5364 5365 // Don't warn if our current context is deprecated or unavailable. 5366 switch (K) { 5367 case Sema::AD_Deprecation: 5368 if (isDeclDeprecated(Ctx) || isDeclUnavailable(Ctx)) 5369 return; 5370 diag = !ObjCPropertyAccess ? diag::warn_deprecated 5371 : diag::warn_property_method_deprecated; 5372 diag_message = diag::warn_deprecated_message; 5373 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message; 5374 property_note_select = /* deprecated */ 0; 5375 available_here_select_kind = /* deprecated */ 2; 5376 break; 5377 5378 case Sema::AD_Unavailable: 5379 if (isDeclUnavailable(Ctx)) 5380 return; 5381 diag = !ObjCPropertyAccess ? diag::err_unavailable 5382 : diag::err_property_method_unavailable; 5383 diag_message = diag::err_unavailable_message; 5384 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message; 5385 property_note_select = /* unavailable */ 1; 5386 available_here_select_kind = /* unavailable */ 0; 5387 break; 5388 5389 case Sema::AD_Partial: 5390 diag = diag::warn_partial_availability; 5391 diag_message = diag::warn_partial_message; 5392 diag_fwdclass_message = diag::warn_partial_fwdclass_message; 5393 property_note_select = /* partial */ 2; 5394 available_here_select_kind = /* partial */ 3; 5395 break; 5396 } 5397 5398 if (!Message.empty()) { 5399 S.Diag(Loc, diag_message) << D << Message; 5400 if (ObjCProperty) 5401 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) 5402 << ObjCProperty->getDeclName() << property_note_select; 5403 } else if (!UnknownObjCClass) { 5404 S.Diag(Loc, diag) << D; 5405 if (ObjCProperty) 5406 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) 5407 << ObjCProperty->getDeclName() << property_note_select; 5408 } else { 5409 S.Diag(Loc, diag_fwdclass_message) << D; 5410 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class); 5411 } 5412 5413 S.Diag(D->getLocation(), diag::note_availability_specified_here) 5414 << D << available_here_select_kind; 5415 if (K == Sema::AD_Partial) 5416 S.Diag(Loc, diag::note_partial_availability_silence) << D; 5417 } 5418 5419 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD, 5420 Decl *Ctx) { 5421 assert(DD.Kind == DelayedDiagnostic::Deprecation || 5422 DD.Kind == DelayedDiagnostic::Unavailable); 5423 Sema::AvailabilityDiagnostic AD = DD.Kind == DelayedDiagnostic::Deprecation 5424 ? Sema::AD_Deprecation 5425 : Sema::AD_Unavailable; 5426 DD.Triggered = true; 5427 DoEmitAvailabilityWarning( 5428 S, AD, Ctx, DD.getDeprecationDecl(), DD.getDeprecationMessage(), DD.Loc, 5429 DD.getUnknownObjCClass(), DD.getObjCProperty(), false); 5430 } 5431 5432 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) { 5433 assert(DelayedDiagnostics.getCurrentPool()); 5434 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool(); 5435 DelayedDiagnostics.popWithoutEmitting(state); 5436 5437 // When delaying diagnostics to run in the context of a parsed 5438 // declaration, we only want to actually emit anything if parsing 5439 // succeeds. 5440 if (!decl) return; 5441 5442 // We emit all the active diagnostics in this pool or any of its 5443 // parents. In general, we'll get one pool for the decl spec 5444 // and a child pool for each declarator; in a decl group like: 5445 // deprecated_typedef foo, *bar, baz(); 5446 // only the declarator pops will be passed decls. This is correct; 5447 // we really do need to consider delayed diagnostics from the decl spec 5448 // for each of the different declarations. 5449 const DelayedDiagnosticPool *pool = &poppedPool; 5450 do { 5451 for (DelayedDiagnosticPool::pool_iterator 5452 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) { 5453 // This const_cast is a bit lame. Really, Triggered should be mutable. 5454 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i); 5455 if (diag.Triggered) 5456 continue; 5457 5458 switch (diag.Kind) { 5459 case DelayedDiagnostic::Deprecation: 5460 case DelayedDiagnostic::Unavailable: 5461 // Don't bother giving deprecation/unavailable diagnostics if 5462 // the decl is invalid. 5463 if (!decl->isInvalidDecl()) 5464 handleDelayedAvailabilityCheck(*this, diag, decl); 5465 break; 5466 5467 case DelayedDiagnostic::Access: 5468 HandleDelayedAccessCheck(diag, decl); 5469 break; 5470 5471 case DelayedDiagnostic::ForbiddenType: 5472 handleDelayedForbiddenType(*this, diag, decl); 5473 break; 5474 } 5475 } 5476 } while ((pool = pool->getParent())); 5477 } 5478 5479 /// Given a set of delayed diagnostics, re-emit them as if they had 5480 /// been delayed in the current context instead of in the given pool. 5481 /// Essentially, this just moves them to the current pool. 5482 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) { 5483 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool(); 5484 assert(curPool && "re-emitting in undelayed context not supported"); 5485 curPool->steal(pool); 5486 } 5487 5488 void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD, 5489 NamedDecl *D, StringRef Message, 5490 SourceLocation Loc, 5491 const ObjCInterfaceDecl *UnknownObjCClass, 5492 const ObjCPropertyDecl *ObjCProperty, 5493 bool ObjCPropertyAccess) { 5494 // Delay if we're currently parsing a declaration. 5495 if (DelayedDiagnostics.shouldDelayDiagnostics() && AD != AD_Partial) { 5496 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability( 5497 AD, Loc, D, UnknownObjCClass, ObjCProperty, Message, 5498 ObjCPropertyAccess)); 5499 return; 5500 } 5501 5502 Decl *Ctx = cast<Decl>(getCurLexicalContext()); 5503 DoEmitAvailabilityWarning(*this, AD, Ctx, D, Message, Loc, UnknownObjCClass, 5504 ObjCProperty, ObjCPropertyAccess); 5505 } 5506