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