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