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