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