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