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