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