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