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