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