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