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/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/Mangle.h" 24 #include "clang/AST/RecursiveASTVisitor.h" 25 #include "clang/Basic/CharInfo.h" 26 #include "clang/Basic/SourceManager.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/Lex/Preprocessor.h" 29 #include "clang/Sema/DeclSpec.h" 30 #include "clang/Sema/DelayedDiagnostic.h" 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/Scope.h" 34 #include "clang/Sema/SemaInternal.h" 35 #include "llvm/ADT/StringExtras.h" 36 #include "llvm/Support/MathExtras.h" 37 38 using namespace clang; 39 using namespace sema; 40 41 namespace AttributeLangSupport { 42 enum LANG { 43 C, 44 Cpp, 45 ObjC 46 }; 47 } // end namespace AttributeLangSupport 48 49 //===----------------------------------------------------------------------===// 50 // Helper functions 51 //===----------------------------------------------------------------------===// 52 53 /// isFunctionOrMethod - Return true if the given decl has function 54 /// type (function or function-typed variable) or an Objective-C 55 /// method. 56 static bool isFunctionOrMethod(const Decl *D) { 57 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D); 58 } 59 60 /// \brief Return true if the given decl has function type (function or 61 /// function-typed variable) or an Objective-C method or a block. 62 static bool isFunctionOrMethodOrBlock(const Decl *D) { 63 return isFunctionOrMethod(D) || isa<BlockDecl>(D); 64 } 65 66 /// Return true if the given decl has a declarator that should have 67 /// been processed by Sema::GetTypeForDeclarator. 68 static bool hasDeclarator(const Decl *D) { 69 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl. 70 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) || 71 isa<ObjCPropertyDecl>(D); 72 } 73 74 /// hasFunctionProto - Return true if the given decl has a argument 75 /// information. This decl should have already passed 76 /// isFunctionOrMethod or isFunctionOrMethodOrBlock. 77 static bool hasFunctionProto(const Decl *D) { 78 if (const FunctionType *FnTy = D->getFunctionType()) 79 return isa<FunctionProtoType>(FnTy); 80 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D); 81 } 82 83 /// getFunctionOrMethodNumParams - Return number of function or method 84 /// parameters. It is an error to call this on a K&R function (use 85 /// hasFunctionProto first). 86 static unsigned getFunctionOrMethodNumParams(const Decl *D) { 87 if (const FunctionType *FnTy = D->getFunctionType()) 88 return cast<FunctionProtoType>(FnTy)->getNumParams(); 89 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 90 return BD->getNumParams(); 91 return cast<ObjCMethodDecl>(D)->param_size(); 92 } 93 94 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) { 95 if (const FunctionType *FnTy = D->getFunctionType()) 96 return cast<FunctionProtoType>(FnTy)->getParamType(Idx); 97 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 98 return BD->getParamDecl(Idx)->getType(); 99 100 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType(); 101 } 102 103 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) { 104 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 105 return FD->getParamDecl(Idx)->getSourceRange(); 106 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 107 return MD->parameters()[Idx]->getSourceRange(); 108 if (const auto *BD = dyn_cast<BlockDecl>(D)) 109 return BD->getParamDecl(Idx)->getSourceRange(); 110 return SourceRange(); 111 } 112 113 static QualType getFunctionOrMethodResultType(const Decl *D) { 114 if (const FunctionType *FnTy = D->getFunctionType()) 115 return cast<FunctionType>(FnTy)->getReturnType(); 116 return cast<ObjCMethodDecl>(D)->getReturnType(); 117 } 118 119 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) { 120 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 121 return FD->getReturnTypeSourceRange(); 122 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 123 return MD->getReturnTypeSourceRange(); 124 return SourceRange(); 125 } 126 127 static bool isFunctionOrMethodVariadic(const Decl *D) { 128 if (const FunctionType *FnTy = D->getFunctionType()) { 129 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy); 130 return proto->isVariadic(); 131 } 132 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 133 return BD->isVariadic(); 134 135 return cast<ObjCMethodDecl>(D)->isVariadic(); 136 } 137 138 static bool isInstanceMethod(const Decl *D) { 139 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) 140 return MethodDecl->isInstance(); 141 return false; 142 } 143 144 static inline bool isNSStringType(QualType T, ASTContext &Ctx) { 145 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>(); 146 if (!PT) 147 return false; 148 149 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface(); 150 if (!Cls) 151 return false; 152 153 IdentifierInfo* ClsName = Cls->getIdentifier(); 154 155 // FIXME: Should we walk the chain of classes? 156 return ClsName == &Ctx.Idents.get("NSString") || 157 ClsName == &Ctx.Idents.get("NSMutableString"); 158 } 159 160 static inline bool isCFStringType(QualType T, ASTContext &Ctx) { 161 const PointerType *PT = T->getAs<PointerType>(); 162 if (!PT) 163 return false; 164 165 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>(); 166 if (!RT) 167 return false; 168 169 const RecordDecl *RD = RT->getDecl(); 170 if (RD->getTagKind() != TTK_Struct) 171 return false; 172 173 return RD->getIdentifier() == &Ctx.Idents.get("__CFString"); 174 } 175 176 static unsigned getNumAttributeArgs(const AttributeList &Attr) { 177 // FIXME: Include the type in the argument list. 178 return Attr.getNumArgs() + Attr.hasParsedType(); 179 } 180 181 template <typename Compare> 182 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr, 183 unsigned Num, unsigned Diag, 184 Compare Comp) { 185 if (Comp(getNumAttributeArgs(Attr), Num)) { 186 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num; 187 return false; 188 } 189 190 return true; 191 } 192 193 /// \brief Check if the attribute has exactly as many args as Num. May 194 /// output an error. 195 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr, 196 unsigned Num) { 197 return checkAttributeNumArgsImpl(S, Attr, Num, 198 diag::err_attribute_wrong_number_arguments, 199 std::not_equal_to<unsigned>()); 200 } 201 202 /// \brief Check if the attribute has at least as many args as Num. May 203 /// output an error. 204 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr, 205 unsigned Num) { 206 return checkAttributeNumArgsImpl(S, Attr, Num, 207 diag::err_attribute_too_few_arguments, 208 std::less<unsigned>()); 209 } 210 211 /// \brief Check if the attribute has at most as many args as Num. May 212 /// output an error. 213 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr, 214 unsigned Num) { 215 return checkAttributeNumArgsImpl(S, Attr, Num, 216 diag::err_attribute_too_many_arguments, 217 std::greater<unsigned>()); 218 } 219 220 /// \brief If Expr is a valid integer constant, get the value of the integer 221 /// expression and return success or failure. May output an error. 222 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr, 223 const Expr *Expr, uint32_t &Val, 224 unsigned Idx = UINT_MAX) { 225 llvm::APSInt I(32); 226 if (Expr->isTypeDependent() || Expr->isValueDependent() || 227 !Expr->isIntegerConstantExpr(I, S.Context)) { 228 if (Idx != UINT_MAX) 229 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 230 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant 231 << Expr->getSourceRange(); 232 else 233 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 234 << Attr.getName() << AANT_ArgumentIntegerConstant 235 << Expr->getSourceRange(); 236 return false; 237 } 238 239 if (!I.isIntN(32)) { 240 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) 241 << I.toString(10, false) << 32 << /* Unsigned */ 1; 242 return false; 243 } 244 245 Val = (uint32_t)I.getZExtValue(); 246 return true; 247 } 248 249 /// \brief Wrapper around checkUInt32Argument, with an extra check to be sure 250 /// that the result will fit into a regular (signed) int. All args have the same 251 /// purpose as they do in checkUInt32Argument. 252 static bool checkPositiveIntArgument(Sema &S, const AttributeList &Attr, 253 const Expr *Expr, int &Val, 254 unsigned Idx = UINT_MAX) { 255 uint32_t UVal; 256 if (!checkUInt32Argument(S, Attr, Expr, UVal, Idx)) 257 return false; 258 259 if (UVal > (uint32_t)std::numeric_limits<int>::max()) { 260 llvm::APSInt I(32); // for toString 261 I = UVal; 262 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) 263 << I.toString(10, false) << 32 << /* Unsigned */ 0; 264 return false; 265 } 266 267 Val = UVal; 268 return true; 269 } 270 271 /// \brief Diagnose mutually exclusive attributes when present on a given 272 /// declaration. Returns true if diagnosed. 273 template <typename AttrTy> 274 static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range, 275 IdentifierInfo *Ident) { 276 if (AttrTy *A = D->getAttr<AttrTy>()) { 277 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident 278 << A; 279 S.Diag(A->getLocation(), diag::note_conflicting_attribute); 280 return true; 281 } 282 return false; 283 } 284 285 /// \brief Check if IdxExpr is a valid parameter index for a function or 286 /// instance method D. May output an error. 287 /// 288 /// \returns true if IdxExpr is a valid index. 289 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D, 290 const AttributeList &Attr, 291 unsigned AttrArgNum, 292 const Expr *IdxExpr, 293 uint64_t &Idx) { 294 assert(isFunctionOrMethodOrBlock(D)); 295 296 // In C++ the implicit 'this' function parameter also counts. 297 // Parameters are counted from one. 298 bool HP = hasFunctionProto(D); 299 bool HasImplicitThisParam = isInstanceMethod(D); 300 bool IV = HP && isFunctionOrMethodVariadic(D); 301 unsigned NumParams = 302 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam; 303 304 llvm::APSInt IdxInt; 305 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() || 306 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) { 307 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 308 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant 309 << IdxExpr->getSourceRange(); 310 return false; 311 } 312 313 Idx = IdxInt.getLimitedValue(); 314 if (Idx < 1 || (!IV && Idx > NumParams)) { 315 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 316 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange(); 317 return false; 318 } 319 Idx--; // Convert to zero-based. 320 if (HasImplicitThisParam) { 321 if (Idx == 0) { 322 S.Diag(Attr.getLoc(), 323 diag::err_attribute_invalid_implicit_this_argument) 324 << Attr.getName() << IdxExpr->getSourceRange(); 325 return false; 326 } 327 --Idx; 328 } 329 330 return true; 331 } 332 333 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal. 334 /// If not emit an error and return false. If the argument is an identifier it 335 /// will emit an error with a fixit hint and treat it as if it was a string 336 /// literal. 337 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr, 338 unsigned ArgNum, StringRef &Str, 339 SourceLocation *ArgLocation) { 340 // Look for identifiers. If we have one emit a hint to fix it to a literal. 341 if (Attr.isArgIdent(ArgNum)) { 342 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum); 343 Diag(Loc->Loc, diag::err_attribute_argument_type) 344 << Attr.getName() << AANT_ArgumentString 345 << FixItHint::CreateInsertion(Loc->Loc, "\"") 346 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\""); 347 Str = Loc->Ident->getName(); 348 if (ArgLocation) 349 *ArgLocation = Loc->Loc; 350 return true; 351 } 352 353 // Now check for an actual string literal. 354 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum); 355 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts()); 356 if (ArgLocation) 357 *ArgLocation = ArgExpr->getLocStart(); 358 359 if (!Literal || !Literal->isAscii()) { 360 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type) 361 << Attr.getName() << AANT_ArgumentString; 362 return false; 363 } 364 365 Str = Literal->getString(); 366 return true; 367 } 368 369 /// \brief Applies the given attribute to the Decl without performing any 370 /// additional semantic checking. 371 template <typename AttrType> 372 static void handleSimpleAttribute(Sema &S, Decl *D, 373 const AttributeList &Attr) { 374 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context, 375 Attr.getAttributeSpellingListIndex())); 376 } 377 378 template <typename AttrType> 379 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D, 380 const AttributeList &Attr) { 381 handleSimpleAttribute<AttrType>(S, D, Attr); 382 } 383 384 /// \brief Applies the given attribute to the Decl so long as the Decl doesn't 385 /// already have one of the given incompatible attributes. 386 template <typename AttrType, typename IncompatibleAttrType, 387 typename... IncompatibleAttrTypes> 388 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D, 389 const AttributeList &Attr) { 390 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(), 391 Attr.getName())) 392 return; 393 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D, 394 Attr); 395 } 396 397 /// \brief Check if the passed-in expression is of type int or bool. 398 static bool isIntOrBool(Expr *Exp) { 399 QualType QT = Exp->getType(); 400 return QT->isBooleanType() || QT->isIntegerType(); 401 } 402 403 404 // Check to see if the type is a smart pointer of some kind. We assume 405 // it's a smart pointer if it defines both operator-> and operator*. 406 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) { 407 DeclContextLookupResult Res1 = RT->getDecl()->lookup( 408 S.Context.DeclarationNames.getCXXOperatorName(OO_Star)); 409 if (Res1.empty()) 410 return false; 411 412 DeclContextLookupResult Res2 = RT->getDecl()->lookup( 413 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow)); 414 if (Res2.empty()) 415 return false; 416 417 return true; 418 } 419 420 /// \brief Check if passed in Decl is a pointer type. 421 /// Note that this function may produce an error message. 422 /// \return true if the Decl is a pointer type; false otherwise 423 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D, 424 const AttributeList &Attr) { 425 const ValueDecl *vd = cast<ValueDecl>(D); 426 QualType QT = vd->getType(); 427 if (QT->isAnyPointerType()) 428 return true; 429 430 if (const RecordType *RT = QT->getAs<RecordType>()) { 431 // If it's an incomplete type, it could be a smart pointer; skip it. 432 // (We don't want to force template instantiation if we can avoid it, 433 // since that would alter the order in which templates are instantiated.) 434 if (RT->isIncompleteType()) 435 return true; 436 437 if (threadSafetyCheckIsSmartPointer(S, RT)) 438 return true; 439 } 440 441 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer) 442 << Attr.getName() << QT; 443 return false; 444 } 445 446 /// \brief Checks that the passed in QualType either is of RecordType or points 447 /// to RecordType. Returns the relevant RecordType, null if it does not exit. 448 static const RecordType *getRecordType(QualType QT) { 449 if (const RecordType *RT = QT->getAs<RecordType>()) 450 return RT; 451 452 // Now check if we point to record type. 453 if (const PointerType *PT = QT->getAs<PointerType>()) 454 return PT->getPointeeType()->getAs<RecordType>(); 455 456 return nullptr; 457 } 458 459 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) { 460 const RecordType *RT = getRecordType(Ty); 461 462 if (!RT) 463 return false; 464 465 // Don't check for the capability if the class hasn't been defined yet. 466 if (RT->isIncompleteType()) 467 return true; 468 469 // Allow smart pointers to be used as capability objects. 470 // FIXME -- Check the type that the smart pointer points to. 471 if (threadSafetyCheckIsSmartPointer(S, RT)) 472 return true; 473 474 // Check if the record itself has a capability. 475 RecordDecl *RD = RT->getDecl(); 476 if (RD->hasAttr<CapabilityAttr>()) 477 return true; 478 479 // Else check if any base classes have a capability. 480 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 481 CXXBasePaths BPaths(false, false); 482 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) { 483 const auto *Type = BS->getType()->getAs<RecordType>(); 484 return Type->getDecl()->hasAttr<CapabilityAttr>(); 485 }, BPaths)) 486 return true; 487 } 488 return false; 489 } 490 491 static bool checkTypedefTypeForCapability(QualType Ty) { 492 const auto *TD = Ty->getAs<TypedefType>(); 493 if (!TD) 494 return false; 495 496 TypedefNameDecl *TN = TD->getDecl(); 497 if (!TN) 498 return false; 499 500 return TN->hasAttr<CapabilityAttr>(); 501 } 502 503 static bool typeHasCapability(Sema &S, QualType Ty) { 504 if (checkTypedefTypeForCapability(Ty)) 505 return true; 506 507 if (checkRecordTypeForCapability(S, Ty)) 508 return true; 509 510 return false; 511 } 512 513 static bool isCapabilityExpr(Sema &S, const Expr *Ex) { 514 // Capability expressions are simple expressions involving the boolean logic 515 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once 516 // a DeclRefExpr is found, its type should be checked to determine whether it 517 // is a capability or not. 518 519 if (const auto *E = dyn_cast<DeclRefExpr>(Ex)) 520 return typeHasCapability(S, E->getType()); 521 else if (const auto *E = dyn_cast<CastExpr>(Ex)) 522 return isCapabilityExpr(S, E->getSubExpr()); 523 else if (const auto *E = dyn_cast<ParenExpr>(Ex)) 524 return isCapabilityExpr(S, E->getSubExpr()); 525 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) { 526 if (E->getOpcode() == UO_LNot) 527 return isCapabilityExpr(S, E->getSubExpr()); 528 return false; 529 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) { 530 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr) 531 return isCapabilityExpr(S, E->getLHS()) && 532 isCapabilityExpr(S, E->getRHS()); 533 return false; 534 } 535 536 return false; 537 } 538 539 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to 540 /// a capability object. 541 /// \param Sidx The attribute argument index to start checking with. 542 /// \param ParamIdxOk Whether an argument can be indexing into a function 543 /// parameter list. 544 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D, 545 const AttributeList &Attr, 546 SmallVectorImpl<Expr *> &Args, 547 int Sidx = 0, 548 bool ParamIdxOk = false) { 549 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) { 550 Expr *ArgExp = Attr.getArgAsExpr(Idx); 551 552 if (ArgExp->isTypeDependent()) { 553 // FIXME -- need to check this again on template instantiation 554 Args.push_back(ArgExp); 555 continue; 556 } 557 558 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) { 559 if (StrLit->getLength() == 0 || 560 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) { 561 // Pass empty strings to the analyzer without warnings. 562 // Treat "*" as the universal lock. 563 Args.push_back(ArgExp); 564 continue; 565 } 566 567 // We allow constant strings to be used as a placeholder for expressions 568 // that are not valid C++ syntax, but warn that they are ignored. 569 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) << 570 Attr.getName(); 571 Args.push_back(ArgExp); 572 continue; 573 } 574 575 QualType ArgTy = ArgExp->getType(); 576 577 // A pointer to member expression of the form &MyClass::mu is treated 578 // specially -- we need to look at the type of the member. 579 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp)) 580 if (UOp->getOpcode() == UO_AddrOf) 581 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr())) 582 if (DRE->getDecl()->isCXXInstanceMember()) 583 ArgTy = DRE->getDecl()->getType(); 584 585 // First see if we can just cast to record type, or pointer to record type. 586 const RecordType *RT = getRecordType(ArgTy); 587 588 // Now check if we index into a record type function param. 589 if(!RT && ParamIdxOk) { 590 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 591 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp); 592 if(FD && IL) { 593 unsigned int NumParams = FD->getNumParams(); 594 llvm::APInt ArgValue = IL->getValue(); 595 uint64_t ParamIdxFromOne = ArgValue.getZExtValue(); 596 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1; 597 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) { 598 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range) 599 << Attr.getName() << Idx + 1 << NumParams; 600 continue; 601 } 602 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType(); 603 } 604 } 605 606 // If the type does not have a capability, see if the components of the 607 // expression have capabilities. This allows for writing C code where the 608 // capability may be on the type, and the expression is a capability 609 // boolean logic expression. Eg) requires_capability(A || B && !C) 610 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp)) 611 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable) 612 << Attr.getName() << ArgTy; 613 614 Args.push_back(ArgExp); 615 } 616 } 617 618 //===----------------------------------------------------------------------===// 619 // Attribute Implementations 620 //===----------------------------------------------------------------------===// 621 622 static void handlePtGuardedVarAttr(Sema &S, Decl *D, 623 const AttributeList &Attr) { 624 if (!threadSafetyCheckIsPointer(S, D, Attr)) 625 return; 626 627 D->addAttr(::new (S.Context) 628 PtGuardedVarAttr(Attr.getRange(), S.Context, 629 Attr.getAttributeSpellingListIndex())); 630 } 631 632 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, 633 const AttributeList &Attr, 634 Expr* &Arg) { 635 SmallVector<Expr*, 1> Args; 636 // check that all arguments are lockable objects 637 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 638 unsigned Size = Args.size(); 639 if (Size != 1) 640 return false; 641 642 Arg = Args[0]; 643 644 return true; 645 } 646 647 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) { 648 Expr *Arg = nullptr; 649 if (!checkGuardedByAttrCommon(S, D, Attr, Arg)) 650 return; 651 652 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg, 653 Attr.getAttributeSpellingListIndex())); 654 } 655 656 static void handlePtGuardedByAttr(Sema &S, Decl *D, 657 const AttributeList &Attr) { 658 Expr *Arg = nullptr; 659 if (!checkGuardedByAttrCommon(S, D, Attr, Arg)) 660 return; 661 662 if (!threadSafetyCheckIsPointer(S, D, Attr)) 663 return; 664 665 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(), 666 S.Context, Arg, 667 Attr.getAttributeSpellingListIndex())); 668 } 669 670 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, 671 const AttributeList &Attr, 672 SmallVectorImpl<Expr *> &Args) { 673 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 674 return false; 675 676 // Check that this attribute only applies to lockable types. 677 QualType QT = cast<ValueDecl>(D)->getType(); 678 if (!QT->isDependentType() && !typeHasCapability(S, QT)) { 679 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable) 680 << Attr.getName(); 681 return false; 682 } 683 684 // Check that all arguments are lockable objects. 685 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 686 if (Args.empty()) 687 return false; 688 689 return true; 690 } 691 692 static void handleAcquiredAfterAttr(Sema &S, Decl *D, 693 const AttributeList &Attr) { 694 SmallVector<Expr*, 1> Args; 695 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args)) 696 return; 697 698 Expr **StartArg = &Args[0]; 699 D->addAttr(::new (S.Context) 700 AcquiredAfterAttr(Attr.getRange(), S.Context, 701 StartArg, Args.size(), 702 Attr.getAttributeSpellingListIndex())); 703 } 704 705 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, 706 const AttributeList &Attr) { 707 SmallVector<Expr*, 1> Args; 708 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args)) 709 return; 710 711 Expr **StartArg = &Args[0]; 712 D->addAttr(::new (S.Context) 713 AcquiredBeforeAttr(Attr.getRange(), S.Context, 714 StartArg, Args.size(), 715 Attr.getAttributeSpellingListIndex())); 716 } 717 718 static bool checkLockFunAttrCommon(Sema &S, Decl *D, 719 const AttributeList &Attr, 720 SmallVectorImpl<Expr *> &Args) { 721 // zero or more arguments ok 722 // check that all arguments are lockable objects 723 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true); 724 725 return true; 726 } 727 728 static void handleAssertSharedLockAttr(Sema &S, Decl *D, 729 const AttributeList &Attr) { 730 SmallVector<Expr*, 1> Args; 731 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 732 return; 733 734 unsigned Size = Args.size(); 735 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 736 D->addAttr(::new (S.Context) 737 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size, 738 Attr.getAttributeSpellingListIndex())); 739 } 740 741 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D, 742 const AttributeList &Attr) { 743 SmallVector<Expr*, 1> Args; 744 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 745 return; 746 747 unsigned Size = Args.size(); 748 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 749 D->addAttr(::new (S.Context) 750 AssertExclusiveLockAttr(Attr.getRange(), S.Context, 751 StartArg, Size, 752 Attr.getAttributeSpellingListIndex())); 753 } 754 755 /// \brief Checks to be sure that the given parameter number is inbounds, and is 756 /// an some integral type. Will emit appropriate diagnostics if this returns 757 /// false. 758 /// 759 /// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used 760 /// to actually retrieve the argument, so it's base-0. 761 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD, 762 const AttributeList &Attr, 763 unsigned FuncParamNo, unsigned AttrArgNo) { 764 assert(Attr.isArgExpr(AttrArgNo) && "Expected expression argument"); 765 uint64_t Idx; 766 if (!checkFunctionOrMethodParameterIndex(S, FD, Attr, FuncParamNo, 767 Attr.getArgAsExpr(AttrArgNo), Idx)) 768 return false; 769 770 const ParmVarDecl *Param = FD->getParamDecl(Idx); 771 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) { 772 SourceLocation SrcLoc = Attr.getArgAsExpr(AttrArgNo)->getLocStart(); 773 S.Diag(SrcLoc, diag::err_attribute_integers_only) 774 << Attr.getName() << Param->getSourceRange(); 775 return false; 776 } 777 return true; 778 } 779 780 static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 781 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) || 782 !checkAttributeAtMostNumArgs(S, Attr, 2)) 783 return; 784 785 const auto *FD = cast<FunctionDecl>(D); 786 if (!FD->getReturnType()->isPointerType()) { 787 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only) 788 << Attr.getName(); 789 return; 790 } 791 792 const Expr *SizeExpr = Attr.getArgAsExpr(0); 793 int SizeArgNo; 794 // Paramater indices are 1-indexed, hence Index=1 795 if (!checkPositiveIntArgument(S, Attr, SizeExpr, SizeArgNo, /*Index=*/1)) 796 return; 797 798 if (!checkParamIsIntegerType(S, FD, Attr, SizeArgNo, /*AttrArgNo=*/0)) 799 return; 800 801 // Args are 1-indexed, so 0 implies that the arg was not present 802 int NumberArgNo = 0; 803 if (Attr.getNumArgs() == 2) { 804 const Expr *NumberExpr = Attr.getArgAsExpr(1); 805 // Paramater indices are 1-based, hence Index=2 806 if (!checkPositiveIntArgument(S, Attr, NumberExpr, NumberArgNo, 807 /*Index=*/2)) 808 return; 809 810 if (!checkParamIsIntegerType(S, FD, Attr, NumberArgNo, /*AttrArgNo=*/1)) 811 return; 812 } 813 814 D->addAttr(::new (S.Context) AllocSizeAttr( 815 Attr.getRange(), S.Context, SizeArgNo, NumberArgNo, 816 Attr.getAttributeSpellingListIndex())); 817 } 818 819 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, 820 const AttributeList &Attr, 821 SmallVectorImpl<Expr *> &Args) { 822 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 823 return false; 824 825 if (!isIntOrBool(Attr.getArgAsExpr(0))) { 826 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 827 << Attr.getName() << 1 << AANT_ArgumentIntOrBool; 828 return false; 829 } 830 831 // check that all arguments are lockable objects 832 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1); 833 834 return true; 835 } 836 837 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D, 838 const AttributeList &Attr) { 839 SmallVector<Expr*, 2> Args; 840 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 841 return; 842 843 D->addAttr(::new (S.Context) 844 SharedTrylockFunctionAttr(Attr.getRange(), S.Context, 845 Attr.getArgAsExpr(0), 846 Args.data(), Args.size(), 847 Attr.getAttributeSpellingListIndex())); 848 } 849 850 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D, 851 const AttributeList &Attr) { 852 SmallVector<Expr*, 2> Args; 853 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 854 return; 855 856 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr( 857 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(), 858 Args.size(), Attr.getAttributeSpellingListIndex())); 859 } 860 861 static void handleLockReturnedAttr(Sema &S, Decl *D, 862 const AttributeList &Attr) { 863 // check that the argument is lockable object 864 SmallVector<Expr*, 1> Args; 865 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 866 unsigned Size = Args.size(); 867 if (Size == 0) 868 return; 869 870 D->addAttr(::new (S.Context) 871 LockReturnedAttr(Attr.getRange(), S.Context, Args[0], 872 Attr.getAttributeSpellingListIndex())); 873 } 874 875 static void handleLocksExcludedAttr(Sema &S, Decl *D, 876 const AttributeList &Attr) { 877 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 878 return; 879 880 // check that all arguments are lockable objects 881 SmallVector<Expr*, 1> Args; 882 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 883 unsigned Size = Args.size(); 884 if (Size == 0) 885 return; 886 Expr **StartArg = &Args[0]; 887 888 D->addAttr(::new (S.Context) 889 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size, 890 Attr.getAttributeSpellingListIndex())); 891 } 892 893 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) { 894 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if); 895 896 Expr *Cond = Attr.getArgAsExpr(0); 897 if (!Cond->isTypeDependent()) { 898 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); 899 if (Converted.isInvalid()) 900 return; 901 Cond = Converted.get(); 902 } 903 904 StringRef Msg; 905 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg)) 906 return; 907 908 SmallVector<PartialDiagnosticAt, 8> Diags; 909 if (!Cond->isValueDependent() && 910 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D), 911 Diags)) { 912 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr); 913 for (const PartialDiagnosticAt &PDiag : Diags) 914 S.Diag(PDiag.first, PDiag.second); 915 return; 916 } 917 918 D->addAttr(::new (S.Context) 919 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg, 920 Attr.getAttributeSpellingListIndex())); 921 } 922 923 static void handlePassObjectSizeAttr(Sema &S, Decl *D, 924 const AttributeList &Attr) { 925 if (D->hasAttr<PassObjectSizeAttr>()) { 926 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter) 927 << Attr.getName(); 928 return; 929 } 930 931 Expr *E = Attr.getArgAsExpr(0); 932 uint32_t Type; 933 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1)) 934 return; 935 936 // pass_object_size's argument is passed in as the second argument of 937 // __builtin_object_size. So, it has the same constraints as that second 938 // argument; namely, it must be in the range [0, 3]. 939 if (Type > 3) { 940 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range) 941 << Attr.getName() << 0 << 3 << E->getSourceRange(); 942 return; 943 } 944 945 // pass_object_size is only supported on constant pointer parameters; as a 946 // kindness to users, we allow the parameter to be non-const for declarations. 947 // At this point, we have no clue if `D` belongs to a function declaration or 948 // definition, so we defer the constness check until later. 949 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) { 950 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only) 951 << Attr.getName() << 1; 952 return; 953 } 954 955 D->addAttr(::new (S.Context) 956 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type, 957 Attr.getAttributeSpellingListIndex())); 958 } 959 960 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) { 961 ConsumableAttr::ConsumedState DefaultState; 962 963 if (Attr.isArgIdent(0)) { 964 IdentifierLoc *IL = Attr.getArgAsIdent(0); 965 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(), 966 DefaultState)) { 967 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) 968 << Attr.getName() << IL->Ident; 969 return; 970 } 971 } else { 972 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 973 << Attr.getName() << AANT_ArgumentIdentifier; 974 return; 975 } 976 977 D->addAttr(::new (S.Context) 978 ConsumableAttr(Attr.getRange(), S.Context, DefaultState, 979 Attr.getAttributeSpellingListIndex())); 980 } 981 982 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD, 983 const AttributeList &Attr) { 984 ASTContext &CurrContext = S.getASTContext(); 985 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType(); 986 987 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) { 988 if (!RD->hasAttr<ConsumableAttr>()) { 989 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) << 990 RD->getNameAsString(); 991 992 return false; 993 } 994 } 995 996 return true; 997 } 998 999 static void handleCallableWhenAttr(Sema &S, Decl *D, 1000 const AttributeList &Attr) { 1001 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 1002 return; 1003 1004 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 1005 return; 1006 1007 SmallVector<CallableWhenAttr::ConsumedState, 3> States; 1008 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) { 1009 CallableWhenAttr::ConsumedState CallableState; 1010 1011 StringRef StateString; 1012 SourceLocation Loc; 1013 if (Attr.isArgIdent(ArgIndex)) { 1014 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex); 1015 StateString = Ident->Ident->getName(); 1016 Loc = Ident->Loc; 1017 } else { 1018 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc)) 1019 return; 1020 } 1021 1022 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString, 1023 CallableState)) { 1024 S.Diag(Loc, diag::warn_attribute_type_not_supported) 1025 << Attr.getName() << StateString; 1026 return; 1027 } 1028 1029 States.push_back(CallableState); 1030 } 1031 1032 D->addAttr(::new (S.Context) 1033 CallableWhenAttr(Attr.getRange(), S.Context, States.data(), 1034 States.size(), Attr.getAttributeSpellingListIndex())); 1035 } 1036 1037 static void handleParamTypestateAttr(Sema &S, Decl *D, 1038 const AttributeList &Attr) { 1039 ParamTypestateAttr::ConsumedState ParamState; 1040 1041 if (Attr.isArgIdent(0)) { 1042 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 1043 StringRef StateString = Ident->Ident->getName(); 1044 1045 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString, 1046 ParamState)) { 1047 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 1048 << Attr.getName() << StateString; 1049 return; 1050 } 1051 } else { 1052 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 1053 Attr.getName() << AANT_ArgumentIdentifier; 1054 return; 1055 } 1056 1057 // FIXME: This check is currently being done in the analysis. It can be 1058 // enabled here only after the parser propagates attributes at 1059 // template specialization definition, not declaration. 1060 //QualType ReturnType = cast<ParmVarDecl>(D)->getType(); 1061 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 1062 // 1063 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 1064 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << 1065 // ReturnType.getAsString(); 1066 // return; 1067 //} 1068 1069 D->addAttr(::new (S.Context) 1070 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState, 1071 Attr.getAttributeSpellingListIndex())); 1072 } 1073 1074 static void handleReturnTypestateAttr(Sema &S, Decl *D, 1075 const AttributeList &Attr) { 1076 ReturnTypestateAttr::ConsumedState ReturnState; 1077 1078 if (Attr.isArgIdent(0)) { 1079 IdentifierLoc *IL = Attr.getArgAsIdent(0); 1080 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(), 1081 ReturnState)) { 1082 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) 1083 << Attr.getName() << IL->Ident; 1084 return; 1085 } 1086 } else { 1087 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 1088 Attr.getName() << AANT_ArgumentIdentifier; 1089 return; 1090 } 1091 1092 // FIXME: This check is currently being done in the analysis. It can be 1093 // enabled here only after the parser propagates attributes at 1094 // template specialization definition, not declaration. 1095 //QualType ReturnType; 1096 // 1097 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) { 1098 // ReturnType = Param->getType(); 1099 // 1100 //} else if (const CXXConstructorDecl *Constructor = 1101 // dyn_cast<CXXConstructorDecl>(D)) { 1102 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType(); 1103 // 1104 //} else { 1105 // 1106 // ReturnType = cast<FunctionDecl>(D)->getCallResultType(); 1107 //} 1108 // 1109 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 1110 // 1111 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 1112 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << 1113 // ReturnType.getAsString(); 1114 // return; 1115 //} 1116 1117 D->addAttr(::new (S.Context) 1118 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState, 1119 Attr.getAttributeSpellingListIndex())); 1120 } 1121 1122 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1123 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 1124 return; 1125 1126 SetTypestateAttr::ConsumedState NewState; 1127 if (Attr.isArgIdent(0)) { 1128 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 1129 StringRef Param = Ident->Ident->getName(); 1130 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) { 1131 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 1132 << Attr.getName() << Param; 1133 return; 1134 } 1135 } else { 1136 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 1137 Attr.getName() << AANT_ArgumentIdentifier; 1138 return; 1139 } 1140 1141 D->addAttr(::new (S.Context) 1142 SetTypestateAttr(Attr.getRange(), S.Context, NewState, 1143 Attr.getAttributeSpellingListIndex())); 1144 } 1145 1146 static void handleTestTypestateAttr(Sema &S, Decl *D, 1147 const AttributeList &Attr) { 1148 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 1149 return; 1150 1151 TestTypestateAttr::ConsumedState TestState; 1152 if (Attr.isArgIdent(0)) { 1153 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 1154 StringRef Param = Ident->Ident->getName(); 1155 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) { 1156 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 1157 << Attr.getName() << Param; 1158 return; 1159 } 1160 } else { 1161 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 1162 Attr.getName() << AANT_ArgumentIdentifier; 1163 return; 1164 } 1165 1166 D->addAttr(::new (S.Context) 1167 TestTypestateAttr(Attr.getRange(), S.Context, TestState, 1168 Attr.getAttributeSpellingListIndex())); 1169 } 1170 1171 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D, 1172 const AttributeList &Attr) { 1173 // Remember this typedef decl, we will need it later for diagnostics. 1174 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D)); 1175 } 1176 1177 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1178 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1179 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context, 1180 Attr.getAttributeSpellingListIndex())); 1181 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1182 // Report warning about changed offset in the newer compiler versions. 1183 if (!FD->getType()->isDependentType() && 1184 !FD->getType()->isIncompleteType() && FD->isBitField() && 1185 S.Context.getTypeAlign(FD->getType()) <= 8) 1186 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield); 1187 1188 FD->addAttr(::new (S.Context) PackedAttr( 1189 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1190 } else 1191 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1192 } 1193 1194 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) { 1195 // The IBOutlet/IBOutletCollection attributes only apply to instance 1196 // variables or properties of Objective-C classes. The outlet must also 1197 // have an object reference type. 1198 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) { 1199 if (!VD->getType()->getAs<ObjCObjectPointerType>()) { 1200 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type) 1201 << Attr.getName() << VD->getType() << 0; 1202 return false; 1203 } 1204 } 1205 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) { 1206 if (!PD->getType()->getAs<ObjCObjectPointerType>()) { 1207 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type) 1208 << Attr.getName() << PD->getType() << 1; 1209 return false; 1210 } 1211 } 1212 else { 1213 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName(); 1214 return false; 1215 } 1216 1217 return true; 1218 } 1219 1220 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) { 1221 if (!checkIBOutletCommon(S, D, Attr)) 1222 return; 1223 1224 D->addAttr(::new (S.Context) 1225 IBOutletAttr(Attr.getRange(), S.Context, 1226 Attr.getAttributeSpellingListIndex())); 1227 } 1228 1229 static void handleIBOutletCollection(Sema &S, Decl *D, 1230 const AttributeList &Attr) { 1231 1232 // The iboutletcollection attribute can have zero or one arguments. 1233 if (Attr.getNumArgs() > 1) { 1234 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 1235 << Attr.getName() << 1; 1236 return; 1237 } 1238 1239 if (!checkIBOutletCommon(S, D, Attr)) 1240 return; 1241 1242 ParsedType PT; 1243 1244 if (Attr.hasParsedType()) 1245 PT = Attr.getTypeArg(); 1246 else { 1247 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(), 1248 S.getScopeForContext(D->getDeclContext()->getParent())); 1249 if (!PT) { 1250 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject"; 1251 return; 1252 } 1253 } 1254 1255 TypeSourceInfo *QTLoc = nullptr; 1256 QualType QT = S.GetTypeFromParser(PT, &QTLoc); 1257 if (!QTLoc) 1258 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc()); 1259 1260 // Diagnose use of non-object type in iboutletcollection attribute. 1261 // FIXME. Gnu attribute extension ignores use of builtin types in 1262 // attributes. So, __attribute__((iboutletcollection(char))) will be 1263 // treated as __attribute__((iboutletcollection())). 1264 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) { 1265 S.Diag(Attr.getLoc(), 1266 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype 1267 : diag::err_iboutletcollection_type) << QT; 1268 return; 1269 } 1270 1271 D->addAttr(::new (S.Context) 1272 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc, 1273 Attr.getAttributeSpellingListIndex())); 1274 } 1275 1276 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) { 1277 if (RefOkay) { 1278 if (T->isReferenceType()) 1279 return true; 1280 } else { 1281 T = T.getNonReferenceType(); 1282 } 1283 1284 // The nonnull attribute, and other similar attributes, can be applied to a 1285 // transparent union that contains a pointer type. 1286 if (const RecordType *UT = T->getAsUnionType()) { 1287 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) { 1288 RecordDecl *UD = UT->getDecl(); 1289 for (const auto *I : UD->fields()) { 1290 QualType QT = I->getType(); 1291 if (QT->isAnyPointerType() || QT->isBlockPointerType()) 1292 return true; 1293 } 1294 } 1295 } 1296 1297 return T->isAnyPointerType() || T->isBlockPointerType(); 1298 } 1299 1300 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr, 1301 SourceRange AttrParmRange, 1302 SourceRange TypeRange, 1303 bool isReturnValue = false) { 1304 if (!S.isValidPointerAttrType(T)) { 1305 if (isReturnValue) 1306 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only) 1307 << Attr.getName() << AttrParmRange << TypeRange; 1308 else 1309 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only) 1310 << Attr.getName() << AttrParmRange << TypeRange << 0; 1311 return false; 1312 } 1313 return true; 1314 } 1315 1316 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1317 SmallVector<unsigned, 8> NonNullArgs; 1318 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) { 1319 Expr *Ex = Attr.getArgAsExpr(I); 1320 uint64_t Idx; 1321 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx)) 1322 return; 1323 1324 // Is the function argument a pointer type? 1325 if (Idx < getFunctionOrMethodNumParams(D) && 1326 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr, 1327 Ex->getSourceRange(), 1328 getFunctionOrMethodParamRange(D, Idx))) 1329 continue; 1330 1331 NonNullArgs.push_back(Idx); 1332 } 1333 1334 // If no arguments were specified to __attribute__((nonnull)) then all pointer 1335 // arguments have a nonnull attribute; warn if there aren't any. Skip this 1336 // check if the attribute came from a macro expansion or a template 1337 // instantiation. 1338 if (NonNullArgs.empty() && Attr.getLoc().isFileID() && 1339 S.ActiveTemplateInstantiations.empty()) { 1340 bool AnyPointers = isFunctionOrMethodVariadic(D); 1341 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); 1342 I != E && !AnyPointers; ++I) { 1343 QualType T = getFunctionOrMethodParamType(D, I); 1344 if (T->isDependentType() || S.isValidPointerAttrType(T)) 1345 AnyPointers = true; 1346 } 1347 1348 if (!AnyPointers) 1349 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers); 1350 } 1351 1352 unsigned *Start = NonNullArgs.data(); 1353 unsigned Size = NonNullArgs.size(); 1354 llvm::array_pod_sort(Start, Start + Size); 1355 D->addAttr(::new (S.Context) 1356 NonNullAttr(Attr.getRange(), S.Context, Start, Size, 1357 Attr.getAttributeSpellingListIndex())); 1358 } 1359 1360 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D, 1361 const AttributeList &Attr) { 1362 if (Attr.getNumArgs() > 0) { 1363 if (D->getFunctionType()) { 1364 handleNonNullAttr(S, D, Attr); 1365 } else { 1366 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args) 1367 << D->getSourceRange(); 1368 } 1369 return; 1370 } 1371 1372 // Is the argument a pointer type? 1373 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(), 1374 D->getSourceRange())) 1375 return; 1376 1377 D->addAttr(::new (S.Context) 1378 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0, 1379 Attr.getAttributeSpellingListIndex())); 1380 } 1381 1382 static void handleReturnsNonNullAttr(Sema &S, Decl *D, 1383 const AttributeList &Attr) { 1384 QualType ResultType = getFunctionOrMethodResultType(D); 1385 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1386 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR, 1387 /* isReturnValue */ true)) 1388 return; 1389 1390 D->addAttr(::new (S.Context) 1391 ReturnsNonNullAttr(Attr.getRange(), S.Context, 1392 Attr.getAttributeSpellingListIndex())); 1393 } 1394 1395 static void handleAssumeAlignedAttr(Sema &S, Decl *D, 1396 const AttributeList &Attr) { 1397 Expr *E = Attr.getArgAsExpr(0), 1398 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr; 1399 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE, 1400 Attr.getAttributeSpellingListIndex()); 1401 } 1402 1403 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 1404 Expr *OE, unsigned SpellingListIndex) { 1405 QualType ResultType = getFunctionOrMethodResultType(D); 1406 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1407 1408 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex); 1409 SourceLocation AttrLoc = AttrRange.getBegin(); 1410 1411 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) { 1412 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) 1413 << &TmpAttr << AttrRange << SR; 1414 return; 1415 } 1416 1417 if (!E->isValueDependent()) { 1418 llvm::APSInt I(64); 1419 if (!E->isIntegerConstantExpr(I, Context)) { 1420 if (OE) 1421 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1422 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant 1423 << E->getSourceRange(); 1424 else 1425 Diag(AttrLoc, diag::err_attribute_argument_type) 1426 << &TmpAttr << AANT_ArgumentIntegerConstant 1427 << E->getSourceRange(); 1428 return; 1429 } 1430 1431 if (!I.isPowerOf2()) { 1432 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 1433 << E->getSourceRange(); 1434 return; 1435 } 1436 } 1437 1438 if (OE) { 1439 if (!OE->isValueDependent()) { 1440 llvm::APSInt I(64); 1441 if (!OE->isIntegerConstantExpr(I, Context)) { 1442 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1443 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant 1444 << OE->getSourceRange(); 1445 return; 1446 } 1447 } 1448 } 1449 1450 D->addAttr(::new (Context) 1451 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex)); 1452 } 1453 1454 /// Normalize the attribute, __foo__ becomes foo. 1455 /// Returns true if normalization was applied. 1456 static bool normalizeName(StringRef &AttrName) { 1457 if (AttrName.size() > 4 && AttrName.startswith("__") && 1458 AttrName.endswith("__")) { 1459 AttrName = AttrName.drop_front(2).drop_back(2); 1460 return true; 1461 } 1462 return false; 1463 } 1464 1465 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) { 1466 // This attribute must be applied to a function declaration. The first 1467 // argument to the attribute must be an identifier, the name of the resource, 1468 // for example: malloc. The following arguments must be argument indexes, the 1469 // arguments must be of integer type for Returns, otherwise of pointer type. 1470 // The difference between Holds and Takes is that a pointer may still be used 1471 // after being held. free() should be __attribute((ownership_takes)), whereas 1472 // a list append function may well be __attribute((ownership_holds)). 1473 1474 if (!AL.isArgIdent(0)) { 1475 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 1476 << AL.getName() << 1 << AANT_ArgumentIdentifier; 1477 return; 1478 } 1479 1480 // Figure out our Kind. 1481 OwnershipAttr::OwnershipKind K = 1482 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0, 1483 AL.getAttributeSpellingListIndex()).getOwnKind(); 1484 1485 // Check arguments. 1486 switch (K) { 1487 case OwnershipAttr::Takes: 1488 case OwnershipAttr::Holds: 1489 if (AL.getNumArgs() < 2) { 1490 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) 1491 << AL.getName() << 2; 1492 return; 1493 } 1494 break; 1495 case OwnershipAttr::Returns: 1496 if (AL.getNumArgs() > 2) { 1497 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) 1498 << AL.getName() << 1; 1499 return; 1500 } 1501 break; 1502 } 1503 1504 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident; 1505 1506 StringRef ModuleName = Module->getName(); 1507 if (normalizeName(ModuleName)) { 1508 Module = &S.PP.getIdentifierTable().get(ModuleName); 1509 } 1510 1511 SmallVector<unsigned, 8> OwnershipArgs; 1512 for (unsigned i = 1; i < AL.getNumArgs(); ++i) { 1513 Expr *Ex = AL.getArgAsExpr(i); 1514 uint64_t Idx; 1515 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx)) 1516 return; 1517 1518 // Is the function argument a pointer type? 1519 QualType T = getFunctionOrMethodParamType(D, Idx); 1520 int Err = -1; // No error 1521 switch (K) { 1522 case OwnershipAttr::Takes: 1523 case OwnershipAttr::Holds: 1524 if (!T->isAnyPointerType() && !T->isBlockPointerType()) 1525 Err = 0; 1526 break; 1527 case OwnershipAttr::Returns: 1528 if (!T->isIntegerType()) 1529 Err = 1; 1530 break; 1531 } 1532 if (-1 != Err) { 1533 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err 1534 << Ex->getSourceRange(); 1535 return; 1536 } 1537 1538 // Check we don't have a conflict with another ownership attribute. 1539 for (const auto *I : D->specific_attrs<OwnershipAttr>()) { 1540 // Cannot have two ownership attributes of different kinds for the same 1541 // index. 1542 if (I->getOwnKind() != K && I->args_end() != 1543 std::find(I->args_begin(), I->args_end(), Idx)) { 1544 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) 1545 << AL.getName() << I; 1546 return; 1547 } else if (K == OwnershipAttr::Returns && 1548 I->getOwnKind() == OwnershipAttr::Returns) { 1549 // A returns attribute conflicts with any other returns attribute using 1550 // a different index. Note, diagnostic reporting is 1-based, but stored 1551 // argument indexes are 0-based. 1552 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) { 1553 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch) 1554 << *(I->args_begin()) + 1; 1555 if (I->args_size()) 1556 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch) 1557 << (unsigned)Idx + 1 << Ex->getSourceRange(); 1558 return; 1559 } 1560 } 1561 } 1562 OwnershipArgs.push_back(Idx); 1563 } 1564 1565 unsigned* start = OwnershipArgs.data(); 1566 unsigned size = OwnershipArgs.size(); 1567 llvm::array_pod_sort(start, start + size); 1568 1569 D->addAttr(::new (S.Context) 1570 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size, 1571 AL.getAttributeSpellingListIndex())); 1572 } 1573 1574 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1575 // Check the attribute arguments. 1576 if (Attr.getNumArgs() > 1) { 1577 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 1578 << Attr.getName() << 1; 1579 return; 1580 } 1581 1582 NamedDecl *nd = cast<NamedDecl>(D); 1583 1584 // gcc rejects 1585 // class c { 1586 // static int a __attribute__((weakref ("v2"))); 1587 // static int b() __attribute__((weakref ("f3"))); 1588 // }; 1589 // and ignores the attributes of 1590 // void f(void) { 1591 // static int a __attribute__((weakref ("v2"))); 1592 // } 1593 // we reject them 1594 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext(); 1595 if (!Ctx->isFileContext()) { 1596 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) 1597 << nd; 1598 return; 1599 } 1600 1601 // The GCC manual says 1602 // 1603 // At present, a declaration to which `weakref' is attached can only 1604 // be `static'. 1605 // 1606 // It also says 1607 // 1608 // Without a TARGET, 1609 // given as an argument to `weakref' or to `alias', `weakref' is 1610 // equivalent to `weak'. 1611 // 1612 // gcc 4.4.1 will accept 1613 // int a7 __attribute__((weakref)); 1614 // as 1615 // int a7 __attribute__((weak)); 1616 // This looks like a bug in gcc. We reject that for now. We should revisit 1617 // it if this behaviour is actually used. 1618 1619 // GCC rejects 1620 // static ((alias ("y"), weakref)). 1621 // Should we? How to check that weakref is before or after alias? 1622 1623 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead 1624 // of transforming it into an AliasAttr. The WeakRefAttr never uses the 1625 // StringRef parameter it was given anyway. 1626 StringRef Str; 1627 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1628 // GCC will accept anything as the argument of weakref. Should we 1629 // check for an existing decl? 1630 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str, 1631 Attr.getAttributeSpellingListIndex())); 1632 1633 D->addAttr(::new (S.Context) 1634 WeakRefAttr(Attr.getRange(), S.Context, 1635 Attr.getAttributeSpellingListIndex())); 1636 } 1637 1638 static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1639 StringRef Str; 1640 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1641 return; 1642 1643 // Aliases should be on declarations, not definitions. 1644 const auto *FD = cast<FunctionDecl>(D); 1645 if (FD->isThisDeclarationADefinition()) { 1646 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1; 1647 return; 1648 } 1649 // FIXME: it should be handled as a target specific attribute. 1650 if (S.Context.getTargetInfo().getTriple().getObjectFormat() != 1651 llvm::Triple::ELF) { 1652 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1653 return; 1654 } 1655 1656 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str, 1657 Attr.getAttributeSpellingListIndex())); 1658 } 1659 1660 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1661 StringRef Str; 1662 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1663 return; 1664 1665 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 1666 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin); 1667 return; 1668 } 1669 if (S.Context.getTargetInfo().getTriple().isNVPTX()) { 1670 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx); 1671 } 1672 1673 // Aliases should be on declarations, not definitions. 1674 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 1675 if (FD->isThisDeclarationADefinition()) { 1676 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0; 1677 return; 1678 } 1679 } else { 1680 const auto *VD = cast<VarDecl>(D); 1681 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) { 1682 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0; 1683 return; 1684 } 1685 } 1686 1687 // FIXME: check if target symbol exists in current file 1688 1689 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str, 1690 Attr.getAttributeSpellingListIndex())); 1691 } 1692 1693 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1694 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName())) 1695 return; 1696 1697 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context, 1698 Attr.getAttributeSpellingListIndex())); 1699 } 1700 1701 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1702 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName())) 1703 return; 1704 1705 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context, 1706 Attr.getAttributeSpellingListIndex())); 1707 } 1708 1709 static void handleTLSModelAttr(Sema &S, Decl *D, 1710 const AttributeList &Attr) { 1711 StringRef Model; 1712 SourceLocation LiteralLoc; 1713 // Check that it is a string. 1714 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc)) 1715 return; 1716 1717 // Check that the value. 1718 if (Model != "global-dynamic" && Model != "local-dynamic" 1719 && Model != "initial-exec" && Model != "local-exec") { 1720 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg); 1721 return; 1722 } 1723 1724 D->addAttr(::new (S.Context) 1725 TLSModelAttr(Attr.getRange(), S.Context, Model, 1726 Attr.getAttributeSpellingListIndex())); 1727 } 1728 1729 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1730 QualType ResultType = getFunctionOrMethodResultType(D); 1731 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) { 1732 D->addAttr(::new (S.Context) RestrictAttr( 1733 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1734 return; 1735 } 1736 1737 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only) 1738 << Attr.getName() << getFunctionOrMethodResultSourceRange(D); 1739 } 1740 1741 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1742 if (S.LangOpts.CPlusPlus) { 1743 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 1744 << Attr.getName() << AttributeLangSupport::Cpp; 1745 return; 1746 } 1747 1748 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(), 1749 Attr.getAttributeSpellingListIndex())) 1750 D->addAttr(CA); 1751 } 1752 1753 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1754 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(), 1755 Attr.getName())) 1756 return; 1757 1758 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context, 1759 Attr.getAttributeSpellingListIndex())); 1760 } 1761 1762 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) { 1763 if (hasDeclarator(D)) return; 1764 1765 if (S.CheckNoReturnAttr(attr)) return; 1766 1767 if (!isa<ObjCMethodDecl>(D)) { 1768 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type) 1769 << attr.getName() << ExpectedFunctionOrMethod; 1770 return; 1771 } 1772 1773 D->addAttr(::new (S.Context) 1774 NoReturnAttr(attr.getRange(), S.Context, 1775 attr.getAttributeSpellingListIndex())); 1776 } 1777 1778 bool Sema::CheckNoReturnAttr(const AttributeList &attr) { 1779 if (!checkAttributeNumArgs(*this, attr, 0)) { 1780 attr.setInvalid(); 1781 return true; 1782 } 1783 1784 return false; 1785 } 1786 1787 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, 1788 const AttributeList &Attr) { 1789 1790 // The checking path for 'noreturn' and 'analyzer_noreturn' are different 1791 // because 'analyzer_noreturn' does not impact the type. 1792 if (!isFunctionOrMethodOrBlock(D)) { 1793 ValueDecl *VD = dyn_cast<ValueDecl>(D); 1794 if (!VD || (!VD->getType()->isBlockPointerType() && 1795 !VD->getType()->isFunctionPointerType())) { 1796 S.Diag(Attr.getLoc(), 1797 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type 1798 : diag::warn_attribute_wrong_decl_type) 1799 << Attr.getName() << ExpectedFunctionMethodOrBlock; 1800 return; 1801 } 1802 } 1803 1804 D->addAttr(::new (S.Context) 1805 AnalyzerNoReturnAttr(Attr.getRange(), S.Context, 1806 Attr.getAttributeSpellingListIndex())); 1807 } 1808 1809 // PS3 PPU-specific. 1810 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1811 /* 1812 Returning a Vector Class in Registers 1813 1814 According to the PPU ABI specifications, a class with a single member of 1815 vector type is returned in memory when used as the return value of a function. 1816 This results in inefficient code when implementing vector classes. To return 1817 the value in a single vector register, add the vecreturn attribute to the 1818 class definition. This attribute is also applicable to struct types. 1819 1820 Example: 1821 1822 struct Vector 1823 { 1824 __vector float xyzw; 1825 } __attribute__((vecreturn)); 1826 1827 Vector Add(Vector lhs, Vector rhs) 1828 { 1829 Vector result; 1830 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw); 1831 return result; // This will be returned in a register 1832 } 1833 */ 1834 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) { 1835 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A; 1836 return; 1837 } 1838 1839 RecordDecl *record = cast<RecordDecl>(D); 1840 int count = 0; 1841 1842 if (!isa<CXXRecordDecl>(record)) { 1843 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 1844 return; 1845 } 1846 1847 if (!cast<CXXRecordDecl>(record)->isPOD()) { 1848 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record); 1849 return; 1850 } 1851 1852 for (const auto *I : record->fields()) { 1853 if ((count == 1) || !I->getType()->isVectorType()) { 1854 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 1855 return; 1856 } 1857 count++; 1858 } 1859 1860 D->addAttr(::new (S.Context) 1861 VecReturnAttr(Attr.getRange(), S.Context, 1862 Attr.getAttributeSpellingListIndex())); 1863 } 1864 1865 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D, 1866 const AttributeList &Attr) { 1867 if (isa<ParmVarDecl>(D)) { 1868 // [[carries_dependency]] can only be applied to a parameter if it is a 1869 // parameter of a function declaration or lambda. 1870 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) { 1871 S.Diag(Attr.getLoc(), 1872 diag::err_carries_dependency_param_not_function_decl); 1873 return; 1874 } 1875 } 1876 1877 D->addAttr(::new (S.Context) CarriesDependencyAttr( 1878 Attr.getRange(), S.Context, 1879 Attr.getAttributeSpellingListIndex())); 1880 } 1881 1882 static void handleNotTailCalledAttr(Sema &S, Decl *D, 1883 const AttributeList &Attr) { 1884 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(), 1885 Attr.getName())) 1886 return; 1887 1888 D->addAttr(::new (S.Context) NotTailCalledAttr( 1889 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1890 } 1891 1892 static void handleDisableTailCallsAttr(Sema &S, Decl *D, 1893 const AttributeList &Attr) { 1894 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(), 1895 Attr.getName())) 1896 return; 1897 1898 D->addAttr(::new (S.Context) DisableTailCallsAttr( 1899 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1900 } 1901 1902 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1903 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1904 if (VD->hasLocalStorage()) { 1905 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1906 return; 1907 } 1908 } else if (!isFunctionOrMethod(D)) { 1909 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 1910 << Attr.getName() << ExpectedVariableOrFunction; 1911 return; 1912 } 1913 1914 D->addAttr(::new (S.Context) 1915 UsedAttr(Attr.getRange(), S.Context, 1916 Attr.getAttributeSpellingListIndex())); 1917 } 1918 1919 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1920 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName(); 1921 1922 if (IsCXX1zAttr && isa<VarDecl>(D)) { 1923 // The C++1z spelling of this attribute cannot be applied to a static data 1924 // member per [dcl.attr.unused]p2. 1925 if (cast<VarDecl>(D)->isStaticDataMember()) { 1926 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 1927 << Attr.getName() << ExpectedForMaybeUnused; 1928 return; 1929 } 1930 } 1931 1932 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn 1933 // about using it as an extension. 1934 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr) 1935 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName(); 1936 1937 D->addAttr(::new (S.Context) UnusedAttr( 1938 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1939 } 1940 1941 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1942 uint32_t priority = ConstructorAttr::DefaultPriority; 1943 if (Attr.getNumArgs() && 1944 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority)) 1945 return; 1946 1947 D->addAttr(::new (S.Context) 1948 ConstructorAttr(Attr.getRange(), S.Context, priority, 1949 Attr.getAttributeSpellingListIndex())); 1950 } 1951 1952 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1953 uint32_t priority = DestructorAttr::DefaultPriority; 1954 if (Attr.getNumArgs() && 1955 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority)) 1956 return; 1957 1958 D->addAttr(::new (S.Context) 1959 DestructorAttr(Attr.getRange(), S.Context, priority, 1960 Attr.getAttributeSpellingListIndex())); 1961 } 1962 1963 template <typename AttrTy> 1964 static void handleAttrWithMessage(Sema &S, Decl *D, 1965 const AttributeList &Attr) { 1966 // Handle the case where the attribute has a text message. 1967 StringRef Str; 1968 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1969 return; 1970 1971 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str, 1972 Attr.getAttributeSpellingListIndex())); 1973 } 1974 1975 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D, 1976 const AttributeList &Attr) { 1977 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) { 1978 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition) 1979 << Attr.getName() << Attr.getRange(); 1980 return; 1981 } 1982 1983 D->addAttr(::new (S.Context) 1984 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context, 1985 Attr.getAttributeSpellingListIndex())); 1986 } 1987 1988 static bool checkAvailabilityAttr(Sema &S, SourceRange Range, 1989 IdentifierInfo *Platform, 1990 VersionTuple Introduced, 1991 VersionTuple Deprecated, 1992 VersionTuple Obsoleted) { 1993 StringRef PlatformName 1994 = AvailabilityAttr::getPrettyPlatformName(Platform->getName()); 1995 if (PlatformName.empty()) 1996 PlatformName = Platform->getName(); 1997 1998 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all 1999 // of these steps are needed). 2000 if (!Introduced.empty() && !Deprecated.empty() && 2001 !(Introduced <= Deprecated)) { 2002 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 2003 << 1 << PlatformName << Deprecated.getAsString() 2004 << 0 << Introduced.getAsString(); 2005 return true; 2006 } 2007 2008 if (!Introduced.empty() && !Obsoleted.empty() && 2009 !(Introduced <= Obsoleted)) { 2010 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 2011 << 2 << PlatformName << Obsoleted.getAsString() 2012 << 0 << Introduced.getAsString(); 2013 return true; 2014 } 2015 2016 if (!Deprecated.empty() && !Obsoleted.empty() && 2017 !(Deprecated <= Obsoleted)) { 2018 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 2019 << 2 << PlatformName << Obsoleted.getAsString() 2020 << 1 << Deprecated.getAsString(); 2021 return true; 2022 } 2023 2024 return false; 2025 } 2026 2027 /// \brief Check whether the two versions match. 2028 /// 2029 /// If either version tuple is empty, then they are assumed to match. If 2030 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y. 2031 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y, 2032 bool BeforeIsOkay) { 2033 if (X.empty() || Y.empty()) 2034 return true; 2035 2036 if (X == Y) 2037 return true; 2038 2039 if (BeforeIsOkay && X < Y) 2040 return true; 2041 2042 return false; 2043 } 2044 2045 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, 2046 IdentifierInfo *Platform, 2047 bool Implicit, 2048 VersionTuple Introduced, 2049 VersionTuple Deprecated, 2050 VersionTuple Obsoleted, 2051 bool IsUnavailable, 2052 StringRef Message, 2053 bool IsStrict, 2054 StringRef Replacement, 2055 AvailabilityMergeKind AMK, 2056 unsigned AttrSpellingListIndex) { 2057 VersionTuple MergedIntroduced = Introduced; 2058 VersionTuple MergedDeprecated = Deprecated; 2059 VersionTuple MergedObsoleted = Obsoleted; 2060 bool FoundAny = false; 2061 bool OverrideOrImpl = false; 2062 switch (AMK) { 2063 case AMK_None: 2064 case AMK_Redeclaration: 2065 OverrideOrImpl = false; 2066 break; 2067 2068 case AMK_Override: 2069 case AMK_ProtocolImplementation: 2070 OverrideOrImpl = true; 2071 break; 2072 } 2073 2074 if (D->hasAttrs()) { 2075 AttrVec &Attrs = D->getAttrs(); 2076 for (unsigned i = 0, e = Attrs.size(); i != e;) { 2077 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]); 2078 if (!OldAA) { 2079 ++i; 2080 continue; 2081 } 2082 2083 IdentifierInfo *OldPlatform = OldAA->getPlatform(); 2084 if (OldPlatform != Platform) { 2085 ++i; 2086 continue; 2087 } 2088 2089 // If there is an existing availability attribute for this platform that 2090 // is explicit and the new one is implicit use the explicit one and 2091 // discard the new implicit attribute. 2092 if (!OldAA->isImplicit() && Implicit) { 2093 return nullptr; 2094 } 2095 2096 // If there is an existing attribute for this platform that is implicit 2097 // and the new attribute is explicit then erase the old one and 2098 // continue processing the attributes. 2099 if (!Implicit && OldAA->isImplicit()) { 2100 Attrs.erase(Attrs.begin() + i); 2101 --e; 2102 continue; 2103 } 2104 2105 FoundAny = true; 2106 VersionTuple OldIntroduced = OldAA->getIntroduced(); 2107 VersionTuple OldDeprecated = OldAA->getDeprecated(); 2108 VersionTuple OldObsoleted = OldAA->getObsoleted(); 2109 bool OldIsUnavailable = OldAA->getUnavailable(); 2110 2111 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) || 2112 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) || 2113 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) || 2114 !(OldIsUnavailable == IsUnavailable || 2115 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) { 2116 if (OverrideOrImpl) { 2117 int Which = -1; 2118 VersionTuple FirstVersion; 2119 VersionTuple SecondVersion; 2120 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) { 2121 Which = 0; 2122 FirstVersion = OldIntroduced; 2123 SecondVersion = Introduced; 2124 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) { 2125 Which = 1; 2126 FirstVersion = Deprecated; 2127 SecondVersion = OldDeprecated; 2128 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) { 2129 Which = 2; 2130 FirstVersion = Obsoleted; 2131 SecondVersion = OldObsoleted; 2132 } 2133 2134 if (Which == -1) { 2135 Diag(OldAA->getLocation(), 2136 diag::warn_mismatched_availability_override_unavail) 2137 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 2138 << (AMK == AMK_Override); 2139 } else { 2140 Diag(OldAA->getLocation(), 2141 diag::warn_mismatched_availability_override) 2142 << Which 2143 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 2144 << FirstVersion.getAsString() << SecondVersion.getAsString() 2145 << (AMK == AMK_Override); 2146 } 2147 if (AMK == AMK_Override) 2148 Diag(Range.getBegin(), diag::note_overridden_method); 2149 else 2150 Diag(Range.getBegin(), diag::note_protocol_method); 2151 } else { 2152 Diag(OldAA->getLocation(), diag::warn_mismatched_availability); 2153 Diag(Range.getBegin(), diag::note_previous_attribute); 2154 } 2155 2156 Attrs.erase(Attrs.begin() + i); 2157 --e; 2158 continue; 2159 } 2160 2161 VersionTuple MergedIntroduced2 = MergedIntroduced; 2162 VersionTuple MergedDeprecated2 = MergedDeprecated; 2163 VersionTuple MergedObsoleted2 = MergedObsoleted; 2164 2165 if (MergedIntroduced2.empty()) 2166 MergedIntroduced2 = OldIntroduced; 2167 if (MergedDeprecated2.empty()) 2168 MergedDeprecated2 = OldDeprecated; 2169 if (MergedObsoleted2.empty()) 2170 MergedObsoleted2 = OldObsoleted; 2171 2172 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform, 2173 MergedIntroduced2, MergedDeprecated2, 2174 MergedObsoleted2)) { 2175 Attrs.erase(Attrs.begin() + i); 2176 --e; 2177 continue; 2178 } 2179 2180 MergedIntroduced = MergedIntroduced2; 2181 MergedDeprecated = MergedDeprecated2; 2182 MergedObsoleted = MergedObsoleted2; 2183 ++i; 2184 } 2185 } 2186 2187 if (FoundAny && 2188 MergedIntroduced == Introduced && 2189 MergedDeprecated == Deprecated && 2190 MergedObsoleted == Obsoleted) 2191 return nullptr; 2192 2193 // Only create a new attribute if !OverrideOrImpl, but we want to do 2194 // the checking. 2195 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced, 2196 MergedDeprecated, MergedObsoleted) && 2197 !OverrideOrImpl) { 2198 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform, 2199 Introduced, Deprecated, 2200 Obsoleted, IsUnavailable, Message, 2201 IsStrict, Replacement, 2202 AttrSpellingListIndex); 2203 Avail->setImplicit(Implicit); 2204 return Avail; 2205 } 2206 return nullptr; 2207 } 2208 2209 static void handleAvailabilityAttr(Sema &S, Decl *D, 2210 const AttributeList &Attr) { 2211 if (!checkAttributeNumArgs(S, Attr, 1)) 2212 return; 2213 IdentifierLoc *Platform = Attr.getArgAsIdent(0); 2214 unsigned Index = Attr.getAttributeSpellingListIndex(); 2215 2216 IdentifierInfo *II = Platform->Ident; 2217 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty()) 2218 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform) 2219 << Platform->Ident; 2220 2221 NamedDecl *ND = dyn_cast<NamedDecl>(D); 2222 if (!ND) { 2223 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 2224 return; 2225 } 2226 2227 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced(); 2228 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated(); 2229 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted(); 2230 bool IsUnavailable = Attr.getUnavailableLoc().isValid(); 2231 bool IsStrict = Attr.getStrictLoc().isValid(); 2232 StringRef Str; 2233 if (const StringLiteral *SE = 2234 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr())) 2235 Str = SE->getString(); 2236 StringRef Replacement; 2237 if (const StringLiteral *SE = 2238 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr())) 2239 Replacement = SE->getString(); 2240 2241 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II, 2242 false/*Implicit*/, 2243 Introduced.Version, 2244 Deprecated.Version, 2245 Obsoleted.Version, 2246 IsUnavailable, Str, 2247 IsStrict, Replacement, 2248 Sema::AMK_None, 2249 Index); 2250 if (NewAttr) 2251 D->addAttr(NewAttr); 2252 2253 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning 2254 // matches before the start of the watchOS platform. 2255 if (S.Context.getTargetInfo().getTriple().isWatchOS()) { 2256 IdentifierInfo *NewII = nullptr; 2257 if (II->getName() == "ios") 2258 NewII = &S.Context.Idents.get("watchos"); 2259 else if (II->getName() == "ios_app_extension") 2260 NewII = &S.Context.Idents.get("watchos_app_extension"); 2261 2262 if (NewII) { 2263 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple { 2264 if (Version.empty()) 2265 return Version; 2266 auto Major = Version.getMajor(); 2267 auto NewMajor = Major >= 9 ? Major - 7 : 0; 2268 if (NewMajor >= 2) { 2269 if (Version.getMinor().hasValue()) { 2270 if (Version.getSubminor().hasValue()) 2271 return VersionTuple(NewMajor, Version.getMinor().getValue(), 2272 Version.getSubminor().getValue()); 2273 else 2274 return VersionTuple(NewMajor, Version.getMinor().getValue()); 2275 } 2276 } 2277 2278 return VersionTuple(2, 0); 2279 }; 2280 2281 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version); 2282 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version); 2283 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version); 2284 2285 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, 2286 Attr.getRange(), 2287 NewII, 2288 true/*Implicit*/, 2289 NewIntroduced, 2290 NewDeprecated, 2291 NewObsoleted, 2292 IsUnavailable, Str, 2293 IsStrict, 2294 Replacement, 2295 Sema::AMK_None, 2296 Index); 2297 if (NewAttr) 2298 D->addAttr(NewAttr); 2299 } 2300 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) { 2301 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning 2302 // matches before the start of the tvOS platform. 2303 IdentifierInfo *NewII = nullptr; 2304 if (II->getName() == "ios") 2305 NewII = &S.Context.Idents.get("tvos"); 2306 else if (II->getName() == "ios_app_extension") 2307 NewII = &S.Context.Idents.get("tvos_app_extension"); 2308 2309 if (NewII) { 2310 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, 2311 Attr.getRange(), 2312 NewII, 2313 true/*Implicit*/, 2314 Introduced.Version, 2315 Deprecated.Version, 2316 Obsoleted.Version, 2317 IsUnavailable, Str, 2318 IsStrict, 2319 Replacement, 2320 Sema::AMK_None, 2321 Index); 2322 if (NewAttr) 2323 D->addAttr(NewAttr); 2324 } 2325 } 2326 } 2327 2328 template <class T> 2329 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range, 2330 typename T::VisibilityType value, 2331 unsigned attrSpellingListIndex) { 2332 T *existingAttr = D->getAttr<T>(); 2333 if (existingAttr) { 2334 typename T::VisibilityType existingValue = existingAttr->getVisibility(); 2335 if (existingValue == value) 2336 return nullptr; 2337 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility); 2338 S.Diag(range.getBegin(), diag::note_previous_attribute); 2339 D->dropAttr<T>(); 2340 } 2341 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex); 2342 } 2343 2344 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range, 2345 VisibilityAttr::VisibilityType Vis, 2346 unsigned AttrSpellingListIndex) { 2347 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis, 2348 AttrSpellingListIndex); 2349 } 2350 2351 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range, 2352 TypeVisibilityAttr::VisibilityType Vis, 2353 unsigned AttrSpellingListIndex) { 2354 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis, 2355 AttrSpellingListIndex); 2356 } 2357 2358 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr, 2359 bool isTypeVisibility) { 2360 // Visibility attributes don't mean anything on a typedef. 2361 if (isa<TypedefNameDecl>(D)) { 2362 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored) 2363 << Attr.getName(); 2364 return; 2365 } 2366 2367 // 'type_visibility' can only go on a type or namespace. 2368 if (isTypeVisibility && 2369 !(isa<TagDecl>(D) || 2370 isa<ObjCInterfaceDecl>(D) || 2371 isa<NamespaceDecl>(D))) { 2372 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type) 2373 << Attr.getName() << ExpectedTypeOrNamespace; 2374 return; 2375 } 2376 2377 // Check that the argument is a string literal. 2378 StringRef TypeStr; 2379 SourceLocation LiteralLoc; 2380 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc)) 2381 return; 2382 2383 VisibilityAttr::VisibilityType type; 2384 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) { 2385 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) 2386 << Attr.getName() << TypeStr; 2387 return; 2388 } 2389 2390 // Complain about attempts to use protected visibility on targets 2391 // (like Darwin) that don't support it. 2392 if (type == VisibilityAttr::Protected && 2393 !S.Context.getTargetInfo().hasProtectedVisibility()) { 2394 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility); 2395 type = VisibilityAttr::Default; 2396 } 2397 2398 unsigned Index = Attr.getAttributeSpellingListIndex(); 2399 clang::Attr *newAttr; 2400 if (isTypeVisibility) { 2401 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(), 2402 (TypeVisibilityAttr::VisibilityType) type, 2403 Index); 2404 } else { 2405 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index); 2406 } 2407 if (newAttr) 2408 D->addAttr(newAttr); 2409 } 2410 2411 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl, 2412 const AttributeList &Attr) { 2413 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl); 2414 if (!Attr.isArgIdent(0)) { 2415 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2416 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2417 return; 2418 } 2419 2420 IdentifierLoc *IL = Attr.getArgAsIdent(0); 2421 ObjCMethodFamilyAttr::FamilyKind F; 2422 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) { 2423 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() 2424 << IL->Ident; 2425 return; 2426 } 2427 2428 if (F == ObjCMethodFamilyAttr::OMF_init && 2429 !method->getReturnType()->isObjCObjectPointerType()) { 2430 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type) 2431 << method->getReturnType(); 2432 // Ignore the attribute. 2433 return; 2434 } 2435 2436 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(), 2437 S.Context, F, 2438 Attr.getAttributeSpellingListIndex())); 2439 } 2440 2441 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) { 2442 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 2443 QualType T = TD->getUnderlyingType(); 2444 if (!T->isCARCBridgableType()) { 2445 S.Diag(TD->getLocation(), diag::err_nsobject_attribute); 2446 return; 2447 } 2448 } 2449 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) { 2450 QualType T = PD->getType(); 2451 if (!T->isCARCBridgableType()) { 2452 S.Diag(PD->getLocation(), diag::err_nsobject_attribute); 2453 return; 2454 } 2455 } 2456 else { 2457 // It is okay to include this attribute on properties, e.g.: 2458 // 2459 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); 2460 // 2461 // In this case it follows tradition and suppresses an error in the above 2462 // case. 2463 S.Diag(D->getLocation(), diag::warn_nsobject_attribute); 2464 } 2465 D->addAttr(::new (S.Context) 2466 ObjCNSObjectAttr(Attr.getRange(), S.Context, 2467 Attr.getAttributeSpellingListIndex())); 2468 } 2469 2470 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) { 2471 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 2472 QualType T = TD->getUnderlyingType(); 2473 if (!T->isObjCObjectPointerType()) { 2474 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute); 2475 return; 2476 } 2477 } else { 2478 S.Diag(D->getLocation(), diag::warn_independentclass_attribute); 2479 return; 2480 } 2481 D->addAttr(::new (S.Context) 2482 ObjCIndependentClassAttr(Attr.getRange(), S.Context, 2483 Attr.getAttributeSpellingListIndex())); 2484 } 2485 2486 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2487 if (!Attr.isArgIdent(0)) { 2488 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2489 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2490 return; 2491 } 2492 2493 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident; 2494 BlocksAttr::BlockType type; 2495 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) { 2496 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 2497 << Attr.getName() << II; 2498 return; 2499 } 2500 2501 D->addAttr(::new (S.Context) 2502 BlocksAttr(Attr.getRange(), S.Context, type, 2503 Attr.getAttributeSpellingListIndex())); 2504 } 2505 2506 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2507 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel; 2508 if (Attr.getNumArgs() > 0) { 2509 Expr *E = Attr.getArgAsExpr(0); 2510 llvm::APSInt Idx(32); 2511 if (E->isTypeDependent() || E->isValueDependent() || 2512 !E->isIntegerConstantExpr(Idx, S.Context)) { 2513 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2514 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant 2515 << E->getSourceRange(); 2516 return; 2517 } 2518 2519 if (Idx.isSigned() && Idx.isNegative()) { 2520 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero) 2521 << E->getSourceRange(); 2522 return; 2523 } 2524 2525 sentinel = Idx.getZExtValue(); 2526 } 2527 2528 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos; 2529 if (Attr.getNumArgs() > 1) { 2530 Expr *E = Attr.getArgAsExpr(1); 2531 llvm::APSInt Idx(32); 2532 if (E->isTypeDependent() || E->isValueDependent() || 2533 !E->isIntegerConstantExpr(Idx, S.Context)) { 2534 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2535 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant 2536 << E->getSourceRange(); 2537 return; 2538 } 2539 nullPos = Idx.getZExtValue(); 2540 2541 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) { 2542 // FIXME: This error message could be improved, it would be nice 2543 // to say what the bounds actually are. 2544 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one) 2545 << E->getSourceRange(); 2546 return; 2547 } 2548 } 2549 2550 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2551 const FunctionType *FT = FD->getType()->castAs<FunctionType>(); 2552 if (isa<FunctionNoProtoType>(FT)) { 2553 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments); 2554 return; 2555 } 2556 2557 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2558 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2559 return; 2560 } 2561 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 2562 if (!MD->isVariadic()) { 2563 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2564 return; 2565 } 2566 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 2567 if (!BD->isVariadic()) { 2568 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1; 2569 return; 2570 } 2571 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) { 2572 QualType Ty = V->getType(); 2573 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 2574 const FunctionType *FT = Ty->isFunctionPointerType() 2575 ? D->getFunctionType() 2576 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 2577 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2578 int m = Ty->isFunctionPointerType() ? 0 : 1; 2579 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m; 2580 return; 2581 } 2582 } else { 2583 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2584 << Attr.getName() << ExpectedFunctionMethodOrBlock; 2585 return; 2586 } 2587 } else { 2588 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2589 << Attr.getName() << ExpectedFunctionMethodOrBlock; 2590 return; 2591 } 2592 D->addAttr(::new (S.Context) 2593 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos, 2594 Attr.getAttributeSpellingListIndex())); 2595 } 2596 2597 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) { 2598 if (D->getFunctionType() && 2599 D->getFunctionType()->getReturnType()->isVoidType()) { 2600 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method) 2601 << Attr.getName() << 0; 2602 return; 2603 } 2604 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 2605 if (MD->getReturnType()->isVoidType()) { 2606 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method) 2607 << Attr.getName() << 1; 2608 return; 2609 } 2610 2611 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn 2612 // about using it as an extension. 2613 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() && 2614 !Attr.getScopeName()) 2615 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName(); 2616 2617 D->addAttr(::new (S.Context) 2618 WarnUnusedResultAttr(Attr.getRange(), S.Context, 2619 Attr.getAttributeSpellingListIndex())); 2620 } 2621 2622 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2623 // weak_import only applies to variable & function declarations. 2624 bool isDef = false; 2625 if (!D->canBeWeakImported(isDef)) { 2626 if (isDef) 2627 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition) 2628 << "weak_import"; 2629 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) || 2630 (S.Context.getTargetInfo().getTriple().isOSDarwin() && 2631 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) { 2632 // Nothing to warn about here. 2633 } else 2634 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2635 << Attr.getName() << ExpectedVariableOrFunction; 2636 2637 return; 2638 } 2639 2640 D->addAttr(::new (S.Context) 2641 WeakImportAttr(Attr.getRange(), S.Context, 2642 Attr.getAttributeSpellingListIndex())); 2643 } 2644 2645 // Handles reqd_work_group_size and work_group_size_hint. 2646 template <typename WorkGroupAttr> 2647 static void handleWorkGroupSize(Sema &S, Decl *D, 2648 const AttributeList &Attr) { 2649 uint32_t WGSize[3]; 2650 for (unsigned i = 0; i < 3; ++i) { 2651 const Expr *E = Attr.getArgAsExpr(i); 2652 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i)) 2653 return; 2654 if (WGSize[i] == 0) { 2655 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero) 2656 << Attr.getName() << E->getSourceRange(); 2657 return; 2658 } 2659 } 2660 2661 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>(); 2662 if (Existing && !(Existing->getXDim() == WGSize[0] && 2663 Existing->getYDim() == WGSize[1] && 2664 Existing->getZDim() == WGSize[2])) 2665 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); 2666 2667 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context, 2668 WGSize[0], WGSize[1], WGSize[2], 2669 Attr.getAttributeSpellingListIndex())); 2670 } 2671 2672 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) { 2673 if (!Attr.hasParsedType()) { 2674 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 2675 << Attr.getName() << 1; 2676 return; 2677 } 2678 2679 TypeSourceInfo *ParmTSI = nullptr; 2680 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI); 2681 assert(ParmTSI && "no type source info for attribute argument"); 2682 2683 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() && 2684 (ParmType->isBooleanType() || 2685 !ParmType->isIntegralType(S.getASTContext()))) { 2686 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint) 2687 << ParmType; 2688 return; 2689 } 2690 2691 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) { 2692 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) { 2693 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); 2694 return; 2695 } 2696 } 2697 2698 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context, 2699 ParmTSI, 2700 Attr.getAttributeSpellingListIndex())); 2701 } 2702 2703 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range, 2704 StringRef Name, 2705 unsigned AttrSpellingListIndex) { 2706 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) { 2707 if (ExistingAttr->getName() == Name) 2708 return nullptr; 2709 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section); 2710 Diag(Range.getBegin(), diag::note_previous_attribute); 2711 return nullptr; 2712 } 2713 return ::new (Context) SectionAttr(Range, Context, Name, 2714 AttrSpellingListIndex); 2715 } 2716 2717 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) { 2718 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName); 2719 if (!Error.empty()) { 2720 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error; 2721 return false; 2722 } 2723 return true; 2724 } 2725 2726 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2727 // Make sure that there is a string literal as the sections's single 2728 // argument. 2729 StringRef Str; 2730 SourceLocation LiteralLoc; 2731 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc)) 2732 return; 2733 2734 if (!S.checkSectionName(LiteralLoc, Str)) 2735 return; 2736 2737 // If the target wants to validate the section specifier, make it happen. 2738 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str); 2739 if (!Error.empty()) { 2740 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) 2741 << Error; 2742 return; 2743 } 2744 2745 unsigned Index = Attr.getAttributeSpellingListIndex(); 2746 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index); 2747 if (NewAttr) 2748 D->addAttr(NewAttr); 2749 } 2750 2751 // Check for things we'd like to warn about, no errors or validation for now. 2752 // TODO: Validation should use a backend target library that specifies 2753 // the allowable subtarget features and cpus. We could use something like a 2754 // TargetCodeGenInfo hook here to do validation. 2755 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) { 2756 for (auto Str : {"tune=", "fpmath="}) 2757 if (AttrStr.find(Str) != StringRef::npos) 2758 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str; 2759 } 2760 2761 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2762 StringRef Str; 2763 SourceLocation LiteralLoc; 2764 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc)) 2765 return; 2766 S.checkTargetAttr(LiteralLoc, Str); 2767 unsigned Index = Attr.getAttributeSpellingListIndex(); 2768 TargetAttr *NewAttr = 2769 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index); 2770 D->addAttr(NewAttr); 2771 } 2772 2773 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2774 VarDecl *VD = cast<VarDecl>(D); 2775 if (!VD->hasLocalStorage()) { 2776 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 2777 return; 2778 } 2779 2780 Expr *E = Attr.getArgAsExpr(0); 2781 SourceLocation Loc = E->getExprLoc(); 2782 FunctionDecl *FD = nullptr; 2783 DeclarationNameInfo NI; 2784 2785 // gcc only allows for simple identifiers. Since we support more than gcc, we 2786 // will warn the user. 2787 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 2788 if (DRE->hasQualifier()) 2789 S.Diag(Loc, diag::warn_cleanup_ext); 2790 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 2791 NI = DRE->getNameInfo(); 2792 if (!FD) { 2793 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1 2794 << NI.getName(); 2795 return; 2796 } 2797 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 2798 if (ULE->hasExplicitTemplateArgs()) 2799 S.Diag(Loc, diag::warn_cleanup_ext); 2800 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true); 2801 NI = ULE->getNameInfo(); 2802 if (!FD) { 2803 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2 2804 << NI.getName(); 2805 if (ULE->getType() == S.Context.OverloadTy) 2806 S.NoteAllOverloadCandidates(ULE); 2807 return; 2808 } 2809 } else { 2810 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0; 2811 return; 2812 } 2813 2814 if (FD->getNumParams() != 1) { 2815 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg) 2816 << NI.getName(); 2817 return; 2818 } 2819 2820 // We're currently more strict than GCC about what function types we accept. 2821 // If this ever proves to be a problem it should be easy to fix. 2822 QualType Ty = S.Context.getPointerType(VD->getType()); 2823 QualType ParamTy = FD->getParamDecl(0)->getType(); 2824 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), 2825 ParamTy, Ty) != Sema::Compatible) { 2826 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type) 2827 << NI.getName() << ParamTy << Ty; 2828 return; 2829 } 2830 2831 D->addAttr(::new (S.Context) 2832 CleanupAttr(Attr.getRange(), S.Context, FD, 2833 Attr.getAttributeSpellingListIndex())); 2834 } 2835 2836 /// Handle __attribute__((format_arg((idx)))) attribute based on 2837 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 2838 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2839 Expr *IdxExpr = Attr.getArgAsExpr(0); 2840 uint64_t Idx; 2841 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx)) 2842 return; 2843 2844 // Make sure the format string is really a string. 2845 QualType Ty = getFunctionOrMethodParamType(D, Idx); 2846 2847 bool NotNSStringTy = !isNSStringType(Ty, S.Context); 2848 if (NotNSStringTy && 2849 !isCFStringType(Ty, S.Context) && 2850 (!Ty->isPointerType() || 2851 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { 2852 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2853 << "a string type" << IdxExpr->getSourceRange() 2854 << getFunctionOrMethodParamRange(D, 0); 2855 return; 2856 } 2857 Ty = getFunctionOrMethodResultType(D); 2858 if (!isNSStringType(Ty, S.Context) && 2859 !isCFStringType(Ty, S.Context) && 2860 (!Ty->isPointerType() || 2861 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { 2862 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not) 2863 << (NotNSStringTy ? "string type" : "NSString") 2864 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); 2865 return; 2866 } 2867 2868 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex 2869 // because that has corrected for the implicit this parameter, and is zero- 2870 // based. The attribute expects what the user wrote explicitly. 2871 llvm::APSInt Val; 2872 IdxExpr->EvaluateAsInt(Val, S.Context); 2873 2874 D->addAttr(::new (S.Context) 2875 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(), 2876 Attr.getAttributeSpellingListIndex())); 2877 } 2878 2879 enum FormatAttrKind { 2880 CFStringFormat, 2881 NSStringFormat, 2882 StrftimeFormat, 2883 SupportedFormat, 2884 IgnoredFormat, 2885 InvalidFormat 2886 }; 2887 2888 /// getFormatAttrKind - Map from format attribute names to supported format 2889 /// types. 2890 static FormatAttrKind getFormatAttrKind(StringRef Format) { 2891 return llvm::StringSwitch<FormatAttrKind>(Format) 2892 // Check for formats that get handled specially. 2893 .Case("NSString", NSStringFormat) 2894 .Case("CFString", CFStringFormat) 2895 .Case("strftime", StrftimeFormat) 2896 2897 // Otherwise, check for supported formats. 2898 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat) 2899 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat) 2900 .Case("kprintf", SupportedFormat) // OpenBSD. 2901 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD. 2902 .Case("os_trace", SupportedFormat) 2903 .Case("os_log", SupportedFormat) 2904 2905 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat) 2906 .Default(InvalidFormat); 2907 } 2908 2909 /// Handle __attribute__((init_priority(priority))) attributes based on 2910 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html 2911 static void handleInitPriorityAttr(Sema &S, Decl *D, 2912 const AttributeList &Attr) { 2913 if (!S.getLangOpts().CPlusPlus) { 2914 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 2915 return; 2916 } 2917 2918 if (S.getCurFunctionOrMethodDecl()) { 2919 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr); 2920 Attr.setInvalid(); 2921 return; 2922 } 2923 QualType T = cast<VarDecl>(D)->getType(); 2924 if (S.Context.getAsArrayType(T)) 2925 T = S.Context.getBaseElementType(T); 2926 if (!T->getAs<RecordType>()) { 2927 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr); 2928 Attr.setInvalid(); 2929 return; 2930 } 2931 2932 Expr *E = Attr.getArgAsExpr(0); 2933 uint32_t prioritynum; 2934 if (!checkUInt32Argument(S, Attr, E, prioritynum)) { 2935 Attr.setInvalid(); 2936 return; 2937 } 2938 2939 if (prioritynum < 101 || prioritynum > 65535) { 2940 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range) 2941 << E->getSourceRange() << Attr.getName() << 101 << 65535; 2942 Attr.setInvalid(); 2943 return; 2944 } 2945 D->addAttr(::new (S.Context) 2946 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum, 2947 Attr.getAttributeSpellingListIndex())); 2948 } 2949 2950 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range, 2951 IdentifierInfo *Format, int FormatIdx, 2952 int FirstArg, 2953 unsigned AttrSpellingListIndex) { 2954 // Check whether we already have an equivalent format attribute. 2955 for (auto *F : D->specific_attrs<FormatAttr>()) { 2956 if (F->getType() == Format && 2957 F->getFormatIdx() == FormatIdx && 2958 F->getFirstArg() == FirstArg) { 2959 // If we don't have a valid location for this attribute, adopt the 2960 // location. 2961 if (F->getLocation().isInvalid()) 2962 F->setRange(Range); 2963 return nullptr; 2964 } 2965 } 2966 2967 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx, 2968 FirstArg, AttrSpellingListIndex); 2969 } 2970 2971 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on 2972 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 2973 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2974 if (!Attr.isArgIdent(0)) { 2975 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2976 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2977 return; 2978 } 2979 2980 // In C++ the implicit 'this' function parameter also counts, and they are 2981 // counted from one. 2982 bool HasImplicitThisParam = isInstanceMethod(D); 2983 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam; 2984 2985 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident; 2986 StringRef Format = II->getName(); 2987 2988 if (normalizeName(Format)) { 2989 // If we've modified the string name, we need a new identifier for it. 2990 II = &S.Context.Idents.get(Format); 2991 } 2992 2993 // Check for supported formats. 2994 FormatAttrKind Kind = getFormatAttrKind(Format); 2995 2996 if (Kind == IgnoredFormat) 2997 return; 2998 2999 if (Kind == InvalidFormat) { 3000 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 3001 << Attr.getName() << II->getName(); 3002 return; 3003 } 3004 3005 // checks for the 2nd argument 3006 Expr *IdxExpr = Attr.getArgAsExpr(1); 3007 uint32_t Idx; 3008 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2)) 3009 return; 3010 3011 if (Idx < 1 || Idx > NumArgs) { 3012 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 3013 << Attr.getName() << 2 << IdxExpr->getSourceRange(); 3014 return; 3015 } 3016 3017 // FIXME: Do we need to bounds check? 3018 unsigned ArgIdx = Idx - 1; 3019 3020 if (HasImplicitThisParam) { 3021 if (ArgIdx == 0) { 3022 S.Diag(Attr.getLoc(), 3023 diag::err_format_attribute_implicit_this_format_string) 3024 << IdxExpr->getSourceRange(); 3025 return; 3026 } 3027 ArgIdx--; 3028 } 3029 3030 // make sure the format string is really a string 3031 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx); 3032 3033 if (Kind == CFStringFormat) { 3034 if (!isCFStringType(Ty, S.Context)) { 3035 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 3036 << "a CFString" << IdxExpr->getSourceRange() 3037 << getFunctionOrMethodParamRange(D, ArgIdx); 3038 return; 3039 } 3040 } else if (Kind == NSStringFormat) { 3041 // FIXME: do we need to check if the type is NSString*? What are the 3042 // semantics? 3043 if (!isNSStringType(Ty, S.Context)) { 3044 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 3045 << "an NSString" << IdxExpr->getSourceRange() 3046 << getFunctionOrMethodParamRange(D, ArgIdx); 3047 return; 3048 } 3049 } else if (!Ty->isPointerType() || 3050 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) { 3051 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 3052 << "a string type" << IdxExpr->getSourceRange() 3053 << getFunctionOrMethodParamRange(D, ArgIdx); 3054 return; 3055 } 3056 3057 // check the 3rd argument 3058 Expr *FirstArgExpr = Attr.getArgAsExpr(2); 3059 uint32_t FirstArg; 3060 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3)) 3061 return; 3062 3063 // check if the function is variadic if the 3rd argument non-zero 3064 if (FirstArg != 0) { 3065 if (isFunctionOrMethodVariadic(D)) { 3066 ++NumArgs; // +1 for ... 3067 } else { 3068 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic); 3069 return; 3070 } 3071 } 3072 3073 // strftime requires FirstArg to be 0 because it doesn't read from any 3074 // variable the input is just the current time + the format string. 3075 if (Kind == StrftimeFormat) { 3076 if (FirstArg != 0) { 3077 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter) 3078 << FirstArgExpr->getSourceRange(); 3079 return; 3080 } 3081 // if 0 it disables parameter checking (to use with e.g. va_list) 3082 } else if (FirstArg != 0 && FirstArg != NumArgs) { 3083 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 3084 << Attr.getName() << 3 << FirstArgExpr->getSourceRange(); 3085 return; 3086 } 3087 3088 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II, 3089 Idx, FirstArg, 3090 Attr.getAttributeSpellingListIndex()); 3091 if (NewAttr) 3092 D->addAttr(NewAttr); 3093 } 3094 3095 static void handleTransparentUnionAttr(Sema &S, Decl *D, 3096 const AttributeList &Attr) { 3097 // Try to find the underlying union declaration. 3098 RecordDecl *RD = nullptr; 3099 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D); 3100 if (TD && TD->getUnderlyingType()->isUnionType()) 3101 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl(); 3102 else 3103 RD = dyn_cast<RecordDecl>(D); 3104 3105 if (!RD || !RD->isUnion()) { 3106 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 3107 << Attr.getName() << ExpectedUnion; 3108 return; 3109 } 3110 3111 if (!RD->isCompleteDefinition()) { 3112 S.Diag(Attr.getLoc(), 3113 diag::warn_transparent_union_attribute_not_definition); 3114 return; 3115 } 3116 3117 RecordDecl::field_iterator Field = RD->field_begin(), 3118 FieldEnd = RD->field_end(); 3119 if (Field == FieldEnd) { 3120 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields); 3121 return; 3122 } 3123 3124 FieldDecl *FirstField = *Field; 3125 QualType FirstType = FirstField->getType(); 3126 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) { 3127 S.Diag(FirstField->getLocation(), 3128 diag::warn_transparent_union_attribute_floating) 3129 << FirstType->isVectorType() << FirstType; 3130 return; 3131 } 3132 3133 if (FirstType->isIncompleteType()) 3134 return; 3135 uint64_t FirstSize = S.Context.getTypeSize(FirstType); 3136 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType); 3137 for (; Field != FieldEnd; ++Field) { 3138 QualType FieldType = Field->getType(); 3139 if (FieldType->isIncompleteType()) 3140 return; 3141 // FIXME: this isn't fully correct; we also need to test whether the 3142 // members of the union would all have the same calling convention as the 3143 // first member of the union. Checking just the size and alignment isn't 3144 // sufficient (consider structs passed on the stack instead of in registers 3145 // as an example). 3146 if (S.Context.getTypeSize(FieldType) != FirstSize || 3147 S.Context.getTypeAlign(FieldType) > FirstAlign) { 3148 // Warn if we drop the attribute. 3149 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize; 3150 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType) 3151 : S.Context.getTypeAlign(FieldType); 3152 S.Diag(Field->getLocation(), 3153 diag::warn_transparent_union_attribute_field_size_align) 3154 << isSize << Field->getDeclName() << FieldBits; 3155 unsigned FirstBits = isSize? FirstSize : FirstAlign; 3156 S.Diag(FirstField->getLocation(), 3157 diag::note_transparent_union_first_field_size_align) 3158 << isSize << FirstBits; 3159 return; 3160 } 3161 } 3162 3163 RD->addAttr(::new (S.Context) 3164 TransparentUnionAttr(Attr.getRange(), S.Context, 3165 Attr.getAttributeSpellingListIndex())); 3166 } 3167 3168 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3169 // Make sure that there is a string literal as the annotation's single 3170 // argument. 3171 StringRef Str; 3172 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 3173 return; 3174 3175 // Don't duplicate annotations that are already set. 3176 for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 3177 if (I->getAnnotation() == Str) 3178 return; 3179 } 3180 3181 D->addAttr(::new (S.Context) 3182 AnnotateAttr(Attr.getRange(), S.Context, Str, 3183 Attr.getAttributeSpellingListIndex())); 3184 } 3185 3186 static void handleAlignValueAttr(Sema &S, Decl *D, 3187 const AttributeList &Attr) { 3188 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0), 3189 Attr.getAttributeSpellingListIndex()); 3190 } 3191 3192 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, 3193 unsigned SpellingListIndex) { 3194 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex); 3195 SourceLocation AttrLoc = AttrRange.getBegin(); 3196 3197 QualType T; 3198 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 3199 T = TD->getUnderlyingType(); 3200 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) 3201 T = VD->getType(); 3202 else 3203 llvm_unreachable("Unknown decl type for align_value"); 3204 3205 if (!T->isDependentType() && !T->isAnyPointerType() && 3206 !T->isReferenceType() && !T->isMemberPointerType()) { 3207 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only) 3208 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange(); 3209 return; 3210 } 3211 3212 if (!E->isValueDependent()) { 3213 llvm::APSInt Alignment; 3214 ExprResult ICE 3215 = VerifyIntegerConstantExpression(E, &Alignment, 3216 diag::err_align_value_attribute_argument_not_int, 3217 /*AllowFold*/ false); 3218 if (ICE.isInvalid()) 3219 return; 3220 3221 if (!Alignment.isPowerOf2()) { 3222 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 3223 << E->getSourceRange(); 3224 return; 3225 } 3226 3227 D->addAttr(::new (Context) 3228 AlignValueAttr(AttrRange, Context, ICE.get(), 3229 SpellingListIndex)); 3230 return; 3231 } 3232 3233 // Save dependent expressions in the AST to be instantiated. 3234 D->addAttr(::new (Context) AlignValueAttr(TmpAttr)); 3235 } 3236 3237 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3238 // check the attribute arguments. 3239 if (Attr.getNumArgs() > 1) { 3240 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 3241 << Attr.getName() << 1; 3242 return; 3243 } 3244 3245 if (Attr.getNumArgs() == 0) { 3246 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context, 3247 true, nullptr, Attr.getAttributeSpellingListIndex())); 3248 return; 3249 } 3250 3251 Expr *E = Attr.getArgAsExpr(0); 3252 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) { 3253 S.Diag(Attr.getEllipsisLoc(), 3254 diag::err_pack_expansion_without_parameter_packs); 3255 return; 3256 } 3257 3258 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E)) 3259 return; 3260 3261 if (E->isValueDependent()) { 3262 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) { 3263 if (!TND->getUnderlyingType()->isDependentType()) { 3264 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name) 3265 << E->getSourceRange(); 3266 return; 3267 } 3268 } 3269 } 3270 3271 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(), 3272 Attr.isPackExpansion()); 3273 } 3274 3275 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 3276 unsigned SpellingListIndex, bool IsPackExpansion) { 3277 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex); 3278 SourceLocation AttrLoc = AttrRange.getBegin(); 3279 3280 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements. 3281 if (TmpAttr.isAlignas()) { 3282 // C++11 [dcl.align]p1: 3283 // An alignment-specifier may be applied to a variable or to a class 3284 // data member, but it shall not be applied to a bit-field, a function 3285 // parameter, the formal parameter of a catch clause, or a variable 3286 // declared with the register storage class specifier. An 3287 // alignment-specifier may also be applied to the declaration of a class 3288 // or enumeration type. 3289 // C11 6.7.5/2: 3290 // An alignment attribute shall not be specified in a declaration of 3291 // a typedef, or a bit-field, or a function, or a parameter, or an 3292 // object declared with the register storage-class specifier. 3293 int DiagKind = -1; 3294 if (isa<ParmVarDecl>(D)) { 3295 DiagKind = 0; 3296 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3297 if (VD->getStorageClass() == SC_Register) 3298 DiagKind = 1; 3299 if (VD->isExceptionVariable()) 3300 DiagKind = 2; 3301 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 3302 if (FD->isBitField()) 3303 DiagKind = 3; 3304 } else if (!isa<TagDecl>(D)) { 3305 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr 3306 << (TmpAttr.isC11() ? ExpectedVariableOrField 3307 : ExpectedVariableFieldOrTag); 3308 return; 3309 } 3310 if (DiagKind != -1) { 3311 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type) 3312 << &TmpAttr << DiagKind; 3313 return; 3314 } 3315 } 3316 3317 if (E->isTypeDependent() || E->isValueDependent()) { 3318 // Save dependent expressions in the AST to be instantiated. 3319 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr); 3320 AA->setPackExpansion(IsPackExpansion); 3321 D->addAttr(AA); 3322 return; 3323 } 3324 3325 // FIXME: Cache the number on the Attr object? 3326 llvm::APSInt Alignment; 3327 ExprResult ICE 3328 = VerifyIntegerConstantExpression(E, &Alignment, 3329 diag::err_aligned_attribute_argument_not_int, 3330 /*AllowFold*/ false); 3331 if (ICE.isInvalid()) 3332 return; 3333 3334 uint64_t AlignVal = Alignment.getZExtValue(); 3335 3336 // C++11 [dcl.align]p2: 3337 // -- if the constant expression evaluates to zero, the alignment 3338 // specifier shall have no effect 3339 // C11 6.7.5p6: 3340 // An alignment specification of zero has no effect. 3341 if (!(TmpAttr.isAlignas() && !Alignment)) { 3342 if (!llvm::isPowerOf2_64(AlignVal)) { 3343 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 3344 << E->getSourceRange(); 3345 return; 3346 } 3347 } 3348 3349 // Alignment calculations can wrap around if it's greater than 2**28. 3350 unsigned MaxValidAlignment = 3351 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192 3352 : 268435456; 3353 if (AlignVal > MaxValidAlignment) { 3354 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment 3355 << E->getSourceRange(); 3356 return; 3357 } 3358 3359 if (Context.getTargetInfo().isTLSSupported()) { 3360 unsigned MaxTLSAlign = 3361 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign()) 3362 .getQuantity(); 3363 auto *VD = dyn_cast<VarDecl>(D); 3364 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD && 3365 VD->getTLSKind() != VarDecl::TLS_None) { 3366 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 3367 << (unsigned)AlignVal << VD << MaxTLSAlign; 3368 return; 3369 } 3370 } 3371 3372 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true, 3373 ICE.get(), SpellingListIndex); 3374 AA->setPackExpansion(IsPackExpansion); 3375 D->addAttr(AA); 3376 } 3377 3378 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS, 3379 unsigned SpellingListIndex, bool IsPackExpansion) { 3380 // FIXME: Cache the number on the Attr object if non-dependent? 3381 // FIXME: Perform checking of type validity 3382 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS, 3383 SpellingListIndex); 3384 AA->setPackExpansion(IsPackExpansion); 3385 D->addAttr(AA); 3386 } 3387 3388 void Sema::CheckAlignasUnderalignment(Decl *D) { 3389 assert(D->hasAttrs() && "no attributes on decl"); 3390 3391 QualType UnderlyingTy, DiagTy; 3392 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 3393 UnderlyingTy = DiagTy = VD->getType(); 3394 } else { 3395 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D)); 3396 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) 3397 UnderlyingTy = ED->getIntegerType(); 3398 } 3399 if (DiagTy->isDependentType() || DiagTy->isIncompleteType()) 3400 return; 3401 3402 // C++11 [dcl.align]p5, C11 6.7.5/4: 3403 // The combined effect of all alignment attributes in a declaration shall 3404 // not specify an alignment that is less strict than the alignment that 3405 // would otherwise be required for the entity being declared. 3406 AlignedAttr *AlignasAttr = nullptr; 3407 unsigned Align = 0; 3408 for (auto *I : D->specific_attrs<AlignedAttr>()) { 3409 if (I->isAlignmentDependent()) 3410 return; 3411 if (I->isAlignas()) 3412 AlignasAttr = I; 3413 Align = std::max(Align, I->getAlignment(Context)); 3414 } 3415 3416 if (AlignasAttr && Align) { 3417 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align); 3418 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy); 3419 if (NaturalAlign > RequestedAlign) 3420 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned) 3421 << DiagTy << (unsigned)NaturalAlign.getQuantity(); 3422 } 3423 } 3424 3425 bool Sema::checkMSInheritanceAttrOnDefinition( 3426 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 3427 MSInheritanceAttr::Spelling SemanticSpelling) { 3428 assert(RD->hasDefinition() && "RD has no definition!"); 3429 3430 // We may not have seen base specifiers or any virtual methods yet. We will 3431 // have to wait until the record is defined to catch any mismatches. 3432 if (!RD->getDefinition()->isCompleteDefinition()) 3433 return false; 3434 3435 // The unspecified model never matches what a definition could need. 3436 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance) 3437 return false; 3438 3439 if (BestCase) { 3440 if (RD->calculateInheritanceModel() == SemanticSpelling) 3441 return false; 3442 } else { 3443 if (RD->calculateInheritanceModel() <= SemanticSpelling) 3444 return false; 3445 } 3446 3447 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance) 3448 << 0 /*definition*/; 3449 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) 3450 << RD->getNameAsString(); 3451 return true; 3452 } 3453 3454 /// parseModeAttrArg - Parses attribute mode string and returns parsed type 3455 /// attribute. 3456 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth, 3457 bool &IntegerMode, bool &ComplexMode) { 3458 IntegerMode = true; 3459 ComplexMode = false; 3460 switch (Str.size()) { 3461 case 2: 3462 switch (Str[0]) { 3463 case 'Q': 3464 DestWidth = 8; 3465 break; 3466 case 'H': 3467 DestWidth = 16; 3468 break; 3469 case 'S': 3470 DestWidth = 32; 3471 break; 3472 case 'D': 3473 DestWidth = 64; 3474 break; 3475 case 'X': 3476 DestWidth = 96; 3477 break; 3478 case 'T': 3479 DestWidth = 128; 3480 break; 3481 } 3482 if (Str[1] == 'F') { 3483 IntegerMode = false; 3484 } else if (Str[1] == 'C') { 3485 IntegerMode = false; 3486 ComplexMode = true; 3487 } else if (Str[1] != 'I') { 3488 DestWidth = 0; 3489 } 3490 break; 3491 case 4: 3492 // FIXME: glibc uses 'word' to define register_t; this is narrower than a 3493 // pointer on PIC16 and other embedded platforms. 3494 if (Str == "word") 3495 DestWidth = S.Context.getTargetInfo().getRegisterWidth(); 3496 else if (Str == "byte") 3497 DestWidth = S.Context.getTargetInfo().getCharWidth(); 3498 break; 3499 case 7: 3500 if (Str == "pointer") 3501 DestWidth = S.Context.getTargetInfo().getPointerWidth(0); 3502 break; 3503 case 11: 3504 if (Str == "unwind_word") 3505 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth(); 3506 break; 3507 } 3508 } 3509 3510 /// handleModeAttr - This attribute modifies the width of a decl with primitive 3511 /// type. 3512 /// 3513 /// Despite what would be logical, the mode attribute is a decl attribute, not a 3514 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be 3515 /// HImode, not an intermediate pointer. 3516 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3517 // This attribute isn't documented, but glibc uses it. It changes 3518 // the width of an int or unsigned int to the specified size. 3519 if (!Attr.isArgIdent(0)) { 3520 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() 3521 << AANT_ArgumentIdentifier; 3522 return; 3523 } 3524 3525 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident; 3526 3527 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex()); 3528 } 3529 3530 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name, 3531 unsigned SpellingListIndex, bool InInstantiation) { 3532 StringRef Str = Name->getName(); 3533 normalizeName(Str); 3534 SourceLocation AttrLoc = AttrRange.getBegin(); 3535 3536 unsigned DestWidth = 0; 3537 bool IntegerMode = true; 3538 bool ComplexMode = false; 3539 llvm::APInt VectorSize(64, 0); 3540 if (Str.size() >= 4 && Str[0] == 'V') { 3541 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2). 3542 size_t StrSize = Str.size(); 3543 size_t VectorStringLength = 0; 3544 while ((VectorStringLength + 1) < StrSize && 3545 isdigit(Str[VectorStringLength + 1])) 3546 ++VectorStringLength; 3547 if (VectorStringLength && 3548 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) && 3549 VectorSize.isPowerOf2()) { 3550 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth, 3551 IntegerMode, ComplexMode); 3552 // Avoid duplicate warning from template instantiation. 3553 if (!InInstantiation) 3554 Diag(AttrLoc, diag::warn_vector_mode_deprecated); 3555 } else { 3556 VectorSize = 0; 3557 } 3558 } 3559 3560 if (!VectorSize) 3561 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode); 3562 3563 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t 3564 // and friends, at least with glibc. 3565 // FIXME: Make sure floating-point mappings are accurate 3566 // FIXME: Support XF and TF types 3567 if (!DestWidth) { 3568 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name; 3569 return; 3570 } 3571 3572 QualType OldTy; 3573 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 3574 OldTy = TD->getUnderlyingType(); 3575 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 3576 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'. 3577 // Try to get type from enum declaration, default to int. 3578 OldTy = ED->getIntegerType(); 3579 if (OldTy.isNull()) 3580 OldTy = Context.IntTy; 3581 } else 3582 OldTy = cast<ValueDecl>(D)->getType(); 3583 3584 if (OldTy->isDependentType()) { 3585 D->addAttr(::new (Context) 3586 ModeAttr(AttrRange, Context, Name, SpellingListIndex)); 3587 return; 3588 } 3589 3590 // Base type can also be a vector type (see PR17453). 3591 // Distinguish between base type and base element type. 3592 QualType OldElemTy = OldTy; 3593 if (const VectorType *VT = OldTy->getAs<VectorType>()) 3594 OldElemTy = VT->getElementType(); 3595 3596 // GCC allows 'mode' attribute on enumeration types (even incomplete), except 3597 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete 3598 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected. 3599 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) && 3600 VectorSize.getBoolValue()) { 3601 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange; 3602 return; 3603 } 3604 bool IntegralOrAnyEnumType = 3605 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>(); 3606 3607 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() && 3608 !IntegralOrAnyEnumType) 3609 Diag(AttrLoc, diag::err_mode_not_primitive); 3610 else if (IntegerMode) { 3611 if (!IntegralOrAnyEnumType) 3612 Diag(AttrLoc, diag::err_mode_wrong_type); 3613 } else if (ComplexMode) { 3614 if (!OldElemTy->isComplexType()) 3615 Diag(AttrLoc, diag::err_mode_wrong_type); 3616 } else { 3617 if (!OldElemTy->isFloatingType()) 3618 Diag(AttrLoc, diag::err_mode_wrong_type); 3619 } 3620 3621 QualType NewElemTy; 3622 3623 if (IntegerMode) 3624 NewElemTy = Context.getIntTypeForBitwidth(DestWidth, 3625 OldElemTy->isSignedIntegerType()); 3626 else 3627 NewElemTy = Context.getRealTypeForBitwidth(DestWidth); 3628 3629 if (NewElemTy.isNull()) { 3630 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name; 3631 return; 3632 } 3633 3634 if (ComplexMode) { 3635 NewElemTy = Context.getComplexType(NewElemTy); 3636 } 3637 3638 QualType NewTy = NewElemTy; 3639 if (VectorSize.getBoolValue()) { 3640 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(), 3641 VectorType::GenericVector); 3642 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) { 3643 // Complex machine mode does not support base vector types. 3644 if (ComplexMode) { 3645 Diag(AttrLoc, diag::err_complex_mode_vector_type); 3646 return; 3647 } 3648 unsigned NumElements = Context.getTypeSize(OldElemTy) * 3649 OldVT->getNumElements() / 3650 Context.getTypeSize(NewElemTy); 3651 NewTy = 3652 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind()); 3653 } 3654 3655 if (NewTy.isNull()) { 3656 Diag(AttrLoc, diag::err_mode_wrong_type); 3657 return; 3658 } 3659 3660 // Install the new type. 3661 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 3662 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy); 3663 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) 3664 ED->setIntegerType(NewTy); 3665 else 3666 cast<ValueDecl>(D)->setType(NewTy); 3667 3668 D->addAttr(::new (Context) 3669 ModeAttr(AttrRange, Context, Name, SpellingListIndex)); 3670 } 3671 3672 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3673 D->addAttr(::new (S.Context) 3674 NoDebugAttr(Attr.getRange(), S.Context, 3675 Attr.getAttributeSpellingListIndex())); 3676 } 3677 3678 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range, 3679 IdentifierInfo *Ident, 3680 unsigned AttrSpellingListIndex) { 3681 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 3682 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident; 3683 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 3684 return nullptr; 3685 } 3686 3687 if (D->hasAttr<AlwaysInlineAttr>()) 3688 return nullptr; 3689 3690 return ::new (Context) AlwaysInlineAttr(Range, Context, 3691 AttrSpellingListIndex); 3692 } 3693 3694 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range, 3695 IdentifierInfo *Ident, 3696 unsigned AttrSpellingListIndex) { 3697 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident)) 3698 return nullptr; 3699 3700 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex); 3701 } 3702 3703 InternalLinkageAttr * 3704 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range, 3705 IdentifierInfo *Ident, 3706 unsigned AttrSpellingListIndex) { 3707 if (auto VD = dyn_cast<VarDecl>(D)) { 3708 // Attribute applies to Var but not any subclass of it (like ParmVar, 3709 // ImplicitParm or VarTemplateSpecialization). 3710 if (VD->getKind() != Decl::Var) { 3711 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type) 3712 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass 3713 : ExpectedVariableOrFunction); 3714 return nullptr; 3715 } 3716 // Attribute does not apply to non-static local variables. 3717 if (VD->hasLocalStorage()) { 3718 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage); 3719 return nullptr; 3720 } 3721 } 3722 3723 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident)) 3724 return nullptr; 3725 3726 return ::new (Context) 3727 InternalLinkageAttr(Range, Context, AttrSpellingListIndex); 3728 } 3729 3730 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range, 3731 unsigned AttrSpellingListIndex) { 3732 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 3733 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'"; 3734 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 3735 return nullptr; 3736 } 3737 3738 if (D->hasAttr<MinSizeAttr>()) 3739 return nullptr; 3740 3741 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex); 3742 } 3743 3744 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range, 3745 unsigned AttrSpellingListIndex) { 3746 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) { 3747 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline; 3748 Diag(Range.getBegin(), diag::note_conflicting_attribute); 3749 D->dropAttr<AlwaysInlineAttr>(); 3750 } 3751 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) { 3752 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize; 3753 Diag(Range.getBegin(), diag::note_conflicting_attribute); 3754 D->dropAttr<MinSizeAttr>(); 3755 } 3756 3757 if (D->hasAttr<OptimizeNoneAttr>()) 3758 return nullptr; 3759 3760 return ::new (Context) OptimizeNoneAttr(Range, Context, 3761 AttrSpellingListIndex); 3762 } 3763 3764 static void handleAlwaysInlineAttr(Sema &S, Decl *D, 3765 const AttributeList &Attr) { 3766 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(), 3767 Attr.getName())) 3768 return; 3769 3770 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr( 3771 D, Attr.getRange(), Attr.getName(), 3772 Attr.getAttributeSpellingListIndex())) 3773 D->addAttr(Inline); 3774 } 3775 3776 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3777 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr( 3778 D, Attr.getRange(), Attr.getAttributeSpellingListIndex())) 3779 D->addAttr(MinSize); 3780 } 3781 3782 static void handleOptimizeNoneAttr(Sema &S, Decl *D, 3783 const AttributeList &Attr) { 3784 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr( 3785 D, Attr.getRange(), Attr.getAttributeSpellingListIndex())) 3786 D->addAttr(Optnone); 3787 } 3788 3789 static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3790 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(), 3791 Attr.getName())) 3792 return; 3793 auto *VD = cast<VarDecl>(D); 3794 if (!VD->hasGlobalStorage()) { 3795 S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant); 3796 return; 3797 } 3798 D->addAttr(::new (S.Context) CUDAConstantAttr( 3799 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3800 } 3801 3802 static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3803 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(), 3804 Attr.getName())) 3805 return; 3806 auto *VD = cast<VarDecl>(D); 3807 // extern __shared__ is only allowed on arrays with no length (e.g. 3808 // "int x[]"). 3809 if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) { 3810 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD; 3811 return; 3812 } 3813 if (S.getLangOpts().CUDA && VD->hasLocalStorage() && 3814 S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared) 3815 << S.CurrentCUDATarget()) 3816 return; 3817 D->addAttr(::new (S.Context) CUDASharedAttr( 3818 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3819 } 3820 3821 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3822 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(), 3823 Attr.getName()) || 3824 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(), 3825 Attr.getName())) { 3826 return; 3827 } 3828 FunctionDecl *FD = cast<FunctionDecl>(D); 3829 if (!FD->getReturnType()->isVoidType()) { 3830 SourceRange RTRange = FD->getReturnTypeSourceRange(); 3831 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return) 3832 << FD->getType() 3833 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 3834 : FixItHint()); 3835 return; 3836 } 3837 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) { 3838 if (Method->isInstance()) { 3839 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method) 3840 << Method; 3841 return; 3842 } 3843 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method; 3844 } 3845 // Only warn for "inline" when compiling for host, to cut down on noise. 3846 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice) 3847 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD; 3848 3849 D->addAttr(::new (S.Context) 3850 CUDAGlobalAttr(Attr.getRange(), S.Context, 3851 Attr.getAttributeSpellingListIndex())); 3852 } 3853 3854 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3855 FunctionDecl *Fn = cast<FunctionDecl>(D); 3856 if (!Fn->isInlineSpecified()) { 3857 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline); 3858 return; 3859 } 3860 3861 D->addAttr(::new (S.Context) 3862 GNUInlineAttr(Attr.getRange(), S.Context, 3863 Attr.getAttributeSpellingListIndex())); 3864 } 3865 3866 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3867 if (hasDeclarator(D)) return; 3868 3869 // Diagnostic is emitted elsewhere: here we store the (valid) Attr 3870 // in the Decl node for syntactic reasoning, e.g., pretty-printing. 3871 CallingConv CC; 3872 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr)) 3873 return; 3874 3875 if (!isa<ObjCMethodDecl>(D)) { 3876 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 3877 << Attr.getName() << ExpectedFunctionOrMethod; 3878 return; 3879 } 3880 3881 switch (Attr.getKind()) { 3882 case AttributeList::AT_FastCall: 3883 D->addAttr(::new (S.Context) 3884 FastCallAttr(Attr.getRange(), S.Context, 3885 Attr.getAttributeSpellingListIndex())); 3886 return; 3887 case AttributeList::AT_StdCall: 3888 D->addAttr(::new (S.Context) 3889 StdCallAttr(Attr.getRange(), S.Context, 3890 Attr.getAttributeSpellingListIndex())); 3891 return; 3892 case AttributeList::AT_ThisCall: 3893 D->addAttr(::new (S.Context) 3894 ThisCallAttr(Attr.getRange(), S.Context, 3895 Attr.getAttributeSpellingListIndex())); 3896 return; 3897 case AttributeList::AT_CDecl: 3898 D->addAttr(::new (S.Context) 3899 CDeclAttr(Attr.getRange(), S.Context, 3900 Attr.getAttributeSpellingListIndex())); 3901 return; 3902 case AttributeList::AT_Pascal: 3903 D->addAttr(::new (S.Context) 3904 PascalAttr(Attr.getRange(), S.Context, 3905 Attr.getAttributeSpellingListIndex())); 3906 return; 3907 case AttributeList::AT_SwiftCall: 3908 D->addAttr(::new (S.Context) 3909 SwiftCallAttr(Attr.getRange(), S.Context, 3910 Attr.getAttributeSpellingListIndex())); 3911 return; 3912 case AttributeList::AT_VectorCall: 3913 D->addAttr(::new (S.Context) 3914 VectorCallAttr(Attr.getRange(), S.Context, 3915 Attr.getAttributeSpellingListIndex())); 3916 return; 3917 case AttributeList::AT_MSABI: 3918 D->addAttr(::new (S.Context) 3919 MSABIAttr(Attr.getRange(), S.Context, 3920 Attr.getAttributeSpellingListIndex())); 3921 return; 3922 case AttributeList::AT_SysVABI: 3923 D->addAttr(::new (S.Context) 3924 SysVABIAttr(Attr.getRange(), S.Context, 3925 Attr.getAttributeSpellingListIndex())); 3926 return; 3927 case AttributeList::AT_RegCall: 3928 D->addAttr(::new (S.Context) RegCallAttr( 3929 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3930 return; 3931 case AttributeList::AT_Pcs: { 3932 PcsAttr::PCSType PCS; 3933 switch (CC) { 3934 case CC_AAPCS: 3935 PCS = PcsAttr::AAPCS; 3936 break; 3937 case CC_AAPCS_VFP: 3938 PCS = PcsAttr::AAPCS_VFP; 3939 break; 3940 default: 3941 llvm_unreachable("unexpected calling convention in pcs attribute"); 3942 } 3943 3944 D->addAttr(::new (S.Context) 3945 PcsAttr(Attr.getRange(), S.Context, PCS, 3946 Attr.getAttributeSpellingListIndex())); 3947 return; 3948 } 3949 case AttributeList::AT_IntelOclBicc: 3950 D->addAttr(::new (S.Context) 3951 IntelOclBiccAttr(Attr.getRange(), S.Context, 3952 Attr.getAttributeSpellingListIndex())); 3953 return; 3954 case AttributeList::AT_PreserveMost: 3955 D->addAttr(::new (S.Context) PreserveMostAttr( 3956 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3957 return; 3958 case AttributeList::AT_PreserveAll: 3959 D->addAttr(::new (S.Context) PreserveAllAttr( 3960 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3961 return; 3962 default: 3963 llvm_unreachable("unexpected attribute kind"); 3964 } 3965 } 3966 3967 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, 3968 const FunctionDecl *FD) { 3969 if (attr.isInvalid()) 3970 return true; 3971 3972 if (attr.hasProcessingCache()) { 3973 CC = (CallingConv) attr.getProcessingCache(); 3974 return false; 3975 } 3976 3977 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0; 3978 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) { 3979 attr.setInvalid(); 3980 return true; 3981 } 3982 3983 // TODO: diagnose uses of these conventions on the wrong target. 3984 switch (attr.getKind()) { 3985 case AttributeList::AT_CDecl: CC = CC_C; break; 3986 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break; 3987 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break; 3988 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break; 3989 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break; 3990 case AttributeList::AT_SwiftCall: CC = CC_Swift; break; 3991 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break; 3992 case AttributeList::AT_RegCall: CC = CC_X86RegCall; break; 3993 case AttributeList::AT_MSABI: 3994 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : 3995 CC_X86_64Win64; 3996 break; 3997 case AttributeList::AT_SysVABI: 3998 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV : 3999 CC_C; 4000 break; 4001 case AttributeList::AT_Pcs: { 4002 StringRef StrRef; 4003 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) { 4004 attr.setInvalid(); 4005 return true; 4006 } 4007 if (StrRef == "aapcs") { 4008 CC = CC_AAPCS; 4009 break; 4010 } else if (StrRef == "aapcs-vfp") { 4011 CC = CC_AAPCS_VFP; 4012 break; 4013 } 4014 4015 attr.setInvalid(); 4016 Diag(attr.getLoc(), diag::err_invalid_pcs); 4017 return true; 4018 } 4019 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break; 4020 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break; 4021 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break; 4022 default: llvm_unreachable("unexpected attribute kind"); 4023 } 4024 4025 const TargetInfo &TI = Context.getTargetInfo(); 4026 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC); 4027 if (A != TargetInfo::CCCR_OK) { 4028 if (A == TargetInfo::CCCR_Warning) 4029 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName(); 4030 4031 // This convention is not valid for the target. Use the default function or 4032 // method calling convention. 4033 bool IsCXXMethod = false, IsVariadic = false; 4034 if (FD) { 4035 IsCXXMethod = FD->isCXXInstanceMember(); 4036 IsVariadic = FD->isVariadic(); 4037 } 4038 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod); 4039 } 4040 4041 attr.setProcessingCache((unsigned) CC); 4042 return false; 4043 } 4044 4045 /// Pointer-like types in the default address space. 4046 static bool isValidSwiftContextType(QualType type) { 4047 if (!type->hasPointerRepresentation()) 4048 return type->isDependentType(); 4049 return type->getPointeeType().getAddressSpace() == 0; 4050 } 4051 4052 /// Pointers and references in the default address space. 4053 static bool isValidSwiftIndirectResultType(QualType type) { 4054 if (auto ptrType = type->getAs<PointerType>()) { 4055 type = ptrType->getPointeeType(); 4056 } else if (auto refType = type->getAs<ReferenceType>()) { 4057 type = refType->getPointeeType(); 4058 } else { 4059 return type->isDependentType(); 4060 } 4061 return type.getAddressSpace() == 0; 4062 } 4063 4064 /// Pointers and references to pointers in the default address space. 4065 static bool isValidSwiftErrorResultType(QualType type) { 4066 if (auto ptrType = type->getAs<PointerType>()) { 4067 type = ptrType->getPointeeType(); 4068 } else if (auto refType = type->getAs<ReferenceType>()) { 4069 type = refType->getPointeeType(); 4070 } else { 4071 return type->isDependentType(); 4072 } 4073 if (!type.getQualifiers().empty()) 4074 return false; 4075 return isValidSwiftContextType(type); 4076 } 4077 4078 static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr, 4079 ParameterABI abi) { 4080 S.AddParameterABIAttr(attr.getRange(), D, abi, 4081 attr.getAttributeSpellingListIndex()); 4082 } 4083 4084 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi, 4085 unsigned spellingIndex) { 4086 4087 QualType type = cast<ParmVarDecl>(D)->getType(); 4088 4089 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) { 4090 if (existingAttr->getABI() != abi) { 4091 Diag(range.getBegin(), diag::err_attributes_are_not_compatible) 4092 << getParameterABISpelling(abi) << existingAttr; 4093 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute); 4094 return; 4095 } 4096 } 4097 4098 switch (abi) { 4099 case ParameterABI::Ordinary: 4100 llvm_unreachable("explicit attribute for ordinary parameter ABI?"); 4101 4102 case ParameterABI::SwiftContext: 4103 if (!isValidSwiftContextType(type)) { 4104 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) 4105 << getParameterABISpelling(abi) 4106 << /*pointer to pointer */ 0 << type; 4107 } 4108 D->addAttr(::new (Context) 4109 SwiftContextAttr(range, Context, spellingIndex)); 4110 return; 4111 4112 case ParameterABI::SwiftErrorResult: 4113 if (!isValidSwiftErrorResultType(type)) { 4114 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) 4115 << getParameterABISpelling(abi) 4116 << /*pointer to pointer */ 1 << type; 4117 } 4118 D->addAttr(::new (Context) 4119 SwiftErrorResultAttr(range, Context, spellingIndex)); 4120 return; 4121 4122 case ParameterABI::SwiftIndirectResult: 4123 if (!isValidSwiftIndirectResultType(type)) { 4124 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) 4125 << getParameterABISpelling(abi) 4126 << /*pointer*/ 0 << type; 4127 } 4128 D->addAttr(::new (Context) 4129 SwiftIndirectResultAttr(range, Context, spellingIndex)); 4130 return; 4131 } 4132 llvm_unreachable("bad parameter ABI attribute"); 4133 } 4134 4135 /// Checks a regparm attribute, returning true if it is ill-formed and 4136 /// otherwise setting numParams to the appropriate value. 4137 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) { 4138 if (Attr.isInvalid()) 4139 return true; 4140 4141 if (!checkAttributeNumArgs(*this, Attr, 1)) { 4142 Attr.setInvalid(); 4143 return true; 4144 } 4145 4146 uint32_t NP; 4147 Expr *NumParamsExpr = Attr.getArgAsExpr(0); 4148 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) { 4149 Attr.setInvalid(); 4150 return true; 4151 } 4152 4153 if (Context.getTargetInfo().getRegParmMax() == 0) { 4154 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform) 4155 << NumParamsExpr->getSourceRange(); 4156 Attr.setInvalid(); 4157 return true; 4158 } 4159 4160 numParams = NP; 4161 if (numParams > Context.getTargetInfo().getRegParmMax()) { 4162 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number) 4163 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange(); 4164 Attr.setInvalid(); 4165 return true; 4166 } 4167 4168 return false; 4169 } 4170 4171 // Checks whether an argument of launch_bounds attribute is 4172 // acceptable, performs implicit conversion to Rvalue, and returns 4173 // non-nullptr Expr result on success. Otherwise, it returns nullptr 4174 // and may output an error. 4175 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E, 4176 const CUDALaunchBoundsAttr &Attr, 4177 const unsigned Idx) { 4178 if (S.DiagnoseUnexpandedParameterPack(E)) 4179 return nullptr; 4180 4181 // Accept template arguments for now as they depend on something else. 4182 // We'll get to check them when they eventually get instantiated. 4183 if (E->isValueDependent()) 4184 return E; 4185 4186 llvm::APSInt I(64); 4187 if (!E->isIntegerConstantExpr(I, S.Context)) { 4188 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type) 4189 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange(); 4190 return nullptr; 4191 } 4192 // Make sure we can fit it in 32 bits. 4193 if (!I.isIntN(32)) { 4194 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false) 4195 << 32 << /* Unsigned */ 1; 4196 return nullptr; 4197 } 4198 if (I < 0) 4199 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative) 4200 << &Attr << Idx << E->getSourceRange(); 4201 4202 // We may need to perform implicit conversion of the argument. 4203 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4204 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false); 4205 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E); 4206 assert(!ValArg.isInvalid() && 4207 "Unexpected PerformCopyInitialization() failure."); 4208 4209 return ValArg.getAs<Expr>(); 4210 } 4211 4212 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, 4213 Expr *MinBlocks, unsigned SpellingListIndex) { 4214 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks, 4215 SpellingListIndex); 4216 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0); 4217 if (MaxThreads == nullptr) 4218 return; 4219 4220 if (MinBlocks) { 4221 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1); 4222 if (MinBlocks == nullptr) 4223 return; 4224 } 4225 4226 D->addAttr(::new (Context) CUDALaunchBoundsAttr( 4227 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex)); 4228 } 4229 4230 static void handleLaunchBoundsAttr(Sema &S, Decl *D, 4231 const AttributeList &Attr) { 4232 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) || 4233 !checkAttributeAtMostNumArgs(S, Attr, 2)) 4234 return; 4235 4236 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0), 4237 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr, 4238 Attr.getAttributeSpellingListIndex()); 4239 } 4240 4241 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D, 4242 const AttributeList &Attr) { 4243 if (!Attr.isArgIdent(0)) { 4244 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 4245 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier; 4246 return; 4247 } 4248 4249 if (!checkAttributeNumArgs(S, Attr, 3)) 4250 return; 4251 4252 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident; 4253 4254 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) { 4255 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type) 4256 << Attr.getName() << ExpectedFunctionOrMethod; 4257 return; 4258 } 4259 4260 uint64_t ArgumentIdx; 4261 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1), 4262 ArgumentIdx)) 4263 return; 4264 4265 uint64_t TypeTagIdx; 4266 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2), 4267 TypeTagIdx)) 4268 return; 4269 4270 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag"); 4271 if (IsPointer) { 4272 // Ensure that buffer has a pointer type. 4273 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx); 4274 if (!BufferTy->isPointerType()) { 4275 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only) 4276 << Attr.getName() << 0; 4277 } 4278 } 4279 4280 D->addAttr(::new (S.Context) 4281 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind, 4282 ArgumentIdx, TypeTagIdx, IsPointer, 4283 Attr.getAttributeSpellingListIndex())); 4284 } 4285 4286 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D, 4287 const AttributeList &Attr) { 4288 if (!Attr.isArgIdent(0)) { 4289 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 4290 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 4291 return; 4292 } 4293 4294 if (!checkAttributeNumArgs(S, Attr, 1)) 4295 return; 4296 4297 if (!isa<VarDecl>(D)) { 4298 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type) 4299 << Attr.getName() << ExpectedVariable; 4300 return; 4301 } 4302 4303 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident; 4304 TypeSourceInfo *MatchingCTypeLoc = nullptr; 4305 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc); 4306 assert(MatchingCTypeLoc && "no type source info for attribute argument"); 4307 4308 D->addAttr(::new (S.Context) 4309 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind, 4310 MatchingCTypeLoc, 4311 Attr.getLayoutCompatible(), 4312 Attr.getMustBeNull(), 4313 Attr.getAttributeSpellingListIndex())); 4314 } 4315 4316 //===----------------------------------------------------------------------===// 4317 // Checker-specific attribute handlers. 4318 //===----------------------------------------------------------------------===// 4319 4320 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) { 4321 return type->isDependentType() || 4322 type->isObjCRetainableType(); 4323 } 4324 4325 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) { 4326 return type->isDependentType() || 4327 type->isObjCObjectPointerType() || 4328 S.Context.isObjCNSObjectType(type); 4329 } 4330 4331 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) { 4332 return type->isDependentType() || 4333 type->isPointerType() || 4334 isValidSubjectOfNSAttribute(S, type); 4335 } 4336 4337 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4338 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(), 4339 Attr.getKind() == AttributeList::AT_NSConsumed, 4340 /*template instantiation*/ false); 4341 } 4342 4343 void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D, 4344 unsigned spellingIndex, bool isNSConsumed, 4345 bool isTemplateInstantiation) { 4346 ParmVarDecl *param = cast<ParmVarDecl>(D); 4347 bool typeOK; 4348 4349 if (isNSConsumed) { 4350 typeOK = isValidSubjectOfNSAttribute(*this, param->getType()); 4351 } else { 4352 typeOK = isValidSubjectOfCFAttribute(*this, param->getType()); 4353 } 4354 4355 if (!typeOK) { 4356 // These attributes are normally just advisory, but in ARC, ns_consumed 4357 // is significant. Allow non-dependent code to contain inappropriate 4358 // attributes even in ARC, but require template instantiations to be 4359 // set up correctly. 4360 Diag(D->getLocStart(), 4361 (isTemplateInstantiation && isNSConsumed && 4362 getLangOpts().ObjCAutoRefCount 4363 ? diag::err_ns_attribute_wrong_parameter_type 4364 : diag::warn_ns_attribute_wrong_parameter_type)) 4365 << attrRange 4366 << (isNSConsumed ? "ns_consumed" : "cf_consumed") 4367 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1); 4368 return; 4369 } 4370 4371 if (isNSConsumed) 4372 param->addAttr(::new (Context) 4373 NSConsumedAttr(attrRange, Context, spellingIndex)); 4374 else 4375 param->addAttr(::new (Context) 4376 CFConsumedAttr(attrRange, Context, spellingIndex)); 4377 } 4378 4379 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D, 4380 const AttributeList &Attr) { 4381 QualType returnType; 4382 4383 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 4384 returnType = MD->getReturnType(); 4385 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) && 4386 (Attr.getKind() == AttributeList::AT_NSReturnsRetained)) 4387 return; // ignore: was handled as a type attribute 4388 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) 4389 returnType = PD->getType(); 4390 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 4391 returnType = FD->getReturnType(); 4392 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) { 4393 returnType = Param->getType()->getPointeeType(); 4394 if (returnType.isNull()) { 4395 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) 4396 << Attr.getName() << /*pointer-to-CF*/2 4397 << Attr.getRange(); 4398 return; 4399 } 4400 } else { 4401 AttributeDeclKind ExpectedDeclKind; 4402 switch (Attr.getKind()) { 4403 default: llvm_unreachable("invalid ownership attribute"); 4404 case AttributeList::AT_NSReturnsRetained: 4405 case AttributeList::AT_NSReturnsAutoreleased: 4406 case AttributeList::AT_NSReturnsNotRetained: 4407 ExpectedDeclKind = ExpectedFunctionOrMethod; 4408 break; 4409 4410 case AttributeList::AT_CFReturnsRetained: 4411 case AttributeList::AT_CFReturnsNotRetained: 4412 ExpectedDeclKind = ExpectedFunctionMethodOrParameter; 4413 break; 4414 } 4415 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type) 4416 << Attr.getRange() << Attr.getName() << ExpectedDeclKind; 4417 return; 4418 } 4419 4420 bool typeOK; 4421 bool cf; 4422 switch (Attr.getKind()) { 4423 default: llvm_unreachable("invalid ownership attribute"); 4424 case AttributeList::AT_NSReturnsRetained: 4425 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType); 4426 cf = false; 4427 break; 4428 4429 case AttributeList::AT_NSReturnsAutoreleased: 4430 case AttributeList::AT_NSReturnsNotRetained: 4431 typeOK = isValidSubjectOfNSAttribute(S, returnType); 4432 cf = false; 4433 break; 4434 4435 case AttributeList::AT_CFReturnsRetained: 4436 case AttributeList::AT_CFReturnsNotRetained: 4437 typeOK = isValidSubjectOfCFAttribute(S, returnType); 4438 cf = true; 4439 break; 4440 } 4441 4442 if (!typeOK) { 4443 if (isa<ParmVarDecl>(D)) { 4444 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) 4445 << Attr.getName() << /*pointer-to-CF*/2 4446 << Attr.getRange(); 4447 } else { 4448 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type. 4449 enum : unsigned { 4450 Function, 4451 Method, 4452 Property 4453 } SubjectKind = Function; 4454 if (isa<ObjCMethodDecl>(D)) 4455 SubjectKind = Method; 4456 else if (isa<ObjCPropertyDecl>(D)) 4457 SubjectKind = Property; 4458 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) 4459 << Attr.getName() << SubjectKind << cf 4460 << Attr.getRange(); 4461 } 4462 return; 4463 } 4464 4465 switch (Attr.getKind()) { 4466 default: 4467 llvm_unreachable("invalid ownership attribute"); 4468 case AttributeList::AT_NSReturnsAutoreleased: 4469 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr( 4470 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4471 return; 4472 case AttributeList::AT_CFReturnsNotRetained: 4473 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr( 4474 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4475 return; 4476 case AttributeList::AT_NSReturnsNotRetained: 4477 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr( 4478 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4479 return; 4480 case AttributeList::AT_CFReturnsRetained: 4481 D->addAttr(::new (S.Context) CFReturnsRetainedAttr( 4482 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4483 return; 4484 case AttributeList::AT_NSReturnsRetained: 4485 D->addAttr(::new (S.Context) NSReturnsRetainedAttr( 4486 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4487 return; 4488 }; 4489 } 4490 4491 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D, 4492 const AttributeList &attr) { 4493 const int EP_ObjCMethod = 1; 4494 const int EP_ObjCProperty = 2; 4495 4496 SourceLocation loc = attr.getLoc(); 4497 QualType resultType; 4498 if (isa<ObjCMethodDecl>(D)) 4499 resultType = cast<ObjCMethodDecl>(D)->getReturnType(); 4500 else 4501 resultType = cast<ObjCPropertyDecl>(D)->getType(); 4502 4503 if (!resultType->isReferenceType() && 4504 (!resultType->isPointerType() || resultType->isObjCRetainableType())) { 4505 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) 4506 << SourceRange(loc) 4507 << attr.getName() 4508 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty) 4509 << /*non-retainable pointer*/ 2; 4510 4511 // Drop the attribute. 4512 return; 4513 } 4514 4515 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr( 4516 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex())); 4517 } 4518 4519 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D, 4520 const AttributeList &attr) { 4521 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D); 4522 4523 DeclContext *DC = method->getDeclContext(); 4524 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) { 4525 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) 4526 << attr.getName() << 0; 4527 S.Diag(PDecl->getLocation(), diag::note_protocol_decl); 4528 return; 4529 } 4530 if (method->getMethodFamily() == OMF_dealloc) { 4531 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) 4532 << attr.getName() << 1; 4533 return; 4534 } 4535 4536 method->addAttr(::new (S.Context) 4537 ObjCRequiresSuperAttr(attr.getRange(), S.Context, 4538 attr.getAttributeSpellingListIndex())); 4539 } 4540 4541 static void handleCFAuditedTransferAttr(Sema &S, Decl *D, 4542 const AttributeList &Attr) { 4543 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(), 4544 Attr.getName())) 4545 return; 4546 4547 D->addAttr(::new (S.Context) 4548 CFAuditedTransferAttr(Attr.getRange(), S.Context, 4549 Attr.getAttributeSpellingListIndex())); 4550 } 4551 4552 static void handleCFUnknownTransferAttr(Sema &S, Decl *D, 4553 const AttributeList &Attr) { 4554 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(), 4555 Attr.getName())) 4556 return; 4557 4558 D->addAttr(::new (S.Context) 4559 CFUnknownTransferAttr(Attr.getRange(), S.Context, 4560 Attr.getAttributeSpellingListIndex())); 4561 } 4562 4563 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D, 4564 const AttributeList &Attr) { 4565 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr; 4566 4567 if (!Parm) { 4568 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 4569 return; 4570 } 4571 4572 // Typedefs only allow objc_bridge(id) and have some additional checking. 4573 if (auto TD = dyn_cast<TypedefNameDecl>(D)) { 4574 if (!Parm->Ident->isStr("id")) { 4575 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id) 4576 << Attr.getName(); 4577 return; 4578 } 4579 4580 // Only allow 'cv void *'. 4581 QualType T = TD->getUnderlyingType(); 4582 if (!T->isVoidPointerType()) { 4583 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer); 4584 return; 4585 } 4586 } 4587 4588 D->addAttr(::new (S.Context) 4589 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident, 4590 Attr.getAttributeSpellingListIndex())); 4591 } 4592 4593 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D, 4594 const AttributeList &Attr) { 4595 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr; 4596 4597 if (!Parm) { 4598 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 4599 return; 4600 } 4601 4602 D->addAttr(::new (S.Context) 4603 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident, 4604 Attr.getAttributeSpellingListIndex())); 4605 } 4606 4607 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D, 4608 const AttributeList &Attr) { 4609 IdentifierInfo *RelatedClass = 4610 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr; 4611 if (!RelatedClass) { 4612 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 4613 return; 4614 } 4615 IdentifierInfo *ClassMethod = 4616 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr; 4617 IdentifierInfo *InstanceMethod = 4618 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr; 4619 D->addAttr(::new (S.Context) 4620 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass, 4621 ClassMethod, InstanceMethod, 4622 Attr.getAttributeSpellingListIndex())); 4623 } 4624 4625 static void handleObjCDesignatedInitializer(Sema &S, Decl *D, 4626 const AttributeList &Attr) { 4627 ObjCInterfaceDecl *IFace; 4628 if (ObjCCategoryDecl *CatDecl = 4629 dyn_cast<ObjCCategoryDecl>(D->getDeclContext())) 4630 IFace = CatDecl->getClassInterface(); 4631 else 4632 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext()); 4633 4634 if (!IFace) 4635 return; 4636 4637 IFace->setHasDesignatedInitializers(); 4638 D->addAttr(::new (S.Context) 4639 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context, 4640 Attr.getAttributeSpellingListIndex())); 4641 } 4642 4643 static void handleObjCRuntimeName(Sema &S, Decl *D, 4644 const AttributeList &Attr) { 4645 StringRef MetaDataName; 4646 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName)) 4647 return; 4648 D->addAttr(::new (S.Context) 4649 ObjCRuntimeNameAttr(Attr.getRange(), S.Context, 4650 MetaDataName, 4651 Attr.getAttributeSpellingListIndex())); 4652 } 4653 4654 // When a user wants to use objc_boxable with a union or struct 4655 // but they don't have access to the declaration (legacy/third-party code) 4656 // then they can 'enable' this feature with a typedef: 4657 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct; 4658 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) { 4659 bool notify = false; 4660 4661 RecordDecl *RD = dyn_cast<RecordDecl>(D); 4662 if (RD && RD->getDefinition()) { 4663 RD = RD->getDefinition(); 4664 notify = true; 4665 } 4666 4667 if (RD) { 4668 ObjCBoxableAttr *BoxableAttr = ::new (S.Context) 4669 ObjCBoxableAttr(Attr.getRange(), S.Context, 4670 Attr.getAttributeSpellingListIndex()); 4671 RD->addAttr(BoxableAttr); 4672 if (notify) { 4673 // we need to notify ASTReader/ASTWriter about 4674 // modification of existing declaration 4675 if (ASTMutationListener *L = S.getASTMutationListener()) 4676 L->AddedAttributeToRecord(BoxableAttr, RD); 4677 } 4678 } 4679 } 4680 4681 static void handleObjCOwnershipAttr(Sema &S, Decl *D, 4682 const AttributeList &Attr) { 4683 if (hasDeclarator(D)) return; 4684 4685 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type) 4686 << Attr.getRange() << Attr.getName() << ExpectedVariable; 4687 } 4688 4689 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D, 4690 const AttributeList &Attr) { 4691 ValueDecl *vd = cast<ValueDecl>(D); 4692 QualType type = vd->getType(); 4693 4694 if (!type->isDependentType() && 4695 !type->isObjCLifetimeType()) { 4696 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type) 4697 << type; 4698 return; 4699 } 4700 4701 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4702 4703 // If we have no lifetime yet, check the lifetime we're presumably 4704 // going to infer. 4705 if (lifetime == Qualifiers::OCL_None && !type->isDependentType()) 4706 lifetime = type->getObjCARCImplicitLifetime(); 4707 4708 switch (lifetime) { 4709 case Qualifiers::OCL_None: 4710 assert(type->isDependentType() && 4711 "didn't infer lifetime for non-dependent type?"); 4712 break; 4713 4714 case Qualifiers::OCL_Weak: // meaningful 4715 case Qualifiers::OCL_Strong: // meaningful 4716 break; 4717 4718 case Qualifiers::OCL_ExplicitNone: 4719 case Qualifiers::OCL_Autoreleasing: 4720 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless) 4721 << (lifetime == Qualifiers::OCL_Autoreleasing); 4722 break; 4723 } 4724 4725 D->addAttr(::new (S.Context) 4726 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context, 4727 Attr.getAttributeSpellingListIndex())); 4728 } 4729 4730 //===----------------------------------------------------------------------===// 4731 // Microsoft specific attribute handlers. 4732 //===----------------------------------------------------------------------===// 4733 4734 UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range, 4735 unsigned AttrSpellingListIndex, StringRef Uuid) { 4736 if (const auto *UA = D->getAttr<UuidAttr>()) { 4737 if (UA->getGuid().equals_lower(Uuid)) 4738 return nullptr; 4739 Diag(UA->getLocation(), diag::err_mismatched_uuid); 4740 Diag(Range.getBegin(), diag::note_previous_uuid); 4741 D->dropAttr<UuidAttr>(); 4742 } 4743 4744 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex); 4745 } 4746 4747 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4748 if (!S.LangOpts.CPlusPlus) { 4749 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 4750 << Attr.getName() << AttributeLangSupport::C; 4751 return; 4752 } 4753 4754 StringRef StrRef; 4755 SourceLocation LiteralLoc; 4756 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc)) 4757 return; 4758 4759 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or 4760 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former. 4761 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}') 4762 StrRef = StrRef.drop_front().drop_back(); 4763 4764 // Validate GUID length. 4765 if (StrRef.size() != 36) { 4766 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 4767 return; 4768 } 4769 4770 for (unsigned i = 0; i < 36; ++i) { 4771 if (i == 8 || i == 13 || i == 18 || i == 23) { 4772 if (StrRef[i] != '-') { 4773 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 4774 return; 4775 } 4776 } else if (!isHexDigit(StrRef[i])) { 4777 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 4778 return; 4779 } 4780 } 4781 4782 UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(), 4783 Attr.getAttributeSpellingListIndex(), StrRef); 4784 if (UA) 4785 D->addAttr(UA); 4786 } 4787 4788 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4789 if (!S.LangOpts.CPlusPlus) { 4790 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 4791 << Attr.getName() << AttributeLangSupport::C; 4792 return; 4793 } 4794 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr( 4795 D, Attr.getRange(), /*BestCase=*/true, 4796 Attr.getAttributeSpellingListIndex(), 4797 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling()); 4798 if (IA) { 4799 D->addAttr(IA); 4800 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 4801 } 4802 } 4803 4804 static void handleDeclspecThreadAttr(Sema &S, Decl *D, 4805 const AttributeList &Attr) { 4806 VarDecl *VD = cast<VarDecl>(D); 4807 if (!S.Context.getTargetInfo().isTLSSupported()) { 4808 S.Diag(Attr.getLoc(), diag::err_thread_unsupported); 4809 return; 4810 } 4811 if (VD->getTSCSpec() != TSCS_unspecified) { 4812 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable); 4813 return; 4814 } 4815 if (VD->hasLocalStorage()) { 4816 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)"; 4817 return; 4818 } 4819 VD->addAttr(::new (S.Context) ThreadAttr( 4820 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4821 } 4822 4823 static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4824 SmallVector<StringRef, 4> Tags; 4825 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) { 4826 StringRef Tag; 4827 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag)) 4828 return; 4829 Tags.push_back(Tag); 4830 } 4831 4832 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) { 4833 if (!NS->isInline()) { 4834 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0; 4835 return; 4836 } 4837 if (NS->isAnonymousNamespace()) { 4838 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1; 4839 return; 4840 } 4841 if (Attr.getNumArgs() == 0) 4842 Tags.push_back(NS->getName()); 4843 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 4844 return; 4845 4846 // Store tags sorted and without duplicates. 4847 std::sort(Tags.begin(), Tags.end()); 4848 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end()); 4849 4850 D->addAttr(::new (S.Context) 4851 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(), 4852 Attr.getAttributeSpellingListIndex())); 4853 } 4854 4855 static void handleARMInterruptAttr(Sema &S, Decl *D, 4856 const AttributeList &Attr) { 4857 // Check the attribute arguments. 4858 if (Attr.getNumArgs() > 1) { 4859 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) 4860 << Attr.getName() << 1; 4861 return; 4862 } 4863 4864 StringRef Str; 4865 SourceLocation ArgLoc; 4866 4867 if (Attr.getNumArgs() == 0) 4868 Str = ""; 4869 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc)) 4870 return; 4871 4872 ARMInterruptAttr::InterruptType Kind; 4873 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 4874 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 4875 << Attr.getName() << Str << ArgLoc; 4876 return; 4877 } 4878 4879 unsigned Index = Attr.getAttributeSpellingListIndex(); 4880 D->addAttr(::new (S.Context) 4881 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index)); 4882 } 4883 4884 static void handleMSP430InterruptAttr(Sema &S, Decl *D, 4885 const AttributeList &Attr) { 4886 if (!checkAttributeNumArgs(S, Attr, 1)) 4887 return; 4888 4889 if (!Attr.isArgExpr(0)) { 4890 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() 4891 << AANT_ArgumentIntegerConstant; 4892 return; 4893 } 4894 4895 // FIXME: Check for decl - it should be void ()(void). 4896 4897 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4898 llvm::APSInt NumParams(32); 4899 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) { 4900 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 4901 << Attr.getName() << AANT_ArgumentIntegerConstant 4902 << NumParamsExpr->getSourceRange(); 4903 return; 4904 } 4905 4906 unsigned Num = NumParams.getLimitedValue(255); 4907 if ((Num & 1) || Num > 30) { 4908 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 4909 << Attr.getName() << (int)NumParams.getSExtValue() 4910 << NumParamsExpr->getSourceRange(); 4911 return; 4912 } 4913 4914 D->addAttr(::new (S.Context) 4915 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num, 4916 Attr.getAttributeSpellingListIndex())); 4917 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 4918 } 4919 4920 static void handleMipsInterruptAttr(Sema &S, Decl *D, 4921 const AttributeList &Attr) { 4922 // Only one optional argument permitted. 4923 if (Attr.getNumArgs() > 1) { 4924 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) 4925 << Attr.getName() << 1; 4926 return; 4927 } 4928 4929 StringRef Str; 4930 SourceLocation ArgLoc; 4931 4932 if (Attr.getNumArgs() == 0) 4933 Str = ""; 4934 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc)) 4935 return; 4936 4937 // Semantic checks for a function with the 'interrupt' attribute for MIPS: 4938 // a) Must be a function. 4939 // b) Must have no parameters. 4940 // c) Must have the 'void' return type. 4941 // d) Cannot have the 'mips16' attribute, as that instruction set 4942 // lacks the 'eret' instruction. 4943 // e) The attribute itself must either have no argument or one of the 4944 // valid interrupt types, see [MipsInterruptDocs]. 4945 4946 if (!isFunctionOrMethod(D)) { 4947 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 4948 << "'interrupt'" << ExpectedFunctionOrMethod; 4949 return; 4950 } 4951 4952 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { 4953 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute) 4954 << 0; 4955 return; 4956 } 4957 4958 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 4959 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute) 4960 << 1; 4961 return; 4962 } 4963 4964 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(), 4965 Attr.getName())) 4966 return; 4967 4968 MipsInterruptAttr::InterruptType Kind; 4969 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 4970 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 4971 << Attr.getName() << "'" + std::string(Str) + "'"; 4972 return; 4973 } 4974 4975 D->addAttr(::new (S.Context) MipsInterruptAttr( 4976 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex())); 4977 } 4978 4979 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, 4980 const AttributeList &Attr) { 4981 // Semantic checks for a function with the 'interrupt' attribute. 4982 // a) Must be a function. 4983 // b) Must have the 'void' return type. 4984 // c) Must take 1 or 2 arguments. 4985 // d) The 1st argument must be a pointer. 4986 // e) The 2nd argument (if any) must be an unsigned integer. 4987 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) || 4988 CXXMethodDecl::isStaticOverloadedOperator( 4989 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) { 4990 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 4991 << Attr.getName() << ExpectedFunctionWithProtoType; 4992 return; 4993 } 4994 // Interrupt handler must have void return type. 4995 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 4996 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(), 4997 diag::err_anyx86_interrupt_attribute) 4998 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 4999 ? 0 5000 : 1) 5001 << 0; 5002 return; 5003 } 5004 // Interrupt handler must have 1 or 2 parameters. 5005 unsigned NumParams = getFunctionOrMethodNumParams(D); 5006 if (NumParams < 1 || NumParams > 2) { 5007 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute) 5008 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 5009 ? 0 5010 : 1) 5011 << 1; 5012 return; 5013 } 5014 // The first argument must be a pointer. 5015 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) { 5016 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(), 5017 diag::err_anyx86_interrupt_attribute) 5018 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 5019 ? 0 5020 : 1) 5021 << 2; 5022 return; 5023 } 5024 // The second argument, if present, must be an unsigned integer. 5025 unsigned TypeSize = 5026 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64 5027 ? 64 5028 : 32; 5029 if (NumParams == 2 && 5030 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() || 5031 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) { 5032 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(), 5033 diag::err_anyx86_interrupt_attribute) 5034 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 5035 ? 0 5036 : 1) 5037 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false); 5038 return; 5039 } 5040 D->addAttr(::new (S.Context) AnyX86InterruptAttr( 5041 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex())); 5042 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 5043 } 5044 5045 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) { 5046 // Dispatch the interrupt attribute based on the current target. 5047 switch (S.Context.getTargetInfo().getTriple().getArch()) { 5048 case llvm::Triple::msp430: 5049 handleMSP430InterruptAttr(S, D, Attr); 5050 break; 5051 case llvm::Triple::mipsel: 5052 case llvm::Triple::mips: 5053 handleMipsInterruptAttr(S, D, Attr); 5054 break; 5055 case llvm::Triple::x86: 5056 case llvm::Triple::x86_64: 5057 handleAnyX86InterruptAttr(S, D, Attr); 5058 break; 5059 default: 5060 handleARMInterruptAttr(S, D, Attr); 5061 break; 5062 } 5063 } 5064 5065 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D, 5066 const AttributeList &Attr) { 5067 uint32_t Min = 0; 5068 Expr *MinExpr = Attr.getArgAsExpr(0); 5069 if (!checkUInt32Argument(S, Attr, MinExpr, Min)) 5070 return; 5071 5072 uint32_t Max = 0; 5073 Expr *MaxExpr = Attr.getArgAsExpr(1); 5074 if (!checkUInt32Argument(S, Attr, MaxExpr, Max)) 5075 return; 5076 5077 if (Min == 0 && Max != 0) { 5078 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid) 5079 << Attr.getName() << 0; 5080 return; 5081 } 5082 if (Min > Max) { 5083 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid) 5084 << Attr.getName() << 1; 5085 return; 5086 } 5087 5088 D->addAttr(::new (S.Context) 5089 AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max, 5090 Attr.getAttributeSpellingListIndex())); 5091 } 5092 5093 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, 5094 const AttributeList &Attr) { 5095 uint32_t Min = 0; 5096 Expr *MinExpr = Attr.getArgAsExpr(0); 5097 if (!checkUInt32Argument(S, Attr, MinExpr, Min)) 5098 return; 5099 5100 uint32_t Max = 0; 5101 if (Attr.getNumArgs() == 2) { 5102 Expr *MaxExpr = Attr.getArgAsExpr(1); 5103 if (!checkUInt32Argument(S, Attr, MaxExpr, Max)) 5104 return; 5105 } 5106 5107 if (Min == 0 && Max != 0) { 5108 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid) 5109 << Attr.getName() << 0; 5110 return; 5111 } 5112 if (Max != 0 && Min > Max) { 5113 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid) 5114 << Attr.getName() << 1; 5115 return; 5116 } 5117 5118 D->addAttr(::new (S.Context) 5119 AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max, 5120 Attr.getAttributeSpellingListIndex())); 5121 } 5122 5123 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, 5124 const AttributeList &Attr) { 5125 uint32_t NumSGPR = 0; 5126 Expr *NumSGPRExpr = Attr.getArgAsExpr(0); 5127 if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR)) 5128 return; 5129 5130 D->addAttr(::new (S.Context) 5131 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR, 5132 Attr.getAttributeSpellingListIndex())); 5133 } 5134 5135 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, 5136 const AttributeList &Attr) { 5137 uint32_t NumVGPR = 0; 5138 Expr *NumVGPRExpr = Attr.getArgAsExpr(0); 5139 if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR)) 5140 return; 5141 5142 D->addAttr(::new (S.Context) 5143 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR, 5144 Attr.getAttributeSpellingListIndex())); 5145 } 5146 5147 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D, 5148 const AttributeList& Attr) { 5149 // If we try to apply it to a function pointer, don't warn, but don't 5150 // do anything, either. It doesn't matter anyway, because there's nothing 5151 // special about calling a force_align_arg_pointer function. 5152 ValueDecl *VD = dyn_cast<ValueDecl>(D); 5153 if (VD && VD->getType()->isFunctionPointerType()) 5154 return; 5155 // Also don't warn on function pointer typedefs. 5156 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D); 5157 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() || 5158 TD->getUnderlyingType()->isFunctionType())) 5159 return; 5160 // Attribute can only be applied to function types. 5161 if (!isa<FunctionDecl>(D)) { 5162 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 5163 << Attr.getName() << /* function */0; 5164 return; 5165 } 5166 5167 D->addAttr(::new (S.Context) 5168 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context, 5169 Attr.getAttributeSpellingListIndex())); 5170 } 5171 5172 static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) { 5173 uint32_t Version; 5174 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 5175 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version)) 5176 return; 5177 5178 // TODO: Investigate what happens with the next major version of MSVC. 5179 if (Version != LangOptions::MSVC2015) { 5180 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 5181 << Attr.getName() << Version << VersionExpr->getSourceRange(); 5182 return; 5183 } 5184 5185 D->addAttr(::new (S.Context) 5186 LayoutVersionAttr(Attr.getRange(), S.Context, Version, 5187 Attr.getAttributeSpellingListIndex())); 5188 } 5189 5190 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range, 5191 unsigned AttrSpellingListIndex) { 5192 if (D->hasAttr<DLLExportAttr>()) { 5193 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'"; 5194 return nullptr; 5195 } 5196 5197 if (D->hasAttr<DLLImportAttr>()) 5198 return nullptr; 5199 5200 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex); 5201 } 5202 5203 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range, 5204 unsigned AttrSpellingListIndex) { 5205 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) { 5206 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import; 5207 D->dropAttr<DLLImportAttr>(); 5208 } 5209 5210 if (D->hasAttr<DLLExportAttr>()) 5211 return nullptr; 5212 5213 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex); 5214 } 5215 5216 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) { 5217 if (isa<ClassTemplatePartialSpecializationDecl>(D) && 5218 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5219 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) 5220 << A.getName(); 5221 return; 5222 } 5223 5224 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5225 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport && 5226 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5227 // MinGW doesn't allow dllimport on inline functions. 5228 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline) 5229 << A.getName(); 5230 return; 5231 } 5232 } 5233 5234 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 5235 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 5236 MD->getParent()->isLambda()) { 5237 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName(); 5238 return; 5239 } 5240 } 5241 5242 unsigned Index = A.getAttributeSpellingListIndex(); 5243 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport 5244 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index) 5245 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index); 5246 if (NewAttr) 5247 D->addAttr(NewAttr); 5248 } 5249 5250 MSInheritanceAttr * 5251 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, 5252 unsigned AttrSpellingListIndex, 5253 MSInheritanceAttr::Spelling SemanticSpelling) { 5254 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) { 5255 if (IA->getSemanticSpelling() == SemanticSpelling) 5256 return nullptr; 5257 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance) 5258 << 1 /*previous declaration*/; 5259 Diag(Range.getBegin(), diag::note_previous_ms_inheritance); 5260 D->dropAttr<MSInheritanceAttr>(); 5261 } 5262 5263 CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 5264 if (RD->hasDefinition()) { 5265 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase, 5266 SemanticSpelling)) { 5267 return nullptr; 5268 } 5269 } else { 5270 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) { 5271 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) 5272 << 1 /*partial specialization*/; 5273 return nullptr; 5274 } 5275 if (RD->getDescribedClassTemplate()) { 5276 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) 5277 << 0 /*primary template*/; 5278 return nullptr; 5279 } 5280 } 5281 5282 return ::new (Context) 5283 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex); 5284 } 5285 5286 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) { 5287 // The capability attributes take a single string parameter for the name of 5288 // the capability they represent. The lockable attribute does not take any 5289 // parameters. However, semantically, both attributes represent the same 5290 // concept, and so they use the same semantic attribute. Eventually, the 5291 // lockable attribute will be removed. 5292 // 5293 // For backward compatibility, any capability which has no specified string 5294 // literal will be considered a "mutex." 5295 StringRef N("mutex"); 5296 SourceLocation LiteralLoc; 5297 if (Attr.getKind() == AttributeList::AT_Capability && 5298 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc)) 5299 return; 5300 5301 // Currently, there are only two names allowed for a capability: role and 5302 // mutex (case insensitive). Diagnose other capability names. 5303 if (!N.equals_lower("mutex") && !N.equals_lower("role")) 5304 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N; 5305 5306 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N, 5307 Attr.getAttributeSpellingListIndex())); 5308 } 5309 5310 static void handleAssertCapabilityAttr(Sema &S, Decl *D, 5311 const AttributeList &Attr) { 5312 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context, 5313 Attr.getArgAsExpr(0), 5314 Attr.getAttributeSpellingListIndex())); 5315 } 5316 5317 static void handleAcquireCapabilityAttr(Sema &S, Decl *D, 5318 const AttributeList &Attr) { 5319 SmallVector<Expr*, 1> Args; 5320 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 5321 return; 5322 5323 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(), 5324 S.Context, 5325 Args.data(), Args.size(), 5326 Attr.getAttributeSpellingListIndex())); 5327 } 5328 5329 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D, 5330 const AttributeList &Attr) { 5331 SmallVector<Expr*, 2> Args; 5332 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 5333 return; 5334 5335 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(), 5336 S.Context, 5337 Attr.getArgAsExpr(0), 5338 Args.data(), 5339 Args.size(), 5340 Attr.getAttributeSpellingListIndex())); 5341 } 5342 5343 static void handleReleaseCapabilityAttr(Sema &S, Decl *D, 5344 const AttributeList &Attr) { 5345 // Check that all arguments are lockable objects. 5346 SmallVector<Expr *, 1> Args; 5347 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true); 5348 5349 D->addAttr(::new (S.Context) ReleaseCapabilityAttr( 5350 Attr.getRange(), S.Context, Args.data(), Args.size(), 5351 Attr.getAttributeSpellingListIndex())); 5352 } 5353 5354 static void handleRequiresCapabilityAttr(Sema &S, Decl *D, 5355 const AttributeList &Attr) { 5356 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 5357 return; 5358 5359 // check that all arguments are lockable objects 5360 SmallVector<Expr*, 1> Args; 5361 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 5362 if (Args.empty()) 5363 return; 5364 5365 RequiresCapabilityAttr *RCA = ::new (S.Context) 5366 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(), 5367 Args.size(), Attr.getAttributeSpellingListIndex()); 5368 5369 D->addAttr(RCA); 5370 } 5371 5372 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 5373 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) { 5374 if (NSD->isAnonymousNamespace()) { 5375 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace); 5376 // Do not want to attach the attribute to the namespace because that will 5377 // cause confusing diagnostic reports for uses of declarations within the 5378 // namespace. 5379 return; 5380 } 5381 } 5382 5383 // Handle the cases where the attribute has a text message. 5384 StringRef Str, Replacement; 5385 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) && 5386 !S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 5387 return; 5388 5389 // Only support a single optional message for Declspec and CXX11. 5390 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute()) 5391 checkAttributeAtMostNumArgs(S, Attr, 1); 5392 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) && 5393 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement)) 5394 return; 5395 5396 if (!S.getLangOpts().CPlusPlus14) 5397 if (Attr.isCXX11Attribute() && 5398 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu"))) 5399 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName(); 5400 5401 D->addAttr(::new (S.Context) 5402 DeprecatedAttr(Attr.getRange(), S.Context, Str, Replacement, 5403 Attr.getAttributeSpellingListIndex())); 5404 } 5405 5406 static bool isGlobalVar(const Decl *D) { 5407 if (const auto *S = dyn_cast<VarDecl>(D)) 5408 return S->hasGlobalStorage(); 5409 return false; 5410 } 5411 5412 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 5413 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 5414 return; 5415 5416 std::vector<StringRef> Sanitizers; 5417 5418 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) { 5419 StringRef SanitizerName; 5420 SourceLocation LiteralLoc; 5421 5422 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc)) 5423 return; 5424 5425 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0) 5426 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName; 5427 else if (isGlobalVar(D) && SanitizerName != "address") 5428 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 5429 << Attr.getName() << ExpectedFunctionOrMethod; 5430 Sanitizers.push_back(SanitizerName); 5431 } 5432 5433 D->addAttr(::new (S.Context) NoSanitizeAttr( 5434 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(), 5435 Attr.getAttributeSpellingListIndex())); 5436 } 5437 5438 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D, 5439 const AttributeList &Attr) { 5440 StringRef AttrName = Attr.getName()->getName(); 5441 normalizeName(AttrName); 5442 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName) 5443 .Case("no_address_safety_analysis", "address") 5444 .Case("no_sanitize_address", "address") 5445 .Case("no_sanitize_thread", "thread") 5446 .Case("no_sanitize_memory", "memory"); 5447 if (isGlobalVar(D) && SanitizerName != "address") 5448 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 5449 << Attr.getName() << ExpectedFunction; 5450 D->addAttr(::new (S.Context) 5451 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1, 5452 Attr.getAttributeSpellingListIndex())); 5453 } 5454 5455 static void handleInternalLinkageAttr(Sema &S, Decl *D, 5456 const AttributeList &Attr) { 5457 if (InternalLinkageAttr *Internal = 5458 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(), 5459 Attr.getAttributeSpellingListIndex())) 5460 D->addAttr(Internal); 5461 } 5462 5463 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) { 5464 if (S.LangOpts.OpenCLVersion != 200) 5465 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version) 5466 << Attr.getName() << "2.0" << 0; 5467 else 5468 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored) 5469 << Attr.getName() << "2.0"; 5470 } 5471 5472 /// Handles semantic checking for features that are common to all attributes, 5473 /// such as checking whether a parameter was properly specified, or the correct 5474 /// number of arguments were passed, etc. 5475 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D, 5476 const AttributeList &Attr) { 5477 // Several attributes carry different semantics than the parsing requires, so 5478 // those are opted out of the common handling. 5479 // 5480 // We also bail on unknown and ignored attributes because those are handled 5481 // as part of the target-specific handling logic. 5482 if (Attr.hasCustomParsing() || 5483 Attr.getKind() == AttributeList::UnknownAttribute) 5484 return false; 5485 5486 // Check whether the attribute requires specific language extensions to be 5487 // enabled. 5488 if (!Attr.diagnoseLangOpts(S)) 5489 return true; 5490 5491 if (Attr.getMinArgs() == Attr.getMaxArgs()) { 5492 // If there are no optional arguments, then checking for the argument count 5493 // is trivial. 5494 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs())) 5495 return true; 5496 } else { 5497 // There are optional arguments, so checking is slightly more involved. 5498 if (Attr.getMinArgs() && 5499 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs())) 5500 return true; 5501 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() && 5502 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs())) 5503 return true; 5504 } 5505 5506 // Check whether the attribute appertains to the given subject. 5507 if (!Attr.diagnoseAppertainsTo(S, D)) 5508 return true; 5509 5510 return false; 5511 } 5512 5513 static void handleOpenCLAccessAttr(Sema &S, Decl *D, 5514 const AttributeList &Attr) { 5515 if (D->isInvalidDecl()) 5516 return; 5517 5518 // Check if there is only one access qualifier. 5519 if (D->hasAttr<OpenCLAccessAttr>()) { 5520 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers) 5521 << D->getSourceRange(); 5522 D->setInvalidDecl(true); 5523 return; 5524 } 5525 5526 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an 5527 // image object can be read and written. 5528 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe 5529 // object. Using the read_write (or __read_write) qualifier with the pipe 5530 // qualifier is a compilation error. 5531 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) { 5532 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr(); 5533 if (Attr.getName()->getName().find("read_write") != StringRef::npos) { 5534 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) { 5535 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write) 5536 << Attr.getName() << PDecl->getType() << DeclTy->isImageType(); 5537 D->setInvalidDecl(true); 5538 return; 5539 } 5540 } 5541 } 5542 5543 D->addAttr(::new (S.Context) OpenCLAccessAttr( 5544 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 5545 } 5546 5547 //===----------------------------------------------------------------------===// 5548 // Top Level Sema Entry Points 5549 //===----------------------------------------------------------------------===// 5550 5551 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if 5552 /// the attribute applies to decls. If the attribute is a type attribute, just 5553 /// silently ignore it if a GNU attribute. 5554 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, 5555 const AttributeList &Attr, 5556 bool IncludeCXX11Attributes) { 5557 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute) 5558 return; 5559 5560 // Ignore C++11 attributes on declarator chunks: they appertain to the type 5561 // instead. 5562 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes) 5563 return; 5564 5565 // Unknown attributes are automatically warned on. Target-specific attributes 5566 // which do not apply to the current target architecture are treated as 5567 // though they were unknown attributes. 5568 if (Attr.getKind() == AttributeList::UnknownAttribute || 5569 !Attr.existsInTarget(S.Context.getTargetInfo())) { 5570 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute() 5571 ? diag::warn_unhandled_ms_attribute_ignored 5572 : diag::warn_unknown_attribute_ignored) 5573 << Attr.getName(); 5574 return; 5575 } 5576 5577 if (handleCommonAttributeFeatures(S, scope, D, Attr)) 5578 return; 5579 5580 switch (Attr.getKind()) { 5581 default: 5582 if (!Attr.isStmtAttr()) { 5583 // Type attributes are handled elsewhere; silently move on. 5584 assert(Attr.isTypeAttr() && "Non-type attribute not handled"); 5585 break; 5586 } 5587 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl) 5588 << Attr.getName() << D->getLocation(); 5589 break; 5590 case AttributeList::AT_Interrupt: 5591 handleInterruptAttr(S, D, Attr); 5592 break; 5593 case AttributeList::AT_X86ForceAlignArgPointer: 5594 handleX86ForceAlignArgPointerAttr(S, D, Attr); 5595 break; 5596 case AttributeList::AT_DLLExport: 5597 case AttributeList::AT_DLLImport: 5598 handleDLLAttr(S, D, Attr); 5599 break; 5600 case AttributeList::AT_Mips16: 5601 handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D, 5602 Attr); 5603 break; 5604 case AttributeList::AT_NoMips16: 5605 handleSimpleAttribute<NoMips16Attr>(S, D, Attr); 5606 break; 5607 case AttributeList::AT_AMDGPUFlatWorkGroupSize: 5608 handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr); 5609 break; 5610 case AttributeList::AT_AMDGPUWavesPerEU: 5611 handleAMDGPUWavesPerEUAttr(S, D, Attr); 5612 break; 5613 case AttributeList::AT_AMDGPUNumSGPR: 5614 handleAMDGPUNumSGPRAttr(S, D, Attr); 5615 break; 5616 case AttributeList::AT_AMDGPUNumVGPR: 5617 handleAMDGPUNumVGPRAttr(S, D, Attr); 5618 break; 5619 case AttributeList::AT_IBAction: 5620 handleSimpleAttribute<IBActionAttr>(S, D, Attr); 5621 break; 5622 case AttributeList::AT_IBOutlet: 5623 handleIBOutlet(S, D, Attr); 5624 break; 5625 case AttributeList::AT_IBOutletCollection: 5626 handleIBOutletCollection(S, D, Attr); 5627 break; 5628 case AttributeList::AT_IFunc: 5629 handleIFuncAttr(S, D, Attr); 5630 break; 5631 case AttributeList::AT_Alias: 5632 handleAliasAttr(S, D, Attr); 5633 break; 5634 case AttributeList::AT_Aligned: 5635 handleAlignedAttr(S, D, Attr); 5636 break; 5637 case AttributeList::AT_AlignValue: 5638 handleAlignValueAttr(S, D, Attr); 5639 break; 5640 case AttributeList::AT_AllocSize: 5641 handleAllocSizeAttr(S, D, Attr); 5642 break; 5643 case AttributeList::AT_AlwaysInline: 5644 handleAlwaysInlineAttr(S, D, Attr); 5645 break; 5646 case AttributeList::AT_AnalyzerNoReturn: 5647 handleAnalyzerNoReturnAttr(S, D, Attr); 5648 break; 5649 case AttributeList::AT_TLSModel: 5650 handleTLSModelAttr(S, D, Attr); 5651 break; 5652 case AttributeList::AT_Annotate: 5653 handleAnnotateAttr(S, D, Attr); 5654 break; 5655 case AttributeList::AT_Availability: 5656 handleAvailabilityAttr(S, D, Attr); 5657 break; 5658 case AttributeList::AT_CarriesDependency: 5659 handleDependencyAttr(S, scope, D, Attr); 5660 break; 5661 case AttributeList::AT_Common: 5662 handleCommonAttr(S, D, Attr); 5663 break; 5664 case AttributeList::AT_CUDAConstant: 5665 handleConstantAttr(S, D, Attr); 5666 break; 5667 case AttributeList::AT_PassObjectSize: 5668 handlePassObjectSizeAttr(S, D, Attr); 5669 break; 5670 case AttributeList::AT_Constructor: 5671 handleConstructorAttr(S, D, Attr); 5672 break; 5673 case AttributeList::AT_CXX11NoReturn: 5674 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr); 5675 break; 5676 case AttributeList::AT_Deprecated: 5677 handleDeprecatedAttr(S, D, Attr); 5678 break; 5679 case AttributeList::AT_Destructor: 5680 handleDestructorAttr(S, D, Attr); 5681 break; 5682 case AttributeList::AT_EnableIf: 5683 handleEnableIfAttr(S, D, Attr); 5684 break; 5685 case AttributeList::AT_ExtVectorType: 5686 handleExtVectorTypeAttr(S, scope, D, Attr); 5687 break; 5688 case AttributeList::AT_MinSize: 5689 handleMinSizeAttr(S, D, Attr); 5690 break; 5691 case AttributeList::AT_OptimizeNone: 5692 handleOptimizeNoneAttr(S, D, Attr); 5693 break; 5694 case AttributeList::AT_FlagEnum: 5695 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr); 5696 break; 5697 case AttributeList::AT_Flatten: 5698 handleSimpleAttribute<FlattenAttr>(S, D, Attr); 5699 break; 5700 case AttributeList::AT_Format: 5701 handleFormatAttr(S, D, Attr); 5702 break; 5703 case AttributeList::AT_FormatArg: 5704 handleFormatArgAttr(S, D, Attr); 5705 break; 5706 case AttributeList::AT_CUDAGlobal: 5707 handleGlobalAttr(S, D, Attr); 5708 break; 5709 case AttributeList::AT_CUDADevice: 5710 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D, 5711 Attr); 5712 break; 5713 case AttributeList::AT_CUDAHost: 5714 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, 5715 Attr); 5716 break; 5717 case AttributeList::AT_GNUInline: 5718 handleGNUInlineAttr(S, D, Attr); 5719 break; 5720 case AttributeList::AT_CUDALaunchBounds: 5721 handleLaunchBoundsAttr(S, D, Attr); 5722 break; 5723 case AttributeList::AT_Restrict: 5724 handleRestrictAttr(S, D, Attr); 5725 break; 5726 case AttributeList::AT_MayAlias: 5727 handleSimpleAttribute<MayAliasAttr>(S, D, Attr); 5728 break; 5729 case AttributeList::AT_Mode: 5730 handleModeAttr(S, D, Attr); 5731 break; 5732 case AttributeList::AT_NoAlias: 5733 handleSimpleAttribute<NoAliasAttr>(S, D, Attr); 5734 break; 5735 case AttributeList::AT_NoCommon: 5736 handleSimpleAttribute<NoCommonAttr>(S, D, Attr); 5737 break; 5738 case AttributeList::AT_NoSplitStack: 5739 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr); 5740 break; 5741 case AttributeList::AT_NonNull: 5742 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D)) 5743 handleNonNullAttrParameter(S, PVD, Attr); 5744 else 5745 handleNonNullAttr(S, D, Attr); 5746 break; 5747 case AttributeList::AT_ReturnsNonNull: 5748 handleReturnsNonNullAttr(S, D, Attr); 5749 break; 5750 case AttributeList::AT_AssumeAligned: 5751 handleAssumeAlignedAttr(S, D, Attr); 5752 break; 5753 case AttributeList::AT_Overloadable: 5754 handleSimpleAttribute<OverloadableAttr>(S, D, Attr); 5755 break; 5756 case AttributeList::AT_Ownership: 5757 handleOwnershipAttr(S, D, Attr); 5758 break; 5759 case AttributeList::AT_Cold: 5760 handleColdAttr(S, D, Attr); 5761 break; 5762 case AttributeList::AT_Hot: 5763 handleHotAttr(S, D, Attr); 5764 break; 5765 case AttributeList::AT_Naked: 5766 handleNakedAttr(S, D, Attr); 5767 break; 5768 case AttributeList::AT_NoReturn: 5769 handleNoReturnAttr(S, D, Attr); 5770 break; 5771 case AttributeList::AT_NoThrow: 5772 handleSimpleAttribute<NoThrowAttr>(S, D, Attr); 5773 break; 5774 case AttributeList::AT_CUDAShared: 5775 handleSharedAttr(S, D, Attr); 5776 break; 5777 case AttributeList::AT_VecReturn: 5778 handleVecReturnAttr(S, D, Attr); 5779 break; 5780 case AttributeList::AT_ObjCOwnership: 5781 handleObjCOwnershipAttr(S, D, Attr); 5782 break; 5783 case AttributeList::AT_ObjCPreciseLifetime: 5784 handleObjCPreciseLifetimeAttr(S, D, Attr); 5785 break; 5786 case AttributeList::AT_ObjCReturnsInnerPointer: 5787 handleObjCReturnsInnerPointerAttr(S, D, Attr); 5788 break; 5789 case AttributeList::AT_ObjCRequiresSuper: 5790 handleObjCRequiresSuperAttr(S, D, Attr); 5791 break; 5792 case AttributeList::AT_ObjCBridge: 5793 handleObjCBridgeAttr(S, scope, D, Attr); 5794 break; 5795 case AttributeList::AT_ObjCBridgeMutable: 5796 handleObjCBridgeMutableAttr(S, scope, D, Attr); 5797 break; 5798 case AttributeList::AT_ObjCBridgeRelated: 5799 handleObjCBridgeRelatedAttr(S, scope, D, Attr); 5800 break; 5801 case AttributeList::AT_ObjCDesignatedInitializer: 5802 handleObjCDesignatedInitializer(S, D, Attr); 5803 break; 5804 case AttributeList::AT_ObjCRuntimeName: 5805 handleObjCRuntimeName(S, D, Attr); 5806 break; 5807 case AttributeList::AT_ObjCRuntimeVisible: 5808 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr); 5809 break; 5810 case AttributeList::AT_ObjCBoxable: 5811 handleObjCBoxable(S, D, Attr); 5812 break; 5813 case AttributeList::AT_CFAuditedTransfer: 5814 handleCFAuditedTransferAttr(S, D, Attr); 5815 break; 5816 case AttributeList::AT_CFUnknownTransfer: 5817 handleCFUnknownTransferAttr(S, D, Attr); 5818 break; 5819 case AttributeList::AT_CFConsumed: 5820 case AttributeList::AT_NSConsumed: 5821 handleNSConsumedAttr(S, D, Attr); 5822 break; 5823 case AttributeList::AT_NSConsumesSelf: 5824 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr); 5825 break; 5826 case AttributeList::AT_NSReturnsAutoreleased: 5827 case AttributeList::AT_NSReturnsNotRetained: 5828 case AttributeList::AT_CFReturnsNotRetained: 5829 case AttributeList::AT_NSReturnsRetained: 5830 case AttributeList::AT_CFReturnsRetained: 5831 handleNSReturnsRetainedAttr(S, D, Attr); 5832 break; 5833 case AttributeList::AT_WorkGroupSizeHint: 5834 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr); 5835 break; 5836 case AttributeList::AT_ReqdWorkGroupSize: 5837 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr); 5838 break; 5839 case AttributeList::AT_VecTypeHint: 5840 handleVecTypeHint(S, D, Attr); 5841 break; 5842 case AttributeList::AT_RequireConstantInit: 5843 handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr); 5844 break; 5845 case AttributeList::AT_InitPriority: 5846 handleInitPriorityAttr(S, D, Attr); 5847 break; 5848 case AttributeList::AT_Packed: 5849 handlePackedAttr(S, D, Attr); 5850 break; 5851 case AttributeList::AT_Section: 5852 handleSectionAttr(S, D, Attr); 5853 break; 5854 case AttributeList::AT_Target: 5855 handleTargetAttr(S, D, Attr); 5856 break; 5857 case AttributeList::AT_Unavailable: 5858 handleAttrWithMessage<UnavailableAttr>(S, D, Attr); 5859 break; 5860 case AttributeList::AT_ArcWeakrefUnavailable: 5861 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr); 5862 break; 5863 case AttributeList::AT_ObjCRootClass: 5864 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr); 5865 break; 5866 case AttributeList::AT_ObjCSubclassingRestricted: 5867 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr); 5868 break; 5869 case AttributeList::AT_ObjCExplicitProtocolImpl: 5870 handleObjCSuppresProtocolAttr(S, D, Attr); 5871 break; 5872 case AttributeList::AT_ObjCRequiresPropertyDefs: 5873 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr); 5874 break; 5875 case AttributeList::AT_Unused: 5876 handleUnusedAttr(S, D, Attr); 5877 break; 5878 case AttributeList::AT_ReturnsTwice: 5879 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr); 5880 break; 5881 case AttributeList::AT_NotTailCalled: 5882 handleNotTailCalledAttr(S, D, Attr); 5883 break; 5884 case AttributeList::AT_DisableTailCalls: 5885 handleDisableTailCallsAttr(S, D, Attr); 5886 break; 5887 case AttributeList::AT_Used: 5888 handleUsedAttr(S, D, Attr); 5889 break; 5890 case AttributeList::AT_Visibility: 5891 handleVisibilityAttr(S, D, Attr, false); 5892 break; 5893 case AttributeList::AT_TypeVisibility: 5894 handleVisibilityAttr(S, D, Attr, true); 5895 break; 5896 case AttributeList::AT_WarnUnused: 5897 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr); 5898 break; 5899 case AttributeList::AT_WarnUnusedResult: 5900 handleWarnUnusedResult(S, D, Attr); 5901 break; 5902 case AttributeList::AT_Weak: 5903 handleSimpleAttribute<WeakAttr>(S, D, Attr); 5904 break; 5905 case AttributeList::AT_WeakRef: 5906 handleWeakRefAttr(S, D, Attr); 5907 break; 5908 case AttributeList::AT_WeakImport: 5909 handleWeakImportAttr(S, D, Attr); 5910 break; 5911 case AttributeList::AT_TransparentUnion: 5912 handleTransparentUnionAttr(S, D, Attr); 5913 break; 5914 case AttributeList::AT_ObjCException: 5915 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr); 5916 break; 5917 case AttributeList::AT_ObjCMethodFamily: 5918 handleObjCMethodFamilyAttr(S, D, Attr); 5919 break; 5920 case AttributeList::AT_ObjCNSObject: 5921 handleObjCNSObject(S, D, Attr); 5922 break; 5923 case AttributeList::AT_ObjCIndependentClass: 5924 handleObjCIndependentClass(S, D, Attr); 5925 break; 5926 case AttributeList::AT_Blocks: 5927 handleBlocksAttr(S, D, Attr); 5928 break; 5929 case AttributeList::AT_Sentinel: 5930 handleSentinelAttr(S, D, Attr); 5931 break; 5932 case AttributeList::AT_Const: 5933 handleSimpleAttribute<ConstAttr>(S, D, Attr); 5934 break; 5935 case AttributeList::AT_Pure: 5936 handleSimpleAttribute<PureAttr>(S, D, Attr); 5937 break; 5938 case AttributeList::AT_Cleanup: 5939 handleCleanupAttr(S, D, Attr); 5940 break; 5941 case AttributeList::AT_NoDebug: 5942 handleNoDebugAttr(S, D, Attr); 5943 break; 5944 case AttributeList::AT_NoDuplicate: 5945 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr); 5946 break; 5947 case AttributeList::AT_Convergent: 5948 handleSimpleAttribute<ConvergentAttr>(S, D, Attr); 5949 break; 5950 case AttributeList::AT_NoInline: 5951 handleSimpleAttribute<NoInlineAttr>(S, D, Attr); 5952 break; 5953 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg. 5954 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr); 5955 break; 5956 case AttributeList::AT_StdCall: 5957 case AttributeList::AT_CDecl: 5958 case AttributeList::AT_FastCall: 5959 case AttributeList::AT_ThisCall: 5960 case AttributeList::AT_Pascal: 5961 case AttributeList::AT_RegCall: 5962 case AttributeList::AT_SwiftCall: 5963 case AttributeList::AT_VectorCall: 5964 case AttributeList::AT_MSABI: 5965 case AttributeList::AT_SysVABI: 5966 case AttributeList::AT_Pcs: 5967 case AttributeList::AT_IntelOclBicc: 5968 case AttributeList::AT_PreserveMost: 5969 case AttributeList::AT_PreserveAll: 5970 handleCallConvAttr(S, D, Attr); 5971 break; 5972 case AttributeList::AT_OpenCLKernel: 5973 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr); 5974 break; 5975 case AttributeList::AT_OpenCLAccess: 5976 handleOpenCLAccessAttr(S, D, Attr); 5977 break; 5978 case AttributeList::AT_OpenCLNoSVM: 5979 handleOpenCLNoSVMAttr(S, D, Attr); 5980 break; 5981 case AttributeList::AT_SwiftContext: 5982 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext); 5983 break; 5984 case AttributeList::AT_SwiftErrorResult: 5985 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult); 5986 break; 5987 case AttributeList::AT_SwiftIndirectResult: 5988 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult); 5989 break; 5990 case AttributeList::AT_InternalLinkage: 5991 handleInternalLinkageAttr(S, D, Attr); 5992 break; 5993 case AttributeList::AT_LTOVisibilityPublic: 5994 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr); 5995 break; 5996 5997 // Microsoft attributes: 5998 case AttributeList::AT_EmptyBases: 5999 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr); 6000 break; 6001 case AttributeList::AT_LayoutVersion: 6002 handleLayoutVersion(S, D, Attr); 6003 break; 6004 case AttributeList::AT_MSNoVTable: 6005 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr); 6006 break; 6007 case AttributeList::AT_MSStruct: 6008 handleSimpleAttribute<MSStructAttr>(S, D, Attr); 6009 break; 6010 case AttributeList::AT_Uuid: 6011 handleUuidAttr(S, D, Attr); 6012 break; 6013 case AttributeList::AT_MSInheritance: 6014 handleMSInheritanceAttr(S, D, Attr); 6015 break; 6016 case AttributeList::AT_SelectAny: 6017 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr); 6018 break; 6019 case AttributeList::AT_Thread: 6020 handleDeclspecThreadAttr(S, D, Attr); 6021 break; 6022 6023 case AttributeList::AT_AbiTag: 6024 handleAbiTagAttr(S, D, Attr); 6025 break; 6026 6027 // Thread safety attributes: 6028 case AttributeList::AT_AssertExclusiveLock: 6029 handleAssertExclusiveLockAttr(S, D, Attr); 6030 break; 6031 case AttributeList::AT_AssertSharedLock: 6032 handleAssertSharedLockAttr(S, D, Attr); 6033 break; 6034 case AttributeList::AT_GuardedVar: 6035 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr); 6036 break; 6037 case AttributeList::AT_PtGuardedVar: 6038 handlePtGuardedVarAttr(S, D, Attr); 6039 break; 6040 case AttributeList::AT_ScopedLockable: 6041 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr); 6042 break; 6043 case AttributeList::AT_NoSanitize: 6044 handleNoSanitizeAttr(S, D, Attr); 6045 break; 6046 case AttributeList::AT_NoSanitizeSpecific: 6047 handleNoSanitizeSpecificAttr(S, D, Attr); 6048 break; 6049 case AttributeList::AT_NoThreadSafetyAnalysis: 6050 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr); 6051 break; 6052 case AttributeList::AT_GuardedBy: 6053 handleGuardedByAttr(S, D, Attr); 6054 break; 6055 case AttributeList::AT_PtGuardedBy: 6056 handlePtGuardedByAttr(S, D, Attr); 6057 break; 6058 case AttributeList::AT_ExclusiveTrylockFunction: 6059 handleExclusiveTrylockFunctionAttr(S, D, Attr); 6060 break; 6061 case AttributeList::AT_LockReturned: 6062 handleLockReturnedAttr(S, D, Attr); 6063 break; 6064 case AttributeList::AT_LocksExcluded: 6065 handleLocksExcludedAttr(S, D, Attr); 6066 break; 6067 case AttributeList::AT_SharedTrylockFunction: 6068 handleSharedTrylockFunctionAttr(S, D, Attr); 6069 break; 6070 case AttributeList::AT_AcquiredBefore: 6071 handleAcquiredBeforeAttr(S, D, Attr); 6072 break; 6073 case AttributeList::AT_AcquiredAfter: 6074 handleAcquiredAfterAttr(S, D, Attr); 6075 break; 6076 6077 // Capability analysis attributes. 6078 case AttributeList::AT_Capability: 6079 case AttributeList::AT_Lockable: 6080 handleCapabilityAttr(S, D, Attr); 6081 break; 6082 case AttributeList::AT_RequiresCapability: 6083 handleRequiresCapabilityAttr(S, D, Attr); 6084 break; 6085 6086 case AttributeList::AT_AssertCapability: 6087 handleAssertCapabilityAttr(S, D, Attr); 6088 break; 6089 case AttributeList::AT_AcquireCapability: 6090 handleAcquireCapabilityAttr(S, D, Attr); 6091 break; 6092 case AttributeList::AT_ReleaseCapability: 6093 handleReleaseCapabilityAttr(S, D, Attr); 6094 break; 6095 case AttributeList::AT_TryAcquireCapability: 6096 handleTryAcquireCapabilityAttr(S, D, Attr); 6097 break; 6098 6099 // Consumed analysis attributes. 6100 case AttributeList::AT_Consumable: 6101 handleConsumableAttr(S, D, Attr); 6102 break; 6103 case AttributeList::AT_ConsumableAutoCast: 6104 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr); 6105 break; 6106 case AttributeList::AT_ConsumableSetOnRead: 6107 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr); 6108 break; 6109 case AttributeList::AT_CallableWhen: 6110 handleCallableWhenAttr(S, D, Attr); 6111 break; 6112 case AttributeList::AT_ParamTypestate: 6113 handleParamTypestateAttr(S, D, Attr); 6114 break; 6115 case AttributeList::AT_ReturnTypestate: 6116 handleReturnTypestateAttr(S, D, Attr); 6117 break; 6118 case AttributeList::AT_SetTypestate: 6119 handleSetTypestateAttr(S, D, Attr); 6120 break; 6121 case AttributeList::AT_TestTypestate: 6122 handleTestTypestateAttr(S, D, Attr); 6123 break; 6124 6125 // Type safety attributes. 6126 case AttributeList::AT_ArgumentWithTypeTag: 6127 handleArgumentWithTypeTagAttr(S, D, Attr); 6128 break; 6129 case AttributeList::AT_TypeTagForDatatype: 6130 handleTypeTagForDatatypeAttr(S, D, Attr); 6131 break; 6132 case AttributeList::AT_RenderScriptKernel: 6133 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr); 6134 break; 6135 // XRay attributes. 6136 case AttributeList::AT_XRayInstrument: 6137 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr); 6138 break; 6139 } 6140 } 6141 6142 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified 6143 /// attribute list to the specified decl, ignoring any type attributes. 6144 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, 6145 const AttributeList *AttrList, 6146 bool IncludeCXX11Attributes) { 6147 for (const AttributeList* l = AttrList; l; l = l->getNext()) 6148 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes); 6149 6150 // FIXME: We should be able to handle these cases in TableGen. 6151 // GCC accepts 6152 // static int a9 __attribute__((weakref)); 6153 // but that looks really pointless. We reject it. 6154 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) { 6155 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) 6156 << cast<NamedDecl>(D); 6157 D->dropAttr<WeakRefAttr>(); 6158 return; 6159 } 6160 6161 // FIXME: We should be able to handle this in TableGen as well. It would be 6162 // good to have a way to specify "these attributes must appear as a group", 6163 // for these. Additionally, it would be good to have a way to specify "these 6164 // attribute must never appear as a group" for attributes like cold and hot. 6165 if (!D->hasAttr<OpenCLKernelAttr>()) { 6166 // These attributes cannot be applied to a non-kernel function. 6167 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) { 6168 // FIXME: This emits a different error message than 6169 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction. 6170 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 6171 D->setInvalidDecl(); 6172 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) { 6173 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 6174 D->setInvalidDecl(); 6175 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) { 6176 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 6177 D->setInvalidDecl(); 6178 } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) { 6179 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 6180 << A << ExpectedKernelFunction; 6181 D->setInvalidDecl(); 6182 } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) { 6183 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 6184 << A << ExpectedKernelFunction; 6185 D->setInvalidDecl(); 6186 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) { 6187 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 6188 << A << ExpectedKernelFunction; 6189 D->setInvalidDecl(); 6190 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) { 6191 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 6192 << A << ExpectedKernelFunction; 6193 D->setInvalidDecl(); 6194 } 6195 } 6196 } 6197 6198 // Annotation attributes are the only attributes allowed after an access 6199 // specifier. 6200 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 6201 const AttributeList *AttrList) { 6202 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6203 if (l->getKind() == AttributeList::AT_Annotate) { 6204 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute()); 6205 } else { 6206 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec); 6207 return true; 6208 } 6209 } 6210 6211 return false; 6212 } 6213 6214 /// checkUnusedDeclAttributes - Check a list of attributes to see if it 6215 /// contains any decl attributes that we should warn about. 6216 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) { 6217 for ( ; A; A = A->getNext()) { 6218 // Only warn if the attribute is an unignored, non-type attribute. 6219 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue; 6220 if (A->getKind() == AttributeList::IgnoredAttribute) continue; 6221 6222 if (A->getKind() == AttributeList::UnknownAttribute) { 6223 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored) 6224 << A->getName() << A->getRange(); 6225 } else { 6226 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl) 6227 << A->getName() << A->getRange(); 6228 } 6229 } 6230 } 6231 6232 /// checkUnusedDeclAttributes - Given a declarator which is not being 6233 /// used to build a declaration, complain about any decl attributes 6234 /// which might be lying around on it. 6235 void Sema::checkUnusedDeclAttributes(Declarator &D) { 6236 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList()); 6237 ::checkUnusedDeclAttributes(*this, D.getAttributes()); 6238 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) 6239 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs()); 6240 } 6241 6242 /// DeclClonePragmaWeak - clone existing decl (maybe definition), 6243 /// \#pragma weak needs a non-definition decl and source may not have one. 6244 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 6245 SourceLocation Loc) { 6246 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND)); 6247 NamedDecl *NewD = nullptr; 6248 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 6249 FunctionDecl *NewFD; 6250 // FIXME: Missing call to CheckFunctionDeclaration(). 6251 // FIXME: Mangling? 6252 // FIXME: Is the qualifier info correct? 6253 // FIXME: Is the DeclContext correct? 6254 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(), 6255 Loc, Loc, DeclarationName(II), 6256 FD->getType(), FD->getTypeSourceInfo(), 6257 SC_None, false/*isInlineSpecified*/, 6258 FD->hasPrototype(), 6259 false/*isConstexprSpecified*/); 6260 NewD = NewFD; 6261 6262 if (FD->getQualifier()) 6263 NewFD->setQualifierInfo(FD->getQualifierLoc()); 6264 6265 // Fake up parameter variables; they are declared as if this were 6266 // a typedef. 6267 QualType FDTy = FD->getType(); 6268 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) { 6269 SmallVector<ParmVarDecl*, 16> Params; 6270 for (const auto &AI : FT->param_types()) { 6271 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI); 6272 Param->setScopeInfo(0, Params.size()); 6273 Params.push_back(Param); 6274 } 6275 NewFD->setParams(Params); 6276 } 6277 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) { 6278 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(), 6279 VD->getInnerLocStart(), VD->getLocation(), II, 6280 VD->getType(), VD->getTypeSourceInfo(), 6281 VD->getStorageClass()); 6282 if (VD->getQualifier()) { 6283 VarDecl *NewVD = cast<VarDecl>(NewD); 6284 NewVD->setQualifierInfo(VD->getQualifierLoc()); 6285 } 6286 } 6287 return NewD; 6288 } 6289 6290 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak 6291 /// applied to it, possibly with an alias. 6292 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) { 6293 if (W.getUsed()) return; // only do this once 6294 W.setUsed(true); 6295 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...)) 6296 IdentifierInfo *NDId = ND->getIdentifier(); 6297 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation()); 6298 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(), 6299 W.getLocation())); 6300 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); 6301 WeakTopLevelDecl.push_back(NewD); 6302 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin 6303 // to insert Decl at TU scope, sorry. 6304 DeclContext *SavedContext = CurContext; 6305 CurContext = Context.getTranslationUnitDecl(); 6306 NewD->setDeclContext(CurContext); 6307 NewD->setLexicalDeclContext(CurContext); 6308 PushOnScopeChains(NewD, S); 6309 CurContext = SavedContext; 6310 } else { // just add weak to existing 6311 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); 6312 } 6313 } 6314 6315 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) { 6316 // It's valid to "forward-declare" #pragma weak, in which case we 6317 // have to do this. 6318 LoadExternalWeakUndeclaredIdentifiers(); 6319 if (!WeakUndeclaredIdentifiers.empty()) { 6320 NamedDecl *ND = nullptr; 6321 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 6322 if (VD->isExternC()) 6323 ND = VD; 6324 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 6325 if (FD->isExternC()) 6326 ND = FD; 6327 if (ND) { 6328 if (IdentifierInfo *Id = ND->getIdentifier()) { 6329 auto I = WeakUndeclaredIdentifiers.find(Id); 6330 if (I != WeakUndeclaredIdentifiers.end()) { 6331 WeakInfo W = I->second; 6332 DeclApplyPragmaWeak(S, ND, W); 6333 WeakUndeclaredIdentifiers[Id] = W; 6334 } 6335 } 6336 } 6337 } 6338 } 6339 6340 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in 6341 /// it, apply them to D. This is a bit tricky because PD can have attributes 6342 /// specified in many different places, and we need to find and apply them all. 6343 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) { 6344 // Apply decl attributes from the DeclSpec if present. 6345 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList()) 6346 ProcessDeclAttributeList(S, D, Attrs); 6347 6348 // Walk the declarator structure, applying decl attributes that were in a type 6349 // position to the decl itself. This handles cases like: 6350 // int *__attr__(x)** D; 6351 // when X is a decl attribute. 6352 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) 6353 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs()) 6354 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false); 6355 6356 // Finally, apply any attributes on the decl itself. 6357 if (const AttributeList *Attrs = PD.getAttributes()) 6358 ProcessDeclAttributeList(S, D, Attrs); 6359 } 6360 6361 /// Is the given declaration allowed to use a forbidden type? 6362 /// If so, it'll still be annotated with an attribute that makes it 6363 /// illegal to actually use. 6364 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl, 6365 const DelayedDiagnostic &diag, 6366 UnavailableAttr::ImplicitReason &reason) { 6367 // Private ivars are always okay. Unfortunately, people don't 6368 // always properly make their ivars private, even in system headers. 6369 // Plus we need to make fields okay, too. 6370 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) && 6371 !isa<FunctionDecl>(decl)) 6372 return false; 6373 6374 // Silently accept unsupported uses of __weak in both user and system 6375 // declarations when it's been disabled, for ease of integration with 6376 // -fno-objc-arc files. We do have to take some care against attempts 6377 // to define such things; for now, we've only done that for ivars 6378 // and properties. 6379 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) { 6380 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled || 6381 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) { 6382 reason = UnavailableAttr::IR_ForbiddenWeak; 6383 return true; 6384 } 6385 } 6386 6387 // Allow all sorts of things in system headers. 6388 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) { 6389 // Currently, all the failures dealt with this way are due to ARC 6390 // restrictions. 6391 reason = UnavailableAttr::IR_ARCForbiddenType; 6392 return true; 6393 } 6394 6395 return false; 6396 } 6397 6398 /// Handle a delayed forbidden-type diagnostic. 6399 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag, 6400 Decl *decl) { 6401 auto reason = UnavailableAttr::IR_None; 6402 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) { 6403 assert(reason && "didn't set reason?"); 6404 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason, 6405 diag.Loc)); 6406 return; 6407 } 6408 if (S.getLangOpts().ObjCAutoRefCount) 6409 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) { 6410 // FIXME: we may want to suppress diagnostics for all 6411 // kind of forbidden type messages on unavailable functions. 6412 if (FD->hasAttr<UnavailableAttr>() && 6413 diag.getForbiddenTypeDiagnostic() == 6414 diag::err_arc_array_param_no_ownership) { 6415 diag.Triggered = true; 6416 return; 6417 } 6418 } 6419 6420 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic()) 6421 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument(); 6422 diag.Triggered = true; 6423 } 6424 6425 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context, 6426 const Decl *D) { 6427 // Check each AvailabilityAttr to find the one for this platform. 6428 for (const auto *A : D->attrs()) { 6429 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) { 6430 // FIXME: this is copied from CheckAvailability. We should try to 6431 // de-duplicate. 6432 6433 // Check if this is an App Extension "platform", and if so chop off 6434 // the suffix for matching with the actual platform. 6435 StringRef ActualPlatform = Avail->getPlatform()->getName(); 6436 StringRef RealizedPlatform = ActualPlatform; 6437 if (Context.getLangOpts().AppExt) { 6438 size_t suffix = RealizedPlatform.rfind("_app_extension"); 6439 if (suffix != StringRef::npos) 6440 RealizedPlatform = RealizedPlatform.slice(0, suffix); 6441 } 6442 6443 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName(); 6444 6445 // Match the platform name. 6446 if (RealizedPlatform == TargetPlatform) 6447 return Avail; 6448 } 6449 } 6450 return nullptr; 6451 } 6452 6453 /// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in 6454 /// the context of \c Ctx. For example, we should emit an unavailable diagnostic 6455 /// in a deprecated context, but not the other way around. 6456 static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K, 6457 VersionTuple DeclVersion, 6458 Decl *Ctx) { 6459 assert(K != AR_Available && "Expected an unavailable declaration here!"); 6460 6461 // Checks if we should emit the availability diagnostic in the context of C. 6462 auto CheckContext = [&](const Decl *C) { 6463 if (K == AR_NotYetIntroduced) { 6464 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C)) 6465 if (AA->getIntroduced() >= DeclVersion) 6466 return true; 6467 } else if (K == AR_Deprecated) 6468 if (C->isDeprecated()) 6469 return true; 6470 6471 if (C->isUnavailable()) 6472 return true; 6473 return false; 6474 }; 6475 6476 // FIXME: This is a temporary workaround! Some existing Apple headers depends 6477 // on nested declarations in an @interface having the availability of the 6478 // interface when they really shouldn't: they are members of the enclosing 6479 // context, and can referenced from there. 6480 if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) { 6481 auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext); 6482 if (CheckContext(OrigCtx)) 6483 return false; 6484 6485 // An implementation implicitly has the availability of the interface. 6486 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) { 6487 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface()) 6488 if (CheckContext(Interface)) 6489 return false; 6490 } 6491 // A category implicitly has the availability of the interface. 6492 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx)) 6493 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface()) 6494 if (CheckContext(Interface)) 6495 return false; 6496 } 6497 6498 do { 6499 if (CheckContext(Ctx)) 6500 return false; 6501 6502 // An implementation implicitly has the availability of the interface. 6503 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) { 6504 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface()) 6505 if (CheckContext(Interface)) 6506 return false; 6507 } 6508 // A category implicitly has the availability of the interface. 6509 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx)) 6510 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface()) 6511 if (CheckContext(Interface)) 6512 return false; 6513 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext()))); 6514 6515 return true; 6516 } 6517 6518 static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K, 6519 Decl *Ctx, const NamedDecl *D, 6520 StringRef Message, SourceLocation Loc, 6521 const ObjCInterfaceDecl *UnknownObjCClass, 6522 const ObjCPropertyDecl *ObjCProperty, 6523 bool ObjCPropertyAccess) { 6524 // Diagnostics for deprecated or unavailable. 6525 unsigned diag, diag_message, diag_fwdclass_message; 6526 unsigned diag_available_here = diag::note_availability_specified_here; 6527 6528 // Matches 'diag::note_property_attribute' options. 6529 unsigned property_note_select; 6530 6531 // Matches diag::note_availability_specified_here. 6532 unsigned available_here_select_kind; 6533 6534 VersionTuple DeclVersion; 6535 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, D)) 6536 DeclVersion = AA->getIntroduced(); 6537 6538 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx)) 6539 return; 6540 6541 switch (K) { 6542 case AR_Deprecated: 6543 diag = !ObjCPropertyAccess ? diag::warn_deprecated 6544 : diag::warn_property_method_deprecated; 6545 diag_message = diag::warn_deprecated_message; 6546 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message; 6547 property_note_select = /* deprecated */ 0; 6548 available_here_select_kind = /* deprecated */ 2; 6549 break; 6550 6551 case AR_Unavailable: 6552 diag = !ObjCPropertyAccess ? diag::err_unavailable 6553 : diag::err_property_method_unavailable; 6554 diag_message = diag::err_unavailable_message; 6555 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message; 6556 property_note_select = /* unavailable */ 1; 6557 available_here_select_kind = /* unavailable */ 0; 6558 6559 if (auto attr = D->getAttr<UnavailableAttr>()) { 6560 if (attr->isImplicit() && attr->getImplicitReason()) { 6561 // Most of these failures are due to extra restrictions in ARC; 6562 // reflect that in the primary diagnostic when applicable. 6563 auto flagARCError = [&] { 6564 if (S.getLangOpts().ObjCAutoRefCount && 6565 S.getSourceManager().isInSystemHeader(D->getLocation())) 6566 diag = diag::err_unavailable_in_arc; 6567 }; 6568 6569 switch (attr->getImplicitReason()) { 6570 case UnavailableAttr::IR_None: break; 6571 6572 case UnavailableAttr::IR_ARCForbiddenType: 6573 flagARCError(); 6574 diag_available_here = diag::note_arc_forbidden_type; 6575 break; 6576 6577 case UnavailableAttr::IR_ForbiddenWeak: 6578 if (S.getLangOpts().ObjCWeakRuntime) 6579 diag_available_here = diag::note_arc_weak_disabled; 6580 else 6581 diag_available_here = diag::note_arc_weak_no_runtime; 6582 break; 6583 6584 case UnavailableAttr::IR_ARCForbiddenConversion: 6585 flagARCError(); 6586 diag_available_here = diag::note_performs_forbidden_arc_conversion; 6587 break; 6588 6589 case UnavailableAttr::IR_ARCInitReturnsUnrelated: 6590 flagARCError(); 6591 diag_available_here = diag::note_arc_init_returns_unrelated; 6592 break; 6593 6594 case UnavailableAttr::IR_ARCFieldWithOwnership: 6595 flagARCError(); 6596 diag_available_here = diag::note_arc_field_with_ownership; 6597 break; 6598 } 6599 } 6600 } 6601 break; 6602 6603 case AR_NotYetIntroduced: 6604 diag = diag::warn_partial_availability; 6605 diag_message = diag::warn_partial_message; 6606 diag_fwdclass_message = diag::warn_partial_fwdclass_message; 6607 property_note_select = /* partial */ 2; 6608 available_here_select_kind = /* partial */ 3; 6609 break; 6610 6611 case AR_Available: 6612 llvm_unreachable("Warning for availability of available declaration?"); 6613 } 6614 6615 CharSourceRange UseRange; 6616 StringRef Replacement; 6617 if (K == AR_Deprecated) { 6618 if (auto attr = D->getAttr<DeprecatedAttr>()) 6619 Replacement = attr->getReplacement(); 6620 if (auto attr = getAttrForPlatform(S.Context, D)) 6621 Replacement = attr->getReplacement(); 6622 6623 if (!Replacement.empty()) 6624 UseRange = 6625 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 6626 } 6627 6628 if (!Message.empty()) { 6629 S.Diag(Loc, diag_message) << D << Message 6630 << (UseRange.isValid() ? 6631 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); 6632 if (ObjCProperty) 6633 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) 6634 << ObjCProperty->getDeclName() << property_note_select; 6635 } else if (!UnknownObjCClass) { 6636 S.Diag(Loc, diag) << D 6637 << (UseRange.isValid() ? 6638 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); 6639 if (ObjCProperty) 6640 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) 6641 << ObjCProperty->getDeclName() << property_note_select; 6642 } else { 6643 S.Diag(Loc, diag_fwdclass_message) << D 6644 << (UseRange.isValid() ? 6645 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); 6646 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class); 6647 } 6648 6649 // The declaration can have multiple availability attributes, we are looking 6650 // at one of them. 6651 const AvailabilityAttr *A = getAttrForPlatform(S.Context, D); 6652 if (A && A->isInherited()) { 6653 for (const Decl *Redecl = D->getMostRecentDecl(); Redecl; 6654 Redecl = Redecl->getPreviousDecl()) { 6655 const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context, 6656 Redecl); 6657 if (AForRedecl && !AForRedecl->isInherited()) { 6658 // If D is a declaration with inherited attributes, the note should 6659 // point to the declaration with actual attributes. 6660 S.Diag(Redecl->getLocation(), diag_available_here) << D 6661 << available_here_select_kind; 6662 break; 6663 } 6664 } 6665 } 6666 else 6667 S.Diag(D->getLocation(), diag_available_here) 6668 << D << available_here_select_kind; 6669 6670 if (K == AR_NotYetIntroduced) 6671 S.Diag(Loc, diag::note_partial_availability_silence) << D; 6672 } 6673 6674 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD, 6675 Decl *Ctx) { 6676 assert(DD.Kind == DelayedDiagnostic::Availability && 6677 "Expected an availability diagnostic here"); 6678 6679 DD.Triggered = true; 6680 DoEmitAvailabilityWarning( 6681 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityDecl(), 6682 DD.getAvailabilityMessage(), DD.Loc, DD.getUnknownObjCClass(), 6683 DD.getObjCProperty(), false); 6684 } 6685 6686 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) { 6687 assert(DelayedDiagnostics.getCurrentPool()); 6688 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool(); 6689 DelayedDiagnostics.popWithoutEmitting(state); 6690 6691 // When delaying diagnostics to run in the context of a parsed 6692 // declaration, we only want to actually emit anything if parsing 6693 // succeeds. 6694 if (!decl) return; 6695 6696 // We emit all the active diagnostics in this pool or any of its 6697 // parents. In general, we'll get one pool for the decl spec 6698 // and a child pool for each declarator; in a decl group like: 6699 // deprecated_typedef foo, *bar, baz(); 6700 // only the declarator pops will be passed decls. This is correct; 6701 // we really do need to consider delayed diagnostics from the decl spec 6702 // for each of the different declarations. 6703 const DelayedDiagnosticPool *pool = &poppedPool; 6704 do { 6705 for (DelayedDiagnosticPool::pool_iterator 6706 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) { 6707 // This const_cast is a bit lame. Really, Triggered should be mutable. 6708 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i); 6709 if (diag.Triggered) 6710 continue; 6711 6712 switch (diag.Kind) { 6713 case DelayedDiagnostic::Availability: 6714 // Don't bother giving deprecation/unavailable diagnostics if 6715 // the decl is invalid. 6716 if (!decl->isInvalidDecl()) 6717 handleDelayedAvailabilityCheck(*this, diag, decl); 6718 break; 6719 6720 case DelayedDiagnostic::Access: 6721 HandleDelayedAccessCheck(diag, decl); 6722 break; 6723 6724 case DelayedDiagnostic::ForbiddenType: 6725 handleDelayedForbiddenType(*this, diag, decl); 6726 break; 6727 } 6728 } 6729 } while ((pool = pool->getParent())); 6730 } 6731 6732 /// Given a set of delayed diagnostics, re-emit them as if they had 6733 /// been delayed in the current context instead of in the given pool. 6734 /// Essentially, this just moves them to the current pool. 6735 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) { 6736 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool(); 6737 assert(curPool && "re-emitting in undelayed context not supported"); 6738 curPool->steal(pool); 6739 } 6740 6741 void Sema::EmitAvailabilityWarning(AvailabilityResult AR, 6742 NamedDecl *D, StringRef Message, 6743 SourceLocation Loc, 6744 const ObjCInterfaceDecl *UnknownObjCClass, 6745 const ObjCPropertyDecl *ObjCProperty, 6746 bool ObjCPropertyAccess) { 6747 // Delay if we're currently parsing a declaration. 6748 if (DelayedDiagnostics.shouldDelayDiagnostics()) { 6749 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability( 6750 AR, Loc, D, UnknownObjCClass, ObjCProperty, Message, 6751 ObjCPropertyAccess)); 6752 return; 6753 } 6754 6755 Decl *Ctx = cast<Decl>(getCurLexicalContext()); 6756 DoEmitAvailabilityWarning(*this, AR, Ctx, D, Message, Loc, UnknownObjCClass, 6757 ObjCProperty, ObjCPropertyAccess); 6758 } 6759 6760 namespace { 6761 6762 /// \brief This class implements -Wunguarded-availability. 6763 /// 6764 /// This is done with a traversal of the AST of a function that makes reference 6765 /// to a partially available declaration. Whenever we encounter an \c if of the 6766 /// form: \c if(@available(...)), we use the version from the condition to visit 6767 /// the then statement. 6768 class DiagnoseUnguardedAvailability 6769 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> { 6770 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base; 6771 6772 Sema &SemaRef; 6773 Decl *Ctx; 6774 6775 /// Stack of potentially nested 'if (@available(...))'s. 6776 SmallVector<VersionTuple, 8> AvailabilityStack; 6777 6778 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range); 6779 6780 public: 6781 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx) 6782 : SemaRef(SemaRef), Ctx(Ctx) { 6783 AvailabilityStack.push_back( 6784 SemaRef.Context.getTargetInfo().getPlatformMinVersion()); 6785 } 6786 6787 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); } 6788 6789 bool TraverseIfStmt(IfStmt *If); 6790 6791 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) { 6792 if (ObjCMethodDecl *D = Msg->getMethodDecl()) 6793 DiagnoseDeclAvailability( 6794 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd())); 6795 return true; 6796 } 6797 6798 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 6799 DiagnoseDeclAvailability(DRE->getDecl(), 6800 SourceRange(DRE->getLocStart(), DRE->getLocEnd())); 6801 return true; 6802 } 6803 6804 bool VisitMemberExpr(MemberExpr *ME) { 6805 DiagnoseDeclAvailability(ME->getMemberDecl(), 6806 SourceRange(ME->getLocStart(), ME->getLocEnd())); 6807 return true; 6808 } 6809 6810 bool VisitTypeLoc(TypeLoc Ty); 6811 }; 6812 6813 void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability( 6814 NamedDecl *D, SourceRange Range) { 6815 6816 VersionTuple ContextVersion = AvailabilityStack.back(); 6817 if (AvailabilityResult Result = 6818 SemaRef.ShouldDiagnoseAvailabilityOfDecl(D, nullptr)) { 6819 // All other diagnostic kinds have already been handled in 6820 // DiagnoseAvailabilityOfDecl. 6821 if (Result != AR_NotYetIntroduced) 6822 return; 6823 6824 const AvailabilityAttr *AA = getAttrForPlatform(SemaRef.getASTContext(), D); 6825 VersionTuple Introduced = AA->getIntroduced(); 6826 6827 if (ContextVersion >= Introduced) 6828 return; 6829 6830 // If the context of this function is less available than D, we should not 6831 // emit a diagnostic. 6832 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx)) 6833 return; 6834 6835 SemaRef.Diag(Range.getBegin(), diag::warn_unguarded_availability) 6836 << Range << D 6837 << AvailabilityAttr::getPrettyPlatformName( 6838 SemaRef.getASTContext().getTargetInfo().getPlatformName()) 6839 << Introduced.getAsString(); 6840 6841 SemaRef.Diag(D->getLocation(), diag::note_availability_specified_here) 6842 << D << /* partial */ 3; 6843 6844 // FIXME: Replace this with a fixit diagnostic. 6845 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence) 6846 << Range << D; 6847 } 6848 } 6849 6850 bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) { 6851 const Type *TyPtr = Ty.getTypePtr(); 6852 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()}; 6853 6854 if (const TagType *TT = dyn_cast<TagType>(TyPtr)) { 6855 TagDecl *TD = TT->getDecl(); 6856 DiagnoseDeclAvailability(TD, Range); 6857 6858 } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) { 6859 TypedefNameDecl *D = TD->getDecl(); 6860 DiagnoseDeclAvailability(D, Range); 6861 6862 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) { 6863 if (NamedDecl *D = ObjCO->getInterface()) 6864 DiagnoseDeclAvailability(D, Range); 6865 } 6866 6867 return true; 6868 } 6869 6870 bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) { 6871 VersionTuple CondVersion; 6872 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) { 6873 CondVersion = E->getVersion(); 6874 6875 // If we're using the '*' case here or if this check is redundant, then we 6876 // use the enclosing version to check both branches. 6877 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back()) 6878 return Base::TraverseStmt(If->getThen()) && 6879 Base::TraverseStmt(If->getElse()); 6880 } else { 6881 // This isn't an availability checking 'if', we can just continue. 6882 return Base::TraverseIfStmt(If); 6883 } 6884 6885 AvailabilityStack.push_back(CondVersion); 6886 bool ShouldContinue = TraverseStmt(If->getThen()); 6887 AvailabilityStack.pop_back(); 6888 6889 return ShouldContinue && TraverseStmt(If->getElse()); 6890 } 6891 6892 } // end anonymous namespace 6893 6894 void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) { 6895 Stmt *Body = nullptr; 6896 6897 if (auto *FD = D->getAsFunction()) { 6898 // FIXME: We only examine the pattern decl for availability violations now, 6899 // but we should also examine instantiated templates. 6900 if (FD->isTemplateInstantiation()) 6901 return; 6902 6903 Body = FD->getBody(); 6904 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) 6905 Body = MD->getBody(); 6906 6907 assert(Body && "Need a body here!"); 6908 6909 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body); 6910 } 6911