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