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() || Expr->isValueDependent() || 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() || IdxExpr->isValueDependent() || 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 (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) { 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 int PriorityModifier = AL.isPragmaClangAttribute() 2500 ? Sema::AP_PragmaClangAttribute 2501 : Sema::AP_Explicit; 2502 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2503 ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version, 2504 Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement, 2505 Sema::AMK_None, PriorityModifier); 2506 if (NewAttr) 2507 D->addAttr(NewAttr); 2508 2509 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning 2510 // matches before the start of the watchOS platform. 2511 if (S.Context.getTargetInfo().getTriple().isWatchOS()) { 2512 IdentifierInfo *NewII = nullptr; 2513 if (II->getName() == "ios") 2514 NewII = &S.Context.Idents.get("watchos"); 2515 else if (II->getName() == "ios_app_extension") 2516 NewII = &S.Context.Idents.get("watchos_app_extension"); 2517 2518 if (NewII) { 2519 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple { 2520 if (Version.empty()) 2521 return Version; 2522 auto Major = Version.getMajor(); 2523 auto NewMajor = Major >= 9 ? Major - 7 : 0; 2524 if (NewMajor >= 2) { 2525 if (Version.getMinor().hasValue()) { 2526 if (Version.getSubminor().hasValue()) 2527 return VersionTuple(NewMajor, Version.getMinor().getValue(), 2528 Version.getSubminor().getValue()); 2529 else 2530 return VersionTuple(NewMajor, Version.getMinor().getValue()); 2531 } 2532 return VersionTuple(NewMajor); 2533 } 2534 2535 return VersionTuple(2, 0); 2536 }; 2537 2538 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version); 2539 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version); 2540 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version); 2541 2542 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2543 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated, 2544 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement, 2545 Sema::AMK_None, 2546 PriorityModifier + Sema::AP_InferredFromOtherPlatform); 2547 if (NewAttr) 2548 D->addAttr(NewAttr); 2549 } 2550 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) { 2551 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning 2552 // matches before the start of the tvOS platform. 2553 IdentifierInfo *NewII = nullptr; 2554 if (II->getName() == "ios") 2555 NewII = &S.Context.Idents.get("tvos"); 2556 else if (II->getName() == "ios_app_extension") 2557 NewII = &S.Context.Idents.get("tvos_app_extension"); 2558 2559 if (NewII) { 2560 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2561 ND, AL, NewII, true /*Implicit*/, Introduced.Version, 2562 Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict, 2563 Replacement, Sema::AMK_None, 2564 PriorityModifier + Sema::AP_InferredFromOtherPlatform); 2565 if (NewAttr) 2566 D->addAttr(NewAttr); 2567 } 2568 } else if (S.Context.getTargetInfo().getTriple().getOS() == 2569 llvm::Triple::IOS && 2570 S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) { 2571 auto GetSDKInfo = [&]() { 2572 return S.getDarwinSDKInfoForAvailabilityChecking(AL.getRange().getBegin(), 2573 "macOS"); 2574 }; 2575 2576 // Transcribe "ios" to "maccatalyst" (and add a new attribute). 2577 IdentifierInfo *NewII = nullptr; 2578 if (II->getName() == "ios") 2579 NewII = &S.Context.Idents.get("maccatalyst"); 2580 else if (II->getName() == "ios_app_extension") 2581 NewII = &S.Context.Idents.get("maccatalyst_app_extension"); 2582 if (NewII) { 2583 auto MinMacCatalystVersion = [](const VersionTuple &V) { 2584 if (V.empty()) 2585 return V; 2586 if (V.getMajor() < 13 || 2587 (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1)) 2588 return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1. 2589 return V; 2590 }; 2591 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2592 ND, AL.getRange(), NewII, true /*Implicit*/, 2593 MinMacCatalystVersion(Introduced.Version), 2594 MinMacCatalystVersion(Deprecated.Version), 2595 MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str, 2596 IsStrict, Replacement, Sema::AMK_None, 2597 PriorityModifier + Sema::AP_InferredFromOtherPlatform); 2598 if (NewAttr) 2599 D->addAttr(NewAttr); 2600 } else if (II->getName() == "macos" && GetSDKInfo() && 2601 (!Introduced.Version.empty() || !Deprecated.Version.empty() || 2602 !Obsoleted.Version.empty())) { 2603 if (const auto *MacOStoMacCatalystMapping = 2604 GetSDKInfo()->getVersionMapping( 2605 DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) { 2606 // Infer Mac Catalyst availability from the macOS availability attribute 2607 // if it has versioned availability. Don't infer 'unavailable'. This 2608 // inferred availability has lower priority than the other availability 2609 // attributes that are inferred from 'ios'. 2610 NewII = &S.Context.Idents.get("maccatalyst"); 2611 auto RemapMacOSVersion = 2612 [&](const VersionTuple &V) -> Optional<VersionTuple> { 2613 if (V.empty()) 2614 return None; 2615 // API_TO_BE_DEPRECATED is 100000. 2616 if (V.getMajor() == 100000) 2617 return VersionTuple(100000); 2618 // The minimum iosmac version is 13.1 2619 return MacOStoMacCatalystMapping->map(V, VersionTuple(13, 1), None); 2620 }; 2621 Optional<VersionTuple> NewIntroduced = 2622 RemapMacOSVersion(Introduced.Version), 2623 NewDeprecated = 2624 RemapMacOSVersion(Deprecated.Version), 2625 NewObsoleted = 2626 RemapMacOSVersion(Obsoleted.Version); 2627 if (NewIntroduced || NewDeprecated || NewObsoleted) { 2628 auto VersionOrEmptyVersion = 2629 [](const Optional<VersionTuple> &V) -> VersionTuple { 2630 return V ? *V : VersionTuple(); 2631 }; 2632 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2633 ND, AL.getRange(), NewII, true /*Implicit*/, 2634 VersionOrEmptyVersion(NewIntroduced), 2635 VersionOrEmptyVersion(NewDeprecated), 2636 VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str, 2637 IsStrict, Replacement, Sema::AMK_None, 2638 PriorityModifier + Sema::AP_InferredFromOtherPlatform + 2639 Sema::AP_InferredFromOtherPlatform); 2640 if (NewAttr) 2641 D->addAttr(NewAttr); 2642 } 2643 } 2644 } 2645 } 2646 } 2647 2648 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D, 2649 const ParsedAttr &AL) { 2650 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 3)) 2651 return; 2652 2653 StringRef Language; 2654 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0))) 2655 Language = SE->getString(); 2656 StringRef DefinedIn; 2657 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1))) 2658 DefinedIn = SE->getString(); 2659 bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr; 2660 2661 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr( 2662 S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration)); 2663 } 2664 2665 template <class T> 2666 static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI, 2667 typename T::VisibilityType value) { 2668 T *existingAttr = D->getAttr<T>(); 2669 if (existingAttr) { 2670 typename T::VisibilityType existingValue = existingAttr->getVisibility(); 2671 if (existingValue == value) 2672 return nullptr; 2673 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility); 2674 S.Diag(CI.getLoc(), diag::note_previous_attribute); 2675 D->dropAttr<T>(); 2676 } 2677 return ::new (S.Context) T(S.Context, CI, value); 2678 } 2679 2680 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, 2681 const AttributeCommonInfo &CI, 2682 VisibilityAttr::VisibilityType Vis) { 2683 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis); 2684 } 2685 2686 TypeVisibilityAttr * 2687 Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 2688 TypeVisibilityAttr::VisibilityType Vis) { 2689 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis); 2690 } 2691 2692 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL, 2693 bool isTypeVisibility) { 2694 // Visibility attributes don't mean anything on a typedef. 2695 if (isa<TypedefNameDecl>(D)) { 2696 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL; 2697 return; 2698 } 2699 2700 // 'type_visibility' can only go on a type or namespace. 2701 if (isTypeVisibility && 2702 !(isa<TagDecl>(D) || 2703 isa<ObjCInterfaceDecl>(D) || 2704 isa<NamespaceDecl>(D))) { 2705 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type) 2706 << AL << ExpectedTypeOrNamespace; 2707 return; 2708 } 2709 2710 // Check that the argument is a string literal. 2711 StringRef TypeStr; 2712 SourceLocation LiteralLoc; 2713 if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc)) 2714 return; 2715 2716 VisibilityAttr::VisibilityType type; 2717 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) { 2718 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL 2719 << TypeStr; 2720 return; 2721 } 2722 2723 // Complain about attempts to use protected visibility on targets 2724 // (like Darwin) that don't support it. 2725 if (type == VisibilityAttr::Protected && 2726 !S.Context.getTargetInfo().hasProtectedVisibility()) { 2727 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility); 2728 type = VisibilityAttr::Default; 2729 } 2730 2731 Attr *newAttr; 2732 if (isTypeVisibility) { 2733 newAttr = S.mergeTypeVisibilityAttr( 2734 D, AL, (TypeVisibilityAttr::VisibilityType)type); 2735 } else { 2736 newAttr = S.mergeVisibilityAttr(D, AL, type); 2737 } 2738 if (newAttr) 2739 D->addAttr(newAttr); 2740 } 2741 2742 static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2743 // objc_direct cannot be set on methods declared in the context of a protocol 2744 if (isa<ObjCProtocolDecl>(D->getDeclContext())) { 2745 S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false; 2746 return; 2747 } 2748 2749 if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) { 2750 handleSimpleAttribute<ObjCDirectAttr>(S, D, AL); 2751 } else { 2752 S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL; 2753 } 2754 } 2755 2756 static void handleObjCDirectMembersAttr(Sema &S, Decl *D, 2757 const ParsedAttr &AL) { 2758 if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) { 2759 handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL); 2760 } else { 2761 S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL; 2762 } 2763 } 2764 2765 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2766 const auto *M = cast<ObjCMethodDecl>(D); 2767 if (!AL.isArgIdent(0)) { 2768 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 2769 << AL << 1 << AANT_ArgumentIdentifier; 2770 return; 2771 } 2772 2773 IdentifierLoc *IL = AL.getArgAsIdent(0); 2774 ObjCMethodFamilyAttr::FamilyKind F; 2775 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) { 2776 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident; 2777 return; 2778 } 2779 2780 if (F == ObjCMethodFamilyAttr::OMF_init && 2781 !M->getReturnType()->isObjCObjectPointerType()) { 2782 S.Diag(M->getLocation(), diag::err_init_method_bad_return_type) 2783 << M->getReturnType(); 2784 // Ignore the attribute. 2785 return; 2786 } 2787 2788 D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F)); 2789 } 2790 2791 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) { 2792 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2793 QualType T = TD->getUnderlyingType(); 2794 if (!T->isCARCBridgableType()) { 2795 S.Diag(TD->getLocation(), diag::err_nsobject_attribute); 2796 return; 2797 } 2798 } 2799 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) { 2800 QualType T = PD->getType(); 2801 if (!T->isCARCBridgableType()) { 2802 S.Diag(PD->getLocation(), diag::err_nsobject_attribute); 2803 return; 2804 } 2805 } 2806 else { 2807 // It is okay to include this attribute on properties, e.g.: 2808 // 2809 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); 2810 // 2811 // In this case it follows tradition and suppresses an error in the above 2812 // case. 2813 S.Diag(D->getLocation(), diag::warn_nsobject_attribute); 2814 } 2815 D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL)); 2816 } 2817 2818 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) { 2819 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2820 QualType T = TD->getUnderlyingType(); 2821 if (!T->isObjCObjectPointerType()) { 2822 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute); 2823 return; 2824 } 2825 } else { 2826 S.Diag(D->getLocation(), diag::warn_independentclass_attribute); 2827 return; 2828 } 2829 D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL)); 2830 } 2831 2832 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2833 if (!AL.isArgIdent(0)) { 2834 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 2835 << AL << 1 << AANT_ArgumentIdentifier; 2836 return; 2837 } 2838 2839 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 2840 BlocksAttr::BlockType type; 2841 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) { 2842 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; 2843 return; 2844 } 2845 2846 D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type)); 2847 } 2848 2849 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2850 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel; 2851 if (AL.getNumArgs() > 0) { 2852 Expr *E = AL.getArgAsExpr(0); 2853 Optional<llvm::APSInt> Idx = llvm::APSInt(32); 2854 if (E->isTypeDependent() || E->isValueDependent() || 2855 !(Idx = E->getIntegerConstantExpr(S.Context))) { 2856 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 2857 << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange(); 2858 return; 2859 } 2860 2861 if (Idx->isSigned() && Idx->isNegative()) { 2862 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero) 2863 << E->getSourceRange(); 2864 return; 2865 } 2866 2867 sentinel = Idx->getZExtValue(); 2868 } 2869 2870 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos; 2871 if (AL.getNumArgs() > 1) { 2872 Expr *E = AL.getArgAsExpr(1); 2873 Optional<llvm::APSInt> Idx = llvm::APSInt(32); 2874 if (E->isTypeDependent() || E->isValueDependent() || 2875 !(Idx = E->getIntegerConstantExpr(S.Context))) { 2876 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 2877 << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange(); 2878 return; 2879 } 2880 nullPos = Idx->getZExtValue(); 2881 2882 if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) { 2883 // FIXME: This error message could be improved, it would be nice 2884 // to say what the bounds actually are. 2885 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one) 2886 << E->getSourceRange(); 2887 return; 2888 } 2889 } 2890 2891 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 2892 const FunctionType *FT = FD->getType()->castAs<FunctionType>(); 2893 if (isa<FunctionNoProtoType>(FT)) { 2894 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments); 2895 return; 2896 } 2897 2898 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2899 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2900 return; 2901 } 2902 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 2903 if (!MD->isVariadic()) { 2904 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2905 return; 2906 } 2907 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) { 2908 if (!BD->isVariadic()) { 2909 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1; 2910 return; 2911 } 2912 } else if (const auto *V = dyn_cast<VarDecl>(D)) { 2913 QualType Ty = V->getType(); 2914 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 2915 const FunctionType *FT = Ty->isFunctionPointerType() 2916 ? D->getFunctionType() 2917 : Ty->castAs<BlockPointerType>() 2918 ->getPointeeType() 2919 ->castAs<FunctionType>(); 2920 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2921 int m = Ty->isFunctionPointerType() ? 0 : 1; 2922 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m; 2923 return; 2924 } 2925 } else { 2926 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 2927 << AL << ExpectedFunctionMethodOrBlock; 2928 return; 2929 } 2930 } else { 2931 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 2932 << AL << ExpectedFunctionMethodOrBlock; 2933 return; 2934 } 2935 D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos)); 2936 } 2937 2938 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) { 2939 if (D->getFunctionType() && 2940 D->getFunctionType()->getReturnType()->isVoidType() && 2941 !isa<CXXConstructorDecl>(D)) { 2942 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0; 2943 return; 2944 } 2945 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 2946 if (MD->getReturnType()->isVoidType()) { 2947 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1; 2948 return; 2949 } 2950 2951 StringRef Str; 2952 if (AL.isStandardAttributeSyntax() && !AL.getScopeName()) { 2953 // The standard attribute cannot be applied to variable declarations such 2954 // as a function pointer. 2955 if (isa<VarDecl>(D)) 2956 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str) 2957 << AL << "functions, classes, or enumerations"; 2958 2959 // If this is spelled as the standard C++17 attribute, but not in C++17, 2960 // warn about using it as an extension. If there are attribute arguments, 2961 // then claim it's a C++2a extension instead. 2962 // FIXME: If WG14 does not seem likely to adopt the same feature, add an 2963 // extension warning for C2x mode. 2964 const LangOptions &LO = S.getLangOpts(); 2965 if (AL.getNumArgs() == 1) { 2966 if (LO.CPlusPlus && !LO.CPlusPlus20) 2967 S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL; 2968 2969 // Since this this is spelled [[nodiscard]], get the optional string 2970 // literal. If in C++ mode, but not in C++2a mode, diagnose as an 2971 // extension. 2972 // FIXME: C2x should support this feature as well, even as an extension. 2973 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr)) 2974 return; 2975 } else if (LO.CPlusPlus && !LO.CPlusPlus17) 2976 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL; 2977 } 2978 2979 D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str)); 2980 } 2981 2982 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2983 // weak_import only applies to variable & function declarations. 2984 bool isDef = false; 2985 if (!D->canBeWeakImported(isDef)) { 2986 if (isDef) 2987 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition) 2988 << "weak_import"; 2989 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) || 2990 (S.Context.getTargetInfo().getTriple().isOSDarwin() && 2991 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) { 2992 // Nothing to warn about here. 2993 } else 2994 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 2995 << AL << ExpectedVariableOrFunction; 2996 2997 return; 2998 } 2999 3000 D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL)); 3001 } 3002 3003 // Handles reqd_work_group_size and work_group_size_hint. 3004 template <typename WorkGroupAttr> 3005 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) { 3006 uint32_t WGSize[3]; 3007 for (unsigned i = 0; i < 3; ++i) { 3008 const Expr *E = AL.getArgAsExpr(i); 3009 if (!checkUInt32Argument(S, AL, E, WGSize[i], i, 3010 /*StrictlyUnsigned=*/true)) 3011 return; 3012 if (WGSize[i] == 0) { 3013 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero) 3014 << AL << E->getSourceRange(); 3015 return; 3016 } 3017 } 3018 3019 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>(); 3020 if (Existing && !(Existing->getXDim() == WGSize[0] && 3021 Existing->getYDim() == WGSize[1] && 3022 Existing->getZDim() == WGSize[2])) 3023 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 3024 3025 D->addAttr(::new (S.Context) 3026 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2])); 3027 } 3028 3029 // Handles intel_reqd_sub_group_size. 3030 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) { 3031 uint32_t SGSize; 3032 const Expr *E = AL.getArgAsExpr(0); 3033 if (!checkUInt32Argument(S, AL, E, SGSize)) 3034 return; 3035 if (SGSize == 0) { 3036 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero) 3037 << AL << E->getSourceRange(); 3038 return; 3039 } 3040 3041 OpenCLIntelReqdSubGroupSizeAttr *Existing = 3042 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>(); 3043 if (Existing && Existing->getSubGroupSize() != SGSize) 3044 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 3045 3046 D->addAttr(::new (S.Context) 3047 OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize)); 3048 } 3049 3050 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) { 3051 if (!AL.hasParsedType()) { 3052 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; 3053 return; 3054 } 3055 3056 TypeSourceInfo *ParmTSI = nullptr; 3057 QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI); 3058 assert(ParmTSI && "no type source info for attribute argument"); 3059 3060 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() && 3061 (ParmType->isBooleanType() || 3062 !ParmType->isIntegralType(S.getASTContext()))) { 3063 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL; 3064 return; 3065 } 3066 3067 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) { 3068 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) { 3069 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 3070 return; 3071 } 3072 } 3073 3074 D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI)); 3075 } 3076 3077 SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, 3078 StringRef Name) { 3079 // Explicit or partial specializations do not inherit 3080 // the section attribute from the primary template. 3081 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3082 if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate && 3083 FD->isFunctionTemplateSpecialization()) 3084 return nullptr; 3085 } 3086 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) { 3087 if (ExistingAttr->getName() == Name) 3088 return nullptr; 3089 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section) 3090 << 1 /*section*/; 3091 Diag(CI.getLoc(), diag::note_previous_attribute); 3092 return nullptr; 3093 } 3094 return ::new (Context) SectionAttr(Context, CI, Name); 3095 } 3096 3097 /// Used to implement to perform semantic checking on 3098 /// attribute((section("foo"))) specifiers. 3099 /// 3100 /// In this case, "foo" is passed in to be checked. If the section 3101 /// specifier is invalid, return an Error that indicates the problem. 3102 /// 3103 /// This is a simple quality of implementation feature to catch errors 3104 /// and give good diagnostics in cases when the assembler or code generator 3105 /// would otherwise reject the section specifier. 3106 llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) { 3107 if (!Context.getTargetInfo().getTriple().isOSDarwin()) 3108 return llvm::Error::success(); 3109 3110 // Let MCSectionMachO validate this. 3111 StringRef Segment, Section; 3112 unsigned TAA, StubSize; 3113 bool HasTAA; 3114 return llvm::MCSectionMachO::ParseSectionSpecifier(SecName, Segment, Section, 3115 TAA, HasTAA, StubSize); 3116 } 3117 3118 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) { 3119 if (llvm::Error E = isValidSectionSpecifier(SecName)) { 3120 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) 3121 << toString(std::move(E)) << 1 /*'section'*/; 3122 return false; 3123 } 3124 return true; 3125 } 3126 3127 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3128 // Make sure that there is a string literal as the sections's single 3129 // argument. 3130 StringRef Str; 3131 SourceLocation LiteralLoc; 3132 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc)) 3133 return; 3134 3135 if (!S.checkSectionName(LiteralLoc, Str)) 3136 return; 3137 3138 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str); 3139 if (NewAttr) { 3140 D->addAttr(NewAttr); 3141 if (isa<FunctionDecl, FunctionTemplateDecl, ObjCMethodDecl, 3142 ObjCPropertyDecl>(D)) 3143 S.UnifySection(NewAttr->getName(), 3144 ASTContext::PSF_Execute | ASTContext::PSF_Read, 3145 cast<NamedDecl>(D)); 3146 } 3147 } 3148 3149 // This is used for `__declspec(code_seg("segname"))` on a decl. 3150 // `#pragma code_seg("segname")` uses checkSectionName() instead. 3151 static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc, 3152 StringRef CodeSegName) { 3153 if (llvm::Error E = S.isValidSectionSpecifier(CodeSegName)) { 3154 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) 3155 << toString(std::move(E)) << 0 /*'code-seg'*/; 3156 return false; 3157 } 3158 3159 return true; 3160 } 3161 3162 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, 3163 StringRef Name) { 3164 // Explicit or partial specializations do not inherit 3165 // the code_seg attribute from the primary template. 3166 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3167 if (FD->isFunctionTemplateSpecialization()) 3168 return nullptr; 3169 } 3170 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) { 3171 if (ExistingAttr->getName() == Name) 3172 return nullptr; 3173 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section) 3174 << 0 /*codeseg*/; 3175 Diag(CI.getLoc(), diag::note_previous_attribute); 3176 return nullptr; 3177 } 3178 return ::new (Context) CodeSegAttr(Context, CI, Name); 3179 } 3180 3181 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3182 StringRef Str; 3183 SourceLocation LiteralLoc; 3184 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc)) 3185 return; 3186 if (!checkCodeSegName(S, LiteralLoc, Str)) 3187 return; 3188 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) { 3189 if (!ExistingAttr->isImplicit()) { 3190 S.Diag(AL.getLoc(), 3191 ExistingAttr->getName() == Str 3192 ? diag::warn_duplicate_codeseg_attribute 3193 : diag::err_conflicting_codeseg_attribute); 3194 return; 3195 } 3196 D->dropAttr<CodeSegAttr>(); 3197 } 3198 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str)) 3199 D->addAttr(CSA); 3200 } 3201 3202 // Check for things we'd like to warn about. Multiversioning issues are 3203 // handled later in the process, once we know how many exist. 3204 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) { 3205 enum FirstParam { Unsupported, Duplicate, Unknown }; 3206 enum SecondParam { None, Architecture, Tune }; 3207 if (AttrStr.find("fpmath=") != StringRef::npos) 3208 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3209 << Unsupported << None << "fpmath="; 3210 3211 // Diagnose use of tune if target doesn't support it. 3212 if (!Context.getTargetInfo().supportsTargetAttributeTune() && 3213 AttrStr.find("tune=") != StringRef::npos) 3214 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3215 << Unsupported << None << "tune="; 3216 3217 ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr); 3218 3219 if (!ParsedAttrs.Architecture.empty() && 3220 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture)) 3221 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3222 << Unknown << Architecture << ParsedAttrs.Architecture; 3223 3224 if (!ParsedAttrs.Tune.empty() && 3225 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune)) 3226 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3227 << Unknown << Tune << ParsedAttrs.Tune; 3228 3229 if (ParsedAttrs.DuplicateArchitecture) 3230 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3231 << Duplicate << None << "arch="; 3232 if (ParsedAttrs.DuplicateTune) 3233 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3234 << Duplicate << None << "tune="; 3235 3236 for (const auto &Feature : ParsedAttrs.Features) { 3237 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -. 3238 if (!Context.getTargetInfo().isValidFeatureName(CurFeature)) 3239 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3240 << Unsupported << None << CurFeature; 3241 } 3242 3243 TargetInfo::BranchProtectionInfo BPI; 3244 StringRef Error; 3245 if (!ParsedAttrs.BranchProtection.empty() && 3246 !Context.getTargetInfo().validateBranchProtection( 3247 ParsedAttrs.BranchProtection, BPI, Error)) { 3248 if (Error.empty()) 3249 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3250 << Unsupported << None << "branch-protection"; 3251 else 3252 return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec) 3253 << Error; 3254 } 3255 3256 return false; 3257 } 3258 3259 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3260 StringRef Str; 3261 SourceLocation LiteralLoc; 3262 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) || 3263 S.checkTargetAttr(LiteralLoc, Str)) 3264 return; 3265 3266 TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str); 3267 D->addAttr(NewAttr); 3268 } 3269 3270 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3271 Expr *E = AL.getArgAsExpr(0); 3272 uint32_t VecWidth; 3273 if (!checkUInt32Argument(S, AL, E, VecWidth)) { 3274 AL.setInvalid(); 3275 return; 3276 } 3277 3278 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>(); 3279 if (Existing && Existing->getVectorWidth() != VecWidth) { 3280 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 3281 return; 3282 } 3283 3284 D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth)); 3285 } 3286 3287 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3288 Expr *E = AL.getArgAsExpr(0); 3289 SourceLocation Loc = E->getExprLoc(); 3290 FunctionDecl *FD = nullptr; 3291 DeclarationNameInfo NI; 3292 3293 // gcc only allows for simple identifiers. Since we support more than gcc, we 3294 // will warn the user. 3295 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 3296 if (DRE->hasQualifier()) 3297 S.Diag(Loc, diag::warn_cleanup_ext); 3298 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 3299 NI = DRE->getNameInfo(); 3300 if (!FD) { 3301 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1 3302 << NI.getName(); 3303 return; 3304 } 3305 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 3306 if (ULE->hasExplicitTemplateArgs()) 3307 S.Diag(Loc, diag::warn_cleanup_ext); 3308 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true); 3309 NI = ULE->getNameInfo(); 3310 if (!FD) { 3311 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2 3312 << NI.getName(); 3313 if (ULE->getType() == S.Context.OverloadTy) 3314 S.NoteAllOverloadCandidates(ULE); 3315 return; 3316 } 3317 } else { 3318 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0; 3319 return; 3320 } 3321 3322 if (FD->getNumParams() != 1) { 3323 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg) 3324 << NI.getName(); 3325 return; 3326 } 3327 3328 // We're currently more strict than GCC about what function types we accept. 3329 // If this ever proves to be a problem it should be easy to fix. 3330 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType()); 3331 QualType ParamTy = FD->getParamDecl(0)->getType(); 3332 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), 3333 ParamTy, Ty) != Sema::Compatible) { 3334 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type) 3335 << NI.getName() << ParamTy << Ty; 3336 return; 3337 } 3338 3339 D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD)); 3340 } 3341 3342 static void handleEnumExtensibilityAttr(Sema &S, Decl *D, 3343 const ParsedAttr &AL) { 3344 if (!AL.isArgIdent(0)) { 3345 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 3346 << AL << 0 << AANT_ArgumentIdentifier; 3347 return; 3348 } 3349 3350 EnumExtensibilityAttr::Kind ExtensibilityKind; 3351 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 3352 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(), 3353 ExtensibilityKind)) { 3354 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; 3355 return; 3356 } 3357 3358 D->addAttr(::new (S.Context) 3359 EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind)); 3360 } 3361 3362 /// Handle __attribute__((format_arg((idx)))) attribute based on 3363 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 3364 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3365 Expr *IdxExpr = AL.getArgAsExpr(0); 3366 ParamIdx Idx; 3367 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx)) 3368 return; 3369 3370 // Make sure the format string is really a string. 3371 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex()); 3372 3373 bool NotNSStringTy = !isNSStringType(Ty, S.Context); 3374 if (NotNSStringTy && 3375 !isCFStringType(Ty, S.Context) && 3376 (!Ty->isPointerType() || 3377 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) { 3378 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3379 << "a string type" << IdxExpr->getSourceRange() 3380 << getFunctionOrMethodParamRange(D, 0); 3381 return; 3382 } 3383 Ty = getFunctionOrMethodResultType(D); 3384 if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true) && 3385 !isCFStringType(Ty, S.Context) && 3386 (!Ty->isPointerType() || 3387 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) { 3388 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not) 3389 << (NotNSStringTy ? "string type" : "NSString") 3390 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); 3391 return; 3392 } 3393 3394 D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx)); 3395 } 3396 3397 enum FormatAttrKind { 3398 CFStringFormat, 3399 NSStringFormat, 3400 StrftimeFormat, 3401 SupportedFormat, 3402 IgnoredFormat, 3403 InvalidFormat 3404 }; 3405 3406 /// getFormatAttrKind - Map from format attribute names to supported format 3407 /// types. 3408 static FormatAttrKind getFormatAttrKind(StringRef Format) { 3409 return llvm::StringSwitch<FormatAttrKind>(Format) 3410 // Check for formats that get handled specially. 3411 .Case("NSString", NSStringFormat) 3412 .Case("CFString", CFStringFormat) 3413 .Case("strftime", StrftimeFormat) 3414 3415 // Otherwise, check for supported formats. 3416 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat) 3417 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat) 3418 .Case("kprintf", SupportedFormat) // OpenBSD. 3419 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD. 3420 .Case("os_trace", SupportedFormat) 3421 .Case("os_log", SupportedFormat) 3422 3423 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat) 3424 .Default(InvalidFormat); 3425 } 3426 3427 /// Handle __attribute__((init_priority(priority))) attributes based on 3428 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html 3429 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3430 if (!S.getLangOpts().CPlusPlus) { 3431 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL; 3432 return; 3433 } 3434 3435 if (S.getCurFunctionOrMethodDecl()) { 3436 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr); 3437 AL.setInvalid(); 3438 return; 3439 } 3440 QualType T = cast<VarDecl>(D)->getType(); 3441 if (S.Context.getAsArrayType(T)) 3442 T = S.Context.getBaseElementType(T); 3443 if (!T->getAs<RecordType>()) { 3444 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr); 3445 AL.setInvalid(); 3446 return; 3447 } 3448 3449 Expr *E = AL.getArgAsExpr(0); 3450 uint32_t prioritynum; 3451 if (!checkUInt32Argument(S, AL, E, prioritynum)) { 3452 AL.setInvalid(); 3453 return; 3454 } 3455 3456 // Only perform the priority check if the attribute is outside of a system 3457 // header. Values <= 100 are reserved for the implementation, and libc++ 3458 // benefits from being able to specify values in that range. 3459 if ((prioritynum < 101 || prioritynum > 65535) && 3460 !S.getSourceManager().isInSystemHeader(AL.getLoc())) { 3461 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range) 3462 << E->getSourceRange() << AL << 101 << 65535; 3463 AL.setInvalid(); 3464 return; 3465 } 3466 D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum)); 3467 } 3468 3469 ErrorAttr *Sema::mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, 3470 StringRef NewUserDiagnostic) { 3471 if (const auto *EA = D->getAttr<ErrorAttr>()) { 3472 std::string NewAttr = CI.getNormalizedFullName(); 3473 assert((NewAttr == "error" || NewAttr == "warning") && 3474 "unexpected normalized full name"); 3475 bool Match = (EA->isError() && NewAttr == "error") || 3476 (EA->isWarning() && NewAttr == "warning"); 3477 if (!Match) { 3478 Diag(EA->getLocation(), diag::err_attributes_are_not_compatible) 3479 << CI << EA; 3480 Diag(CI.getLoc(), diag::note_conflicting_attribute); 3481 return nullptr; 3482 } 3483 if (EA->getUserDiagnostic() != NewUserDiagnostic) { 3484 Diag(CI.getLoc(), diag::warn_duplicate_attribute) << EA; 3485 Diag(EA->getLoc(), diag::note_previous_attribute); 3486 } 3487 D->dropAttr<ErrorAttr>(); 3488 } 3489 return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic); 3490 } 3491 3492 FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, 3493 IdentifierInfo *Format, int FormatIdx, 3494 int FirstArg) { 3495 // Check whether we already have an equivalent format attribute. 3496 for (auto *F : D->specific_attrs<FormatAttr>()) { 3497 if (F->getType() == Format && 3498 F->getFormatIdx() == FormatIdx && 3499 F->getFirstArg() == FirstArg) { 3500 // If we don't have a valid location for this attribute, adopt the 3501 // location. 3502 if (F->getLocation().isInvalid()) 3503 F->setRange(CI.getRange()); 3504 return nullptr; 3505 } 3506 } 3507 3508 return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg); 3509 } 3510 3511 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on 3512 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 3513 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3514 if (!AL.isArgIdent(0)) { 3515 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 3516 << AL << 1 << AANT_ArgumentIdentifier; 3517 return; 3518 } 3519 3520 // In C++ the implicit 'this' function parameter also counts, and they are 3521 // counted from one. 3522 bool HasImplicitThisParam = isInstanceMethod(D); 3523 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam; 3524 3525 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 3526 StringRef Format = II->getName(); 3527 3528 if (normalizeName(Format)) { 3529 // If we've modified the string name, we need a new identifier for it. 3530 II = &S.Context.Idents.get(Format); 3531 } 3532 3533 // Check for supported formats. 3534 FormatAttrKind Kind = getFormatAttrKind(Format); 3535 3536 if (Kind == IgnoredFormat) 3537 return; 3538 3539 if (Kind == InvalidFormat) { 3540 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 3541 << AL << II->getName(); 3542 return; 3543 } 3544 3545 // checks for the 2nd argument 3546 Expr *IdxExpr = AL.getArgAsExpr(1); 3547 uint32_t Idx; 3548 if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2)) 3549 return; 3550 3551 if (Idx < 1 || Idx > NumArgs) { 3552 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3553 << AL << 2 << IdxExpr->getSourceRange(); 3554 return; 3555 } 3556 3557 // FIXME: Do we need to bounds check? 3558 unsigned ArgIdx = Idx - 1; 3559 3560 if (HasImplicitThisParam) { 3561 if (ArgIdx == 0) { 3562 S.Diag(AL.getLoc(), 3563 diag::err_format_attribute_implicit_this_format_string) 3564 << IdxExpr->getSourceRange(); 3565 return; 3566 } 3567 ArgIdx--; 3568 } 3569 3570 // make sure the format string is really a string 3571 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx); 3572 3573 if (Kind == CFStringFormat) { 3574 if (!isCFStringType(Ty, S.Context)) { 3575 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3576 << "a CFString" << IdxExpr->getSourceRange() 3577 << getFunctionOrMethodParamRange(D, ArgIdx); 3578 return; 3579 } 3580 } else if (Kind == NSStringFormat) { 3581 // FIXME: do we need to check if the type is NSString*? What are the 3582 // semantics? 3583 if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true)) { 3584 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3585 << "an NSString" << IdxExpr->getSourceRange() 3586 << getFunctionOrMethodParamRange(D, ArgIdx); 3587 return; 3588 } 3589 } else if (!Ty->isPointerType() || 3590 !Ty->castAs<PointerType>()->getPointeeType()->isCharType()) { 3591 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3592 << "a string type" << IdxExpr->getSourceRange() 3593 << getFunctionOrMethodParamRange(D, ArgIdx); 3594 return; 3595 } 3596 3597 // check the 3rd argument 3598 Expr *FirstArgExpr = AL.getArgAsExpr(2); 3599 uint32_t FirstArg; 3600 if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3)) 3601 return; 3602 3603 // check if the function is variadic if the 3rd argument non-zero 3604 if (FirstArg != 0) { 3605 if (isFunctionOrMethodVariadic(D)) { 3606 ++NumArgs; // +1 for ... 3607 } else { 3608 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic); 3609 return; 3610 } 3611 } 3612 3613 // strftime requires FirstArg to be 0 because it doesn't read from any 3614 // variable the input is just the current time + the format string. 3615 if (Kind == StrftimeFormat) { 3616 if (FirstArg != 0) { 3617 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter) 3618 << FirstArgExpr->getSourceRange(); 3619 return; 3620 } 3621 // if 0 it disables parameter checking (to use with e.g. va_list) 3622 } else if (FirstArg != 0 && FirstArg != NumArgs) { 3623 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3624 << AL << 3 << FirstArgExpr->getSourceRange(); 3625 return; 3626 } 3627 3628 FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg); 3629 if (NewAttr) 3630 D->addAttr(NewAttr); 3631 } 3632 3633 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes. 3634 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3635 // The index that identifies the callback callee is mandatory. 3636 if (AL.getNumArgs() == 0) { 3637 S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee) 3638 << AL.getRange(); 3639 return; 3640 } 3641 3642 bool HasImplicitThisParam = isInstanceMethod(D); 3643 int32_t NumArgs = getFunctionOrMethodNumParams(D); 3644 3645 FunctionDecl *FD = D->getAsFunction(); 3646 assert(FD && "Expected a function declaration!"); 3647 3648 llvm::StringMap<int> NameIdxMapping; 3649 NameIdxMapping["__"] = -1; 3650 3651 NameIdxMapping["this"] = 0; 3652 3653 int Idx = 1; 3654 for (const ParmVarDecl *PVD : FD->parameters()) 3655 NameIdxMapping[PVD->getName()] = Idx++; 3656 3657 auto UnknownName = NameIdxMapping.end(); 3658 3659 SmallVector<int, 8> EncodingIndices; 3660 for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) { 3661 SourceRange SR; 3662 int32_t ArgIdx; 3663 3664 if (AL.isArgIdent(I)) { 3665 IdentifierLoc *IdLoc = AL.getArgAsIdent(I); 3666 auto It = NameIdxMapping.find(IdLoc->Ident->getName()); 3667 if (It == UnknownName) { 3668 S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown) 3669 << IdLoc->Ident << IdLoc->Loc; 3670 return; 3671 } 3672 3673 SR = SourceRange(IdLoc->Loc); 3674 ArgIdx = It->second; 3675 } else if (AL.isArgExpr(I)) { 3676 Expr *IdxExpr = AL.getArgAsExpr(I); 3677 3678 // If the expression is not parseable as an int32_t we have a problem. 3679 if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1, 3680 false)) { 3681 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3682 << AL << (I + 1) << IdxExpr->getSourceRange(); 3683 return; 3684 } 3685 3686 // Check oob, excluding the special values, 0 and -1. 3687 if (ArgIdx < -1 || ArgIdx > NumArgs) { 3688 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3689 << AL << (I + 1) << IdxExpr->getSourceRange(); 3690 return; 3691 } 3692 3693 SR = IdxExpr->getSourceRange(); 3694 } else { 3695 llvm_unreachable("Unexpected ParsedAttr argument type!"); 3696 } 3697 3698 if (ArgIdx == 0 && !HasImplicitThisParam) { 3699 S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available) 3700 << (I + 1) << SR; 3701 return; 3702 } 3703 3704 // Adjust for the case we do not have an implicit "this" parameter. In this 3705 // case we decrease all positive values by 1 to get LLVM argument indices. 3706 if (!HasImplicitThisParam && ArgIdx > 0) 3707 ArgIdx -= 1; 3708 3709 EncodingIndices.push_back(ArgIdx); 3710 } 3711 3712 int CalleeIdx = EncodingIndices.front(); 3713 // Check if the callee index is proper, thus not "this" and not "unknown". 3714 // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam" 3715 // is false and positive if "HasImplicitThisParam" is true. 3716 if (CalleeIdx < (int)HasImplicitThisParam) { 3717 S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee) 3718 << AL.getRange(); 3719 return; 3720 } 3721 3722 // Get the callee type, note the index adjustment as the AST doesn't contain 3723 // the this type (which the callee cannot reference anyway!). 3724 const Type *CalleeType = 3725 getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam) 3726 .getTypePtr(); 3727 if (!CalleeType || !CalleeType->isFunctionPointerType()) { 3728 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type) 3729 << AL.getRange(); 3730 return; 3731 } 3732 3733 const Type *CalleeFnType = 3734 CalleeType->getPointeeType()->getUnqualifiedDesugaredType(); 3735 3736 // TODO: Check the type of the callee arguments. 3737 3738 const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType); 3739 if (!CalleeFnProtoType) { 3740 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type) 3741 << AL.getRange(); 3742 return; 3743 } 3744 3745 if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) { 3746 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) 3747 << AL << (unsigned)(EncodingIndices.size() - 1); 3748 return; 3749 } 3750 3751 if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) { 3752 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) 3753 << AL << (unsigned)(EncodingIndices.size() - 1); 3754 return; 3755 } 3756 3757 if (CalleeFnProtoType->isVariadic()) { 3758 S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange(); 3759 return; 3760 } 3761 3762 // Do not allow multiple callback attributes. 3763 if (D->hasAttr<CallbackAttr>()) { 3764 S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange(); 3765 return; 3766 } 3767 3768 D->addAttr(::new (S.Context) CallbackAttr( 3769 S.Context, AL, EncodingIndices.data(), EncodingIndices.size())); 3770 } 3771 3772 static bool isFunctionLike(const Type &T) { 3773 // Check for explicit function types. 3774 // 'called_once' is only supported in Objective-C and it has 3775 // function pointers and block pointers. 3776 return T.isFunctionPointerType() || T.isBlockPointerType(); 3777 } 3778 3779 /// Handle 'called_once' attribute. 3780 static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3781 // 'called_once' only applies to parameters representing functions. 3782 QualType T = cast<ParmVarDecl>(D)->getType(); 3783 3784 if (!isFunctionLike(*T)) { 3785 S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type); 3786 return; 3787 } 3788 3789 D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL)); 3790 } 3791 3792 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3793 // Try to find the underlying union declaration. 3794 RecordDecl *RD = nullptr; 3795 const auto *TD = dyn_cast<TypedefNameDecl>(D); 3796 if (TD && TD->getUnderlyingType()->isUnionType()) 3797 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl(); 3798 else 3799 RD = dyn_cast<RecordDecl>(D); 3800 3801 if (!RD || !RD->isUnion()) { 3802 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL 3803 << ExpectedUnion; 3804 return; 3805 } 3806 3807 if (!RD->isCompleteDefinition()) { 3808 if (!RD->isBeingDefined()) 3809 S.Diag(AL.getLoc(), 3810 diag::warn_transparent_union_attribute_not_definition); 3811 return; 3812 } 3813 3814 RecordDecl::field_iterator Field = RD->field_begin(), 3815 FieldEnd = RD->field_end(); 3816 if (Field == FieldEnd) { 3817 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields); 3818 return; 3819 } 3820 3821 FieldDecl *FirstField = *Field; 3822 QualType FirstType = FirstField->getType(); 3823 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) { 3824 S.Diag(FirstField->getLocation(), 3825 diag::warn_transparent_union_attribute_floating) 3826 << FirstType->isVectorType() << FirstType; 3827 return; 3828 } 3829 3830 if (FirstType->isIncompleteType()) 3831 return; 3832 uint64_t FirstSize = S.Context.getTypeSize(FirstType); 3833 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType); 3834 for (; Field != FieldEnd; ++Field) { 3835 QualType FieldType = Field->getType(); 3836 if (FieldType->isIncompleteType()) 3837 return; 3838 // FIXME: this isn't fully correct; we also need to test whether the 3839 // members of the union would all have the same calling convention as the 3840 // first member of the union. Checking just the size and alignment isn't 3841 // sufficient (consider structs passed on the stack instead of in registers 3842 // as an example). 3843 if (S.Context.getTypeSize(FieldType) != FirstSize || 3844 S.Context.getTypeAlign(FieldType) > FirstAlign) { 3845 // Warn if we drop the attribute. 3846 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize; 3847 unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType) 3848 : S.Context.getTypeAlign(FieldType); 3849 S.Diag(Field->getLocation(), 3850 diag::warn_transparent_union_attribute_field_size_align) 3851 << isSize << *Field << FieldBits; 3852 unsigned FirstBits = isSize ? FirstSize : FirstAlign; 3853 S.Diag(FirstField->getLocation(), 3854 diag::note_transparent_union_first_field_size_align) 3855 << isSize << FirstBits; 3856 return; 3857 } 3858 } 3859 3860 RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL)); 3861 } 3862 3863 void Sema::AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, 3864 StringRef Str, MutableArrayRef<Expr *> Args) { 3865 auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI); 3866 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 3867 for (unsigned Idx = 0; Idx < Attr->args_size(); Idx++) { 3868 Expr *&E = Attr->args_begin()[Idx]; 3869 assert(E && "error are handled before"); 3870 if (E->isValueDependent() || E->isTypeDependent()) 3871 continue; 3872 3873 if (E->getType()->isArrayType()) 3874 E = ImpCastExprToType(E, Context.getPointerType(E->getType()), 3875 clang::CK_ArrayToPointerDecay) 3876 .get(); 3877 if (E->getType()->isFunctionType()) 3878 E = ImplicitCastExpr::Create(Context, 3879 Context.getPointerType(E->getType()), 3880 clang::CK_FunctionToPointerDecay, E, nullptr, 3881 VK_PRValue, FPOptionsOverride()); 3882 if (E->isLValue()) 3883 E = ImplicitCastExpr::Create(Context, E->getType().getNonReferenceType(), 3884 clang::CK_LValueToRValue, E, nullptr, 3885 VK_PRValue, FPOptionsOverride()); 3886 3887 Expr::EvalResult Eval; 3888 Notes.clear(); 3889 Eval.Diag = &Notes; 3890 3891 bool Result = 3892 E->EvaluateAsConstantExpr(Eval, Context); 3893 3894 /// Result means the expression can be folded to a constant. 3895 /// Note.empty() means the expression is a valid constant expression in the 3896 /// current language mode. 3897 if (!Result || !Notes.empty()) { 3898 Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type) 3899 << CI << (Idx + 1) << AANT_ArgumentConstantExpr; 3900 for (auto &Note : Notes) 3901 Diag(Note.first, Note.second); 3902 return; 3903 } 3904 assert(Eval.Val.hasValue()); 3905 E = ConstantExpr::Create(Context, E, Eval.Val); 3906 } 3907 D->addAttr(Attr); 3908 } 3909 3910 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3911 // Make sure that there is a string literal as the annotation's first 3912 // argument. 3913 StringRef Str; 3914 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 3915 return; 3916 3917 llvm::SmallVector<Expr *, 4> Args; 3918 Args.reserve(AL.getNumArgs() - 1); 3919 for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) { 3920 assert(!AL.isArgIdent(Idx)); 3921 Args.push_back(AL.getArgAsExpr(Idx)); 3922 } 3923 3924 S.AddAnnotationAttr(D, AL, Str, Args); 3925 } 3926 3927 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3928 S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0)); 3929 } 3930 3931 void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) { 3932 AlignValueAttr TmpAttr(Context, CI, E); 3933 SourceLocation AttrLoc = CI.getLoc(); 3934 3935 QualType T; 3936 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) 3937 T = TD->getUnderlyingType(); 3938 else if (const auto *VD = dyn_cast<ValueDecl>(D)) 3939 T = VD->getType(); 3940 else 3941 llvm_unreachable("Unknown decl type for align_value"); 3942 3943 if (!T->isDependentType() && !T->isAnyPointerType() && 3944 !T->isReferenceType() && !T->isMemberPointerType()) { 3945 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only) 3946 << &TmpAttr << T << D->getSourceRange(); 3947 return; 3948 } 3949 3950 if (!E->isValueDependent()) { 3951 llvm::APSInt Alignment; 3952 ExprResult ICE = VerifyIntegerConstantExpression( 3953 E, &Alignment, diag::err_align_value_attribute_argument_not_int); 3954 if (ICE.isInvalid()) 3955 return; 3956 3957 if (!Alignment.isPowerOf2()) { 3958 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 3959 << E->getSourceRange(); 3960 return; 3961 } 3962 3963 D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get())); 3964 return; 3965 } 3966 3967 // Save dependent expressions in the AST to be instantiated. 3968 D->addAttr(::new (Context) AlignValueAttr(Context, CI, E)); 3969 } 3970 3971 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3972 // check the attribute arguments. 3973 if (AL.getNumArgs() > 1) { 3974 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; 3975 return; 3976 } 3977 3978 if (AL.getNumArgs() == 0) { 3979 D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr)); 3980 return; 3981 } 3982 3983 Expr *E = AL.getArgAsExpr(0); 3984 if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) { 3985 S.Diag(AL.getEllipsisLoc(), 3986 diag::err_pack_expansion_without_parameter_packs); 3987 return; 3988 } 3989 3990 if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E)) 3991 return; 3992 3993 S.AddAlignedAttr(D, AL, E, AL.isPackExpansion()); 3994 } 3995 3996 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 3997 bool IsPackExpansion) { 3998 AlignedAttr TmpAttr(Context, CI, true, E); 3999 SourceLocation AttrLoc = CI.getLoc(); 4000 4001 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements. 4002 if (TmpAttr.isAlignas()) { 4003 // C++11 [dcl.align]p1: 4004 // An alignment-specifier may be applied to a variable or to a class 4005 // data member, but it shall not be applied to a bit-field, a function 4006 // parameter, the formal parameter of a catch clause, or a variable 4007 // declared with the register storage class specifier. An 4008 // alignment-specifier may also be applied to the declaration of a class 4009 // or enumeration type. 4010 // C11 6.7.5/2: 4011 // An alignment attribute shall not be specified in a declaration of 4012 // a typedef, or a bit-field, or a function, or a parameter, or an 4013 // object declared with the register storage-class specifier. 4014 int DiagKind = -1; 4015 if (isa<ParmVarDecl>(D)) { 4016 DiagKind = 0; 4017 } else if (const auto *VD = dyn_cast<VarDecl>(D)) { 4018 if (VD->getStorageClass() == SC_Register) 4019 DiagKind = 1; 4020 if (VD->isExceptionVariable()) 4021 DiagKind = 2; 4022 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) { 4023 if (FD->isBitField()) 4024 DiagKind = 3; 4025 } else if (!isa<TagDecl>(D)) { 4026 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr 4027 << (TmpAttr.isC11() ? ExpectedVariableOrField 4028 : ExpectedVariableFieldOrTag); 4029 return; 4030 } 4031 if (DiagKind != -1) { 4032 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type) 4033 << &TmpAttr << DiagKind; 4034 return; 4035 } 4036 } 4037 4038 if (E->isValueDependent()) { 4039 // We can't support a dependent alignment on a non-dependent type, 4040 // because we have no way to model that a type is "alignment-dependent" 4041 // but not dependent in any other way. 4042 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) { 4043 if (!TND->getUnderlyingType()->isDependentType()) { 4044 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name) 4045 << E->getSourceRange(); 4046 return; 4047 } 4048 } 4049 4050 // Save dependent expressions in the AST to be instantiated. 4051 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E); 4052 AA->setPackExpansion(IsPackExpansion); 4053 D->addAttr(AA); 4054 return; 4055 } 4056 4057 // FIXME: Cache the number on the AL object? 4058 llvm::APSInt Alignment; 4059 ExprResult ICE = VerifyIntegerConstantExpression( 4060 E, &Alignment, diag::err_aligned_attribute_argument_not_int); 4061 if (ICE.isInvalid()) 4062 return; 4063 4064 uint64_t AlignVal = Alignment.getZExtValue(); 4065 // 16 byte ByVal alignment not due to a vector member is not honoured by XL 4066 // on AIX. Emit a warning here that users are generating binary incompatible 4067 // code to be safe. 4068 if (AlignVal >= 16 && isa<FieldDecl>(D) && 4069 Context.getTargetInfo().getTriple().isOSAIX()) 4070 Diag(AttrLoc, diag::warn_not_xl_compatible) << E->getSourceRange(); 4071 4072 // C++11 [dcl.align]p2: 4073 // -- if the constant expression evaluates to zero, the alignment 4074 // specifier shall have no effect 4075 // C11 6.7.5p6: 4076 // An alignment specification of zero has no effect. 4077 if (!(TmpAttr.isAlignas() && !Alignment)) { 4078 if (!llvm::isPowerOf2_64(AlignVal)) { 4079 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 4080 << E->getSourceRange(); 4081 return; 4082 } 4083 } 4084 4085 unsigned MaximumAlignment = Sema::MaximumAlignment; 4086 if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF()) 4087 MaximumAlignment = std::min(MaximumAlignment, 8192u); 4088 if (AlignVal > MaximumAlignment) { 4089 Diag(AttrLoc, diag::err_attribute_aligned_too_great) 4090 << MaximumAlignment << E->getSourceRange(); 4091 return; 4092 } 4093 4094 const auto *VD = dyn_cast<VarDecl>(D); 4095 if (VD && Context.getTargetInfo().isTLSSupported()) { 4096 unsigned MaxTLSAlign = 4097 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign()) 4098 .getQuantity(); 4099 if (MaxTLSAlign && AlignVal > MaxTLSAlign && 4100 VD->getTLSKind() != VarDecl::TLS_None) { 4101 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 4102 << (unsigned)AlignVal << VD << MaxTLSAlign; 4103 return; 4104 } 4105 } 4106 4107 // On AIX, an aligned attribute can not decrease the alignment when applied 4108 // to a variable declaration with vector type. 4109 if (VD && Context.getTargetInfo().getTriple().isOSAIX()) { 4110 const Type *Ty = VD->getType().getTypePtr(); 4111 if (Ty->isVectorType() && AlignVal < 16) { 4112 Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned) 4113 << VD->getType() << 16; 4114 return; 4115 } 4116 } 4117 4118 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get()); 4119 AA->setPackExpansion(IsPackExpansion); 4120 D->addAttr(AA); 4121 } 4122 4123 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, 4124 TypeSourceInfo *TS, bool IsPackExpansion) { 4125 // FIXME: Cache the number on the AL object if non-dependent? 4126 // FIXME: Perform checking of type validity 4127 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS); 4128 AA->setPackExpansion(IsPackExpansion); 4129 D->addAttr(AA); 4130 } 4131 4132 void Sema::CheckAlignasUnderalignment(Decl *D) { 4133 assert(D->hasAttrs() && "no attributes on decl"); 4134 4135 QualType UnderlyingTy, DiagTy; 4136 if (const auto *VD = dyn_cast<ValueDecl>(D)) { 4137 UnderlyingTy = DiagTy = VD->getType(); 4138 } else { 4139 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D)); 4140 if (const auto *ED = dyn_cast<EnumDecl>(D)) 4141 UnderlyingTy = ED->getIntegerType(); 4142 } 4143 if (DiagTy->isDependentType() || DiagTy->isIncompleteType()) 4144 return; 4145 4146 // C++11 [dcl.align]p5, C11 6.7.5/4: 4147 // The combined effect of all alignment attributes in a declaration shall 4148 // not specify an alignment that is less strict than the alignment that 4149 // would otherwise be required for the entity being declared. 4150 AlignedAttr *AlignasAttr = nullptr; 4151 AlignedAttr *LastAlignedAttr = nullptr; 4152 unsigned Align = 0; 4153 for (auto *I : D->specific_attrs<AlignedAttr>()) { 4154 if (I->isAlignmentDependent()) 4155 return; 4156 if (I->isAlignas()) 4157 AlignasAttr = I; 4158 Align = std::max(Align, I->getAlignment(Context)); 4159 LastAlignedAttr = I; 4160 } 4161 4162 if (Align && DiagTy->isSizelessType()) { 4163 Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type) 4164 << LastAlignedAttr << DiagTy; 4165 } else if (AlignasAttr && Align) { 4166 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align); 4167 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy); 4168 if (NaturalAlign > RequestedAlign) 4169 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned) 4170 << DiagTy << (unsigned)NaturalAlign.getQuantity(); 4171 } 4172 } 4173 4174 bool Sema::checkMSInheritanceAttrOnDefinition( 4175 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 4176 MSInheritanceModel ExplicitModel) { 4177 assert(RD->hasDefinition() && "RD has no definition!"); 4178 4179 // We may not have seen base specifiers or any virtual methods yet. We will 4180 // have to wait until the record is defined to catch any mismatches. 4181 if (!RD->getDefinition()->isCompleteDefinition()) 4182 return false; 4183 4184 // The unspecified model never matches what a definition could need. 4185 if (ExplicitModel == MSInheritanceModel::Unspecified) 4186 return false; 4187 4188 if (BestCase) { 4189 if (RD->calculateInheritanceModel() == ExplicitModel) 4190 return false; 4191 } else { 4192 if (RD->calculateInheritanceModel() <= ExplicitModel) 4193 return false; 4194 } 4195 4196 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance) 4197 << 0 /*definition*/; 4198 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD; 4199 return true; 4200 } 4201 4202 /// parseModeAttrArg - Parses attribute mode string and returns parsed type 4203 /// attribute. 4204 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth, 4205 bool &IntegerMode, bool &ComplexMode, 4206 bool &ExplicitIEEE) { 4207 IntegerMode = true; 4208 ComplexMode = false; 4209 switch (Str.size()) { 4210 case 2: 4211 switch (Str[0]) { 4212 case 'Q': 4213 DestWidth = 8; 4214 break; 4215 case 'H': 4216 DestWidth = 16; 4217 break; 4218 case 'S': 4219 DestWidth = 32; 4220 break; 4221 case 'D': 4222 DestWidth = 64; 4223 break; 4224 case 'X': 4225 DestWidth = 96; 4226 break; 4227 case 'K': // KFmode - IEEE quad precision (__float128) 4228 ExplicitIEEE = true; 4229 DestWidth = Str[1] == 'I' ? 0 : 128; 4230 break; 4231 case 'T': 4232 ExplicitIEEE = false; 4233 DestWidth = 128; 4234 break; 4235 } 4236 if (Str[1] == 'F') { 4237 IntegerMode = false; 4238 } else if (Str[1] == 'C') { 4239 IntegerMode = false; 4240 ComplexMode = true; 4241 } else if (Str[1] != 'I') { 4242 DestWidth = 0; 4243 } 4244 break; 4245 case 4: 4246 // FIXME: glibc uses 'word' to define register_t; this is narrower than a 4247 // pointer on PIC16 and other embedded platforms. 4248 if (Str == "word") 4249 DestWidth = S.Context.getTargetInfo().getRegisterWidth(); 4250 else if (Str == "byte") 4251 DestWidth = S.Context.getTargetInfo().getCharWidth(); 4252 break; 4253 case 7: 4254 if (Str == "pointer") 4255 DestWidth = S.Context.getTargetInfo().getPointerWidth(0); 4256 break; 4257 case 11: 4258 if (Str == "unwind_word") 4259 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth(); 4260 break; 4261 } 4262 } 4263 4264 /// handleModeAttr - This attribute modifies the width of a decl with primitive 4265 /// type. 4266 /// 4267 /// Despite what would be logical, the mode attribute is a decl attribute, not a 4268 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be 4269 /// HImode, not an intermediate pointer. 4270 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4271 // This attribute isn't documented, but glibc uses it. It changes 4272 // the width of an int or unsigned int to the specified size. 4273 if (!AL.isArgIdent(0)) { 4274 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 4275 << AL << AANT_ArgumentIdentifier; 4276 return; 4277 } 4278 4279 IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident; 4280 4281 S.AddModeAttr(D, AL, Name); 4282 } 4283 4284 void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI, 4285 IdentifierInfo *Name, bool InInstantiation) { 4286 StringRef Str = Name->getName(); 4287 normalizeName(Str); 4288 SourceLocation AttrLoc = CI.getLoc(); 4289 4290 unsigned DestWidth = 0; 4291 bool IntegerMode = true; 4292 bool ComplexMode = false; 4293 bool ExplicitIEEE = false; 4294 llvm::APInt VectorSize(64, 0); 4295 if (Str.size() >= 4 && Str[0] == 'V') { 4296 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2). 4297 size_t StrSize = Str.size(); 4298 size_t VectorStringLength = 0; 4299 while ((VectorStringLength + 1) < StrSize && 4300 isdigit(Str[VectorStringLength + 1])) 4301 ++VectorStringLength; 4302 if (VectorStringLength && 4303 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) && 4304 VectorSize.isPowerOf2()) { 4305 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth, 4306 IntegerMode, ComplexMode, ExplicitIEEE); 4307 // Avoid duplicate warning from template instantiation. 4308 if (!InInstantiation) 4309 Diag(AttrLoc, diag::warn_vector_mode_deprecated); 4310 } else { 4311 VectorSize = 0; 4312 } 4313 } 4314 4315 if (!VectorSize) 4316 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode, 4317 ExplicitIEEE); 4318 4319 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t 4320 // and friends, at least with glibc. 4321 // FIXME: Make sure floating-point mappings are accurate 4322 // FIXME: Support XF and TF types 4323 if (!DestWidth) { 4324 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name; 4325 return; 4326 } 4327 4328 QualType OldTy; 4329 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) 4330 OldTy = TD->getUnderlyingType(); 4331 else if (const auto *ED = dyn_cast<EnumDecl>(D)) { 4332 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'. 4333 // Try to get type from enum declaration, default to int. 4334 OldTy = ED->getIntegerType(); 4335 if (OldTy.isNull()) 4336 OldTy = Context.IntTy; 4337 } else 4338 OldTy = cast<ValueDecl>(D)->getType(); 4339 4340 if (OldTy->isDependentType()) { 4341 D->addAttr(::new (Context) ModeAttr(Context, CI, Name)); 4342 return; 4343 } 4344 4345 // Base type can also be a vector type (see PR17453). 4346 // Distinguish between base type and base element type. 4347 QualType OldElemTy = OldTy; 4348 if (const auto *VT = OldTy->getAs<VectorType>()) 4349 OldElemTy = VT->getElementType(); 4350 4351 // GCC allows 'mode' attribute on enumeration types (even incomplete), except 4352 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete 4353 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected. 4354 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) && 4355 VectorSize.getBoolValue()) { 4356 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange(); 4357 return; 4358 } 4359 bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() && 4360 !OldElemTy->isExtIntType()) || 4361 OldElemTy->getAs<EnumType>(); 4362 4363 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() && 4364 !IntegralOrAnyEnumType) 4365 Diag(AttrLoc, diag::err_mode_not_primitive); 4366 else if (IntegerMode) { 4367 if (!IntegralOrAnyEnumType) 4368 Diag(AttrLoc, diag::err_mode_wrong_type); 4369 } else if (ComplexMode) { 4370 if (!OldElemTy->isComplexType()) 4371 Diag(AttrLoc, diag::err_mode_wrong_type); 4372 } else { 4373 if (!OldElemTy->isFloatingType()) 4374 Diag(AttrLoc, diag::err_mode_wrong_type); 4375 } 4376 4377 QualType NewElemTy; 4378 4379 if (IntegerMode) 4380 NewElemTy = Context.getIntTypeForBitwidth(DestWidth, 4381 OldElemTy->isSignedIntegerType()); 4382 else 4383 NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitIEEE); 4384 4385 if (NewElemTy.isNull()) { 4386 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name; 4387 return; 4388 } 4389 4390 if (ComplexMode) { 4391 NewElemTy = Context.getComplexType(NewElemTy); 4392 } 4393 4394 QualType NewTy = NewElemTy; 4395 if (VectorSize.getBoolValue()) { 4396 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(), 4397 VectorType::GenericVector); 4398 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) { 4399 // Complex machine mode does not support base vector types. 4400 if (ComplexMode) { 4401 Diag(AttrLoc, diag::err_complex_mode_vector_type); 4402 return; 4403 } 4404 unsigned NumElements = Context.getTypeSize(OldElemTy) * 4405 OldVT->getNumElements() / 4406 Context.getTypeSize(NewElemTy); 4407 NewTy = 4408 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind()); 4409 } 4410 4411 if (NewTy.isNull()) { 4412 Diag(AttrLoc, diag::err_mode_wrong_type); 4413 return; 4414 } 4415 4416 // Install the new type. 4417 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) 4418 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy); 4419 else if (auto *ED = dyn_cast<EnumDecl>(D)) 4420 ED->setIntegerType(NewTy); 4421 else 4422 cast<ValueDecl>(D)->setType(NewTy); 4423 4424 D->addAttr(::new (Context) ModeAttr(Context, CI, Name)); 4425 } 4426 4427 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4428 D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL)); 4429 } 4430 4431 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, 4432 const AttributeCommonInfo &CI, 4433 const IdentifierInfo *Ident) { 4434 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 4435 Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident; 4436 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 4437 return nullptr; 4438 } 4439 4440 if (D->hasAttr<AlwaysInlineAttr>()) 4441 return nullptr; 4442 4443 return ::new (Context) AlwaysInlineAttr(Context, CI); 4444 } 4445 4446 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D, 4447 const ParsedAttr &AL) { 4448 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4449 // Attribute applies to Var but not any subclass of it (like ParmVar, 4450 // ImplicitParm or VarTemplateSpecialization). 4451 if (VD->getKind() != Decl::Var) { 4452 Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 4453 << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass 4454 : ExpectedVariableOrFunction); 4455 return nullptr; 4456 } 4457 // Attribute does not apply to non-static local variables. 4458 if (VD->hasLocalStorage()) { 4459 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage); 4460 return nullptr; 4461 } 4462 } 4463 4464 return ::new (Context) InternalLinkageAttr(Context, AL); 4465 } 4466 InternalLinkageAttr * 4467 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) { 4468 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4469 // Attribute applies to Var but not any subclass of it (like ParmVar, 4470 // ImplicitParm or VarTemplateSpecialization). 4471 if (VD->getKind() != Decl::Var) { 4472 Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type) 4473 << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass 4474 : ExpectedVariableOrFunction); 4475 return nullptr; 4476 } 4477 // Attribute does not apply to non-static local variables. 4478 if (VD->hasLocalStorage()) { 4479 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage); 4480 return nullptr; 4481 } 4482 } 4483 4484 return ::new (Context) InternalLinkageAttr(Context, AL); 4485 } 4486 4487 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) { 4488 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 4489 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'"; 4490 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 4491 return nullptr; 4492 } 4493 4494 if (D->hasAttr<MinSizeAttr>()) 4495 return nullptr; 4496 4497 return ::new (Context) MinSizeAttr(Context, CI); 4498 } 4499 4500 SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, 4501 StringRef Name) { 4502 if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) { 4503 if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) { 4504 Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible) 4505 << PrevSNA << &SNA; 4506 Diag(SNA.getLoc(), diag::note_conflicting_attribute); 4507 } 4508 4509 D->dropAttr<SwiftNameAttr>(); 4510 } 4511 return ::new (Context) SwiftNameAttr(Context, SNA, Name); 4512 } 4513 4514 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, 4515 const AttributeCommonInfo &CI) { 4516 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) { 4517 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline; 4518 Diag(CI.getLoc(), diag::note_conflicting_attribute); 4519 D->dropAttr<AlwaysInlineAttr>(); 4520 } 4521 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) { 4522 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize; 4523 Diag(CI.getLoc(), diag::note_conflicting_attribute); 4524 D->dropAttr<MinSizeAttr>(); 4525 } 4526 4527 if (D->hasAttr<OptimizeNoneAttr>()) 4528 return nullptr; 4529 4530 return ::new (Context) OptimizeNoneAttr(Context, CI); 4531 } 4532 4533 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4534 if (AlwaysInlineAttr *Inline = 4535 S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName())) 4536 D->addAttr(Inline); 4537 } 4538 4539 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4540 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL)) 4541 D->addAttr(MinSize); 4542 } 4543 4544 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4545 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL)) 4546 D->addAttr(Optnone); 4547 } 4548 4549 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4550 const auto *VD = cast<VarDecl>(D); 4551 if (VD->hasLocalStorage()) { 4552 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev); 4553 return; 4554 } 4555 // constexpr variable may already get an implicit constant attr, which should 4556 // be replaced by the explicit constant attr. 4557 if (auto *A = D->getAttr<CUDAConstantAttr>()) { 4558 if (!A->isImplicit()) 4559 return; 4560 D->dropAttr<CUDAConstantAttr>(); 4561 } 4562 D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL)); 4563 } 4564 4565 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4566 const auto *VD = cast<VarDecl>(D); 4567 // extern __shared__ is only allowed on arrays with no length (e.g. 4568 // "int x[]"). 4569 if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() && 4570 !isa<IncompleteArrayType>(VD->getType())) { 4571 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD; 4572 return; 4573 } 4574 if (S.getLangOpts().CUDA && VD->hasLocalStorage() && 4575 S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared) 4576 << S.CurrentCUDATarget()) 4577 return; 4578 D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL)); 4579 } 4580 4581 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4582 const auto *FD = cast<FunctionDecl>(D); 4583 if (!FD->getReturnType()->isVoidType() && 4584 !FD->getReturnType()->getAs<AutoType>() && 4585 !FD->getReturnType()->isInstantiationDependentType()) { 4586 SourceRange RTRange = FD->getReturnTypeSourceRange(); 4587 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return) 4588 << FD->getType() 4589 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 4590 : FixItHint()); 4591 return; 4592 } 4593 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) { 4594 if (Method->isInstance()) { 4595 S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method) 4596 << Method; 4597 return; 4598 } 4599 S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method; 4600 } 4601 // Only warn for "inline" when compiling for host, to cut down on noise. 4602 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice) 4603 S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD; 4604 4605 D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL)); 4606 // In host compilation the kernel is emitted as a stub function, which is 4607 // a helper function for launching the kernel. The instructions in the helper 4608 // function has nothing to do with the source code of the kernel. Do not emit 4609 // debug info for the stub function to avoid confusing the debugger. 4610 if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice) 4611 D->addAttr(NoDebugAttr::CreateImplicit(S.Context)); 4612 } 4613 4614 static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4615 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4616 if (VD->hasLocalStorage()) { 4617 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev); 4618 return; 4619 } 4620 } 4621 4622 if (auto *A = D->getAttr<CUDADeviceAttr>()) { 4623 if (!A->isImplicit()) 4624 return; 4625 D->dropAttr<CUDADeviceAttr>(); 4626 } 4627 D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL)); 4628 } 4629 4630 static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4631 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4632 if (VD->hasLocalStorage()) { 4633 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev); 4634 return; 4635 } 4636 } 4637 if (!D->hasAttr<HIPManagedAttr>()) 4638 D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL)); 4639 if (!D->hasAttr<CUDADeviceAttr>()) 4640 D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context)); 4641 } 4642 4643 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4644 const auto *Fn = cast<FunctionDecl>(D); 4645 if (!Fn->isInlineSpecified()) { 4646 S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline); 4647 return; 4648 } 4649 4650 if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern) 4651 S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern); 4652 4653 D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL)); 4654 } 4655 4656 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4657 if (hasDeclarator(D)) return; 4658 4659 // Diagnostic is emitted elsewhere: here we store the (valid) AL 4660 // in the Decl node for syntactic reasoning, e.g., pretty-printing. 4661 CallingConv CC; 4662 if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr)) 4663 return; 4664 4665 if (!isa<ObjCMethodDecl>(D)) { 4666 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 4667 << AL << ExpectedFunctionOrMethod; 4668 return; 4669 } 4670 4671 switch (AL.getKind()) { 4672 case ParsedAttr::AT_FastCall: 4673 D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL)); 4674 return; 4675 case ParsedAttr::AT_StdCall: 4676 D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL)); 4677 return; 4678 case ParsedAttr::AT_ThisCall: 4679 D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL)); 4680 return; 4681 case ParsedAttr::AT_CDecl: 4682 D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL)); 4683 return; 4684 case ParsedAttr::AT_Pascal: 4685 D->addAttr(::new (S.Context) PascalAttr(S.Context, AL)); 4686 return; 4687 case ParsedAttr::AT_SwiftCall: 4688 D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL)); 4689 return; 4690 case ParsedAttr::AT_SwiftAsyncCall: 4691 D->addAttr(::new (S.Context) SwiftAsyncCallAttr(S.Context, AL)); 4692 return; 4693 case ParsedAttr::AT_VectorCall: 4694 D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL)); 4695 return; 4696 case ParsedAttr::AT_MSABI: 4697 D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL)); 4698 return; 4699 case ParsedAttr::AT_SysVABI: 4700 D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL)); 4701 return; 4702 case ParsedAttr::AT_RegCall: 4703 D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL)); 4704 return; 4705 case ParsedAttr::AT_Pcs: { 4706 PcsAttr::PCSType PCS; 4707 switch (CC) { 4708 case CC_AAPCS: 4709 PCS = PcsAttr::AAPCS; 4710 break; 4711 case CC_AAPCS_VFP: 4712 PCS = PcsAttr::AAPCS_VFP; 4713 break; 4714 default: 4715 llvm_unreachable("unexpected calling convention in pcs attribute"); 4716 } 4717 4718 D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS)); 4719 return; 4720 } 4721 case ParsedAttr::AT_AArch64VectorPcs: 4722 D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL)); 4723 return; 4724 case ParsedAttr::AT_IntelOclBicc: 4725 D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL)); 4726 return; 4727 case ParsedAttr::AT_PreserveMost: 4728 D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL)); 4729 return; 4730 case ParsedAttr::AT_PreserveAll: 4731 D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL)); 4732 return; 4733 default: 4734 llvm_unreachable("unexpected attribute kind"); 4735 } 4736 } 4737 4738 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4739 if (!AL.checkAtLeastNumArgs(S, 1)) 4740 return; 4741 4742 std::vector<StringRef> DiagnosticIdentifiers; 4743 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 4744 StringRef RuleName; 4745 4746 if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr)) 4747 return; 4748 4749 // FIXME: Warn if the rule name is unknown. This is tricky because only 4750 // clang-tidy knows about available rules. 4751 DiagnosticIdentifiers.push_back(RuleName); 4752 } 4753 D->addAttr(::new (S.Context) 4754 SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(), 4755 DiagnosticIdentifiers.size())); 4756 } 4757 4758 static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4759 TypeSourceInfo *DerefTypeLoc = nullptr; 4760 QualType ParmType; 4761 if (AL.hasParsedType()) { 4762 ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc); 4763 4764 unsigned SelectIdx = ~0U; 4765 if (ParmType->isReferenceType()) 4766 SelectIdx = 0; 4767 else if (ParmType->isArrayType()) 4768 SelectIdx = 1; 4769 4770 if (SelectIdx != ~0U) { 4771 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) 4772 << SelectIdx << AL; 4773 return; 4774 } 4775 } 4776 4777 // To check if earlier decl attributes do not conflict the newly parsed ones 4778 // we always add (and check) the attribute to the cannonical decl. We need 4779 // to repeat the check for attribute mutual exclusion because we're attaching 4780 // all of the attributes to the canonical declaration rather than the current 4781 // declaration. 4782 D = D->getCanonicalDecl(); 4783 if (AL.getKind() == ParsedAttr::AT_Owner) { 4784 if (checkAttrMutualExclusion<PointerAttr>(S, D, AL)) 4785 return; 4786 if (const auto *OAttr = D->getAttr<OwnerAttr>()) { 4787 const Type *ExistingDerefType = OAttr->getDerefTypeLoc() 4788 ? OAttr->getDerefType().getTypePtr() 4789 : nullptr; 4790 if (ExistingDerefType != ParmType.getTypePtrOrNull()) { 4791 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) 4792 << AL << OAttr; 4793 S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute); 4794 } 4795 return; 4796 } 4797 for (Decl *Redecl : D->redecls()) { 4798 Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc)); 4799 } 4800 } else { 4801 if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL)) 4802 return; 4803 if (const auto *PAttr = D->getAttr<PointerAttr>()) { 4804 const Type *ExistingDerefType = PAttr->getDerefTypeLoc() 4805 ? PAttr->getDerefType().getTypePtr() 4806 : nullptr; 4807 if (ExistingDerefType != ParmType.getTypePtrOrNull()) { 4808 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) 4809 << AL << PAttr; 4810 S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute); 4811 } 4812 return; 4813 } 4814 for (Decl *Redecl : D->redecls()) { 4815 Redecl->addAttr(::new (S.Context) 4816 PointerAttr(S.Context, AL, DerefTypeLoc)); 4817 } 4818 } 4819 } 4820 4821 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC, 4822 const FunctionDecl *FD) { 4823 if (Attrs.isInvalid()) 4824 return true; 4825 4826 if (Attrs.hasProcessingCache()) { 4827 CC = (CallingConv) Attrs.getProcessingCache(); 4828 return false; 4829 } 4830 4831 unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0; 4832 if (!Attrs.checkExactlyNumArgs(*this, ReqArgs)) { 4833 Attrs.setInvalid(); 4834 return true; 4835 } 4836 4837 // TODO: diagnose uses of these conventions on the wrong target. 4838 switch (Attrs.getKind()) { 4839 case ParsedAttr::AT_CDecl: 4840 CC = CC_C; 4841 break; 4842 case ParsedAttr::AT_FastCall: 4843 CC = CC_X86FastCall; 4844 break; 4845 case ParsedAttr::AT_StdCall: 4846 CC = CC_X86StdCall; 4847 break; 4848 case ParsedAttr::AT_ThisCall: 4849 CC = CC_X86ThisCall; 4850 break; 4851 case ParsedAttr::AT_Pascal: 4852 CC = CC_X86Pascal; 4853 break; 4854 case ParsedAttr::AT_SwiftCall: 4855 CC = CC_Swift; 4856 break; 4857 case ParsedAttr::AT_SwiftAsyncCall: 4858 CC = CC_SwiftAsync; 4859 break; 4860 case ParsedAttr::AT_VectorCall: 4861 CC = CC_X86VectorCall; 4862 break; 4863 case ParsedAttr::AT_AArch64VectorPcs: 4864 CC = CC_AArch64VectorCall; 4865 break; 4866 case ParsedAttr::AT_RegCall: 4867 CC = CC_X86RegCall; 4868 break; 4869 case ParsedAttr::AT_MSABI: 4870 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : 4871 CC_Win64; 4872 break; 4873 case ParsedAttr::AT_SysVABI: 4874 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV : 4875 CC_C; 4876 break; 4877 case ParsedAttr::AT_Pcs: { 4878 StringRef StrRef; 4879 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) { 4880 Attrs.setInvalid(); 4881 return true; 4882 } 4883 if (StrRef == "aapcs") { 4884 CC = CC_AAPCS; 4885 break; 4886 } else if (StrRef == "aapcs-vfp") { 4887 CC = CC_AAPCS_VFP; 4888 break; 4889 } 4890 4891 Attrs.setInvalid(); 4892 Diag(Attrs.getLoc(), diag::err_invalid_pcs); 4893 return true; 4894 } 4895 case ParsedAttr::AT_IntelOclBicc: 4896 CC = CC_IntelOclBicc; 4897 break; 4898 case ParsedAttr::AT_PreserveMost: 4899 CC = CC_PreserveMost; 4900 break; 4901 case ParsedAttr::AT_PreserveAll: 4902 CC = CC_PreserveAll; 4903 break; 4904 default: llvm_unreachable("unexpected attribute kind"); 4905 } 4906 4907 TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK; 4908 const TargetInfo &TI = Context.getTargetInfo(); 4909 // CUDA functions may have host and/or device attributes which indicate 4910 // their targeted execution environment, therefore the calling convention 4911 // of functions in CUDA should be checked against the target deduced based 4912 // on their host/device attributes. 4913 if (LangOpts.CUDA) { 4914 auto *Aux = Context.getAuxTargetInfo(); 4915 auto CudaTarget = IdentifyCUDATarget(FD); 4916 bool CheckHost = false, CheckDevice = false; 4917 switch (CudaTarget) { 4918 case CFT_HostDevice: 4919 CheckHost = true; 4920 CheckDevice = true; 4921 break; 4922 case CFT_Host: 4923 CheckHost = true; 4924 break; 4925 case CFT_Device: 4926 case CFT_Global: 4927 CheckDevice = true; 4928 break; 4929 case CFT_InvalidTarget: 4930 llvm_unreachable("unexpected cuda target"); 4931 } 4932 auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI; 4933 auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux; 4934 if (CheckHost && HostTI) 4935 A = HostTI->checkCallingConvention(CC); 4936 if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI) 4937 A = DeviceTI->checkCallingConvention(CC); 4938 } else { 4939 A = TI.checkCallingConvention(CC); 4940 } 4941 4942 switch (A) { 4943 case TargetInfo::CCCR_OK: 4944 break; 4945 4946 case TargetInfo::CCCR_Ignore: 4947 // Treat an ignored convention as if it was an explicit C calling convention 4948 // attribute. For example, __stdcall on Win x64 functions as __cdecl, so 4949 // that command line flags that change the default convention to 4950 // __vectorcall don't affect declarations marked __stdcall. 4951 CC = CC_C; 4952 break; 4953 4954 case TargetInfo::CCCR_Error: 4955 Diag(Attrs.getLoc(), diag::error_cconv_unsupported) 4956 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget; 4957 break; 4958 4959 case TargetInfo::CCCR_Warning: { 4960 Diag(Attrs.getLoc(), diag::warn_cconv_unsupported) 4961 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget; 4962 4963 // This convention is not valid for the target. Use the default function or 4964 // method calling convention. 4965 bool IsCXXMethod = false, IsVariadic = false; 4966 if (FD) { 4967 IsCXXMethod = FD->isCXXInstanceMember(); 4968 IsVariadic = FD->isVariadic(); 4969 } 4970 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod); 4971 break; 4972 } 4973 } 4974 4975 Attrs.setProcessingCache((unsigned) CC); 4976 return false; 4977 } 4978 4979 /// Pointer-like types in the default address space. 4980 static bool isValidSwiftContextType(QualType Ty) { 4981 if (!Ty->hasPointerRepresentation()) 4982 return Ty->isDependentType(); 4983 return Ty->getPointeeType().getAddressSpace() == LangAS::Default; 4984 } 4985 4986 /// Pointers and references in the default address space. 4987 static bool isValidSwiftIndirectResultType(QualType Ty) { 4988 if (const auto *PtrType = Ty->getAs<PointerType>()) { 4989 Ty = PtrType->getPointeeType(); 4990 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) { 4991 Ty = RefType->getPointeeType(); 4992 } else { 4993 return Ty->isDependentType(); 4994 } 4995 return Ty.getAddressSpace() == LangAS::Default; 4996 } 4997 4998 /// Pointers and references to pointers in the default address space. 4999 static bool isValidSwiftErrorResultType(QualType Ty) { 5000 if (const auto *PtrType = Ty->getAs<PointerType>()) { 5001 Ty = PtrType->getPointeeType(); 5002 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) { 5003 Ty = RefType->getPointeeType(); 5004 } else { 5005 return Ty->isDependentType(); 5006 } 5007 if (!Ty.getQualifiers().empty()) 5008 return false; 5009 return isValidSwiftContextType(Ty); 5010 } 5011 5012 void Sema::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, 5013 ParameterABI abi) { 5014 5015 QualType type = cast<ParmVarDecl>(D)->getType(); 5016 5017 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) { 5018 if (existingAttr->getABI() != abi) { 5019 Diag(CI.getLoc(), diag::err_attributes_are_not_compatible) 5020 << getParameterABISpelling(abi) << existingAttr; 5021 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute); 5022 return; 5023 } 5024 } 5025 5026 switch (abi) { 5027 case ParameterABI::Ordinary: 5028 llvm_unreachable("explicit attribute for ordinary parameter ABI?"); 5029 5030 case ParameterABI::SwiftContext: 5031 if (!isValidSwiftContextType(type)) { 5032 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type) 5033 << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type; 5034 } 5035 D->addAttr(::new (Context) SwiftContextAttr(Context, CI)); 5036 return; 5037 5038 case ParameterABI::SwiftAsyncContext: 5039 if (!isValidSwiftContextType(type)) { 5040 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type) 5041 << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type; 5042 } 5043 D->addAttr(::new (Context) SwiftAsyncContextAttr(Context, CI)); 5044 return; 5045 5046 case ParameterABI::SwiftErrorResult: 5047 if (!isValidSwiftErrorResultType(type)) { 5048 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type) 5049 << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type; 5050 } 5051 D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI)); 5052 return; 5053 5054 case ParameterABI::SwiftIndirectResult: 5055 if (!isValidSwiftIndirectResultType(type)) { 5056 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type) 5057 << getParameterABISpelling(abi) << /*pointer*/ 0 << type; 5058 } 5059 D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI)); 5060 return; 5061 } 5062 llvm_unreachable("bad parameter ABI attribute"); 5063 } 5064 5065 /// Checks a regparm attribute, returning true if it is ill-formed and 5066 /// otherwise setting numParams to the appropriate value. 5067 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) { 5068 if (AL.isInvalid()) 5069 return true; 5070 5071 if (!AL.checkExactlyNumArgs(*this, 1)) { 5072 AL.setInvalid(); 5073 return true; 5074 } 5075 5076 uint32_t NP; 5077 Expr *NumParamsExpr = AL.getArgAsExpr(0); 5078 if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) { 5079 AL.setInvalid(); 5080 return true; 5081 } 5082 5083 if (Context.getTargetInfo().getRegParmMax() == 0) { 5084 Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform) 5085 << NumParamsExpr->getSourceRange(); 5086 AL.setInvalid(); 5087 return true; 5088 } 5089 5090 numParams = NP; 5091 if (numParams > Context.getTargetInfo().getRegParmMax()) { 5092 Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number) 5093 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange(); 5094 AL.setInvalid(); 5095 return true; 5096 } 5097 5098 return false; 5099 } 5100 5101 // Checks whether an argument of launch_bounds attribute is 5102 // acceptable, performs implicit conversion to Rvalue, and returns 5103 // non-nullptr Expr result on success. Otherwise, it returns nullptr 5104 // and may output an error. 5105 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E, 5106 const CUDALaunchBoundsAttr &AL, 5107 const unsigned Idx) { 5108 if (S.DiagnoseUnexpandedParameterPack(E)) 5109 return nullptr; 5110 5111 // Accept template arguments for now as they depend on something else. 5112 // We'll get to check them when they eventually get instantiated. 5113 if (E->isValueDependent()) 5114 return E; 5115 5116 Optional<llvm::APSInt> I = llvm::APSInt(64); 5117 if (!(I = E->getIntegerConstantExpr(S.Context))) { 5118 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type) 5119 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange(); 5120 return nullptr; 5121 } 5122 // Make sure we can fit it in 32 bits. 5123 if (!I->isIntN(32)) { 5124 S.Diag(E->getExprLoc(), diag::err_ice_too_large) 5125 << toString(*I, 10, false) << 32 << /* Unsigned */ 1; 5126 return nullptr; 5127 } 5128 if (*I < 0) 5129 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative) 5130 << &AL << Idx << E->getSourceRange(); 5131 5132 // We may need to perform implicit conversion of the argument. 5133 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5134 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false); 5135 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E); 5136 assert(!ValArg.isInvalid() && 5137 "Unexpected PerformCopyInitialization() failure."); 5138 5139 return ValArg.getAs<Expr>(); 5140 } 5141 5142 void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, 5143 Expr *MaxThreads, Expr *MinBlocks) { 5144 CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks); 5145 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0); 5146 if (MaxThreads == nullptr) 5147 return; 5148 5149 if (MinBlocks) { 5150 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1); 5151 if (MinBlocks == nullptr) 5152 return; 5153 } 5154 5155 D->addAttr(::new (Context) 5156 CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks)); 5157 } 5158 5159 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5160 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2)) 5161 return; 5162 5163 S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0), 5164 AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr); 5165 } 5166 5167 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D, 5168 const ParsedAttr &AL) { 5169 if (!AL.isArgIdent(0)) { 5170 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 5171 << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier; 5172 return; 5173 } 5174 5175 ParamIdx ArgumentIdx; 5176 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1), 5177 ArgumentIdx)) 5178 return; 5179 5180 ParamIdx TypeTagIdx; 5181 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2), 5182 TypeTagIdx)) 5183 return; 5184 5185 bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag"; 5186 if (IsPointer) { 5187 // Ensure that buffer has a pointer type. 5188 unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex(); 5189 if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) || 5190 !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType()) 5191 S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0; 5192 } 5193 5194 D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr( 5195 S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx, 5196 IsPointer)); 5197 } 5198 5199 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D, 5200 const ParsedAttr &AL) { 5201 if (!AL.isArgIdent(0)) { 5202 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 5203 << AL << 1 << AANT_ArgumentIdentifier; 5204 return; 5205 } 5206 5207 if (!AL.checkExactlyNumArgs(S, 1)) 5208 return; 5209 5210 if (!isa<VarDecl>(D)) { 5211 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type) 5212 << AL << ExpectedVariable; 5213 return; 5214 } 5215 5216 IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident; 5217 TypeSourceInfo *MatchingCTypeLoc = nullptr; 5218 S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc); 5219 assert(MatchingCTypeLoc && "no type source info for attribute argument"); 5220 5221 D->addAttr(::new (S.Context) TypeTagForDatatypeAttr( 5222 S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(), 5223 AL.getMustBeNull())); 5224 } 5225 5226 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5227 ParamIdx ArgCount; 5228 5229 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0), 5230 ArgCount, 5231 true /* CanIndexImplicitThis */)) 5232 return; 5233 5234 // ArgCount isn't a parameter index [0;n), it's a count [1;n] 5235 D->addAttr(::new (S.Context) 5236 XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex())); 5237 } 5238 5239 static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D, 5240 const ParsedAttr &AL) { 5241 uint32_t Count = 0, Offset = 0; 5242 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Count, 0, true)) 5243 return; 5244 if (AL.getNumArgs() == 2) { 5245 Expr *Arg = AL.getArgAsExpr(1); 5246 if (!checkUInt32Argument(S, AL, Arg, Offset, 1, true)) 5247 return; 5248 if (Count < Offset) { 5249 S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range) 5250 << &AL << 0 << Count << Arg->getBeginLoc(); 5251 return; 5252 } 5253 } 5254 D->addAttr(::new (S.Context) 5255 PatchableFunctionEntryAttr(S.Context, AL, Count, Offset)); 5256 } 5257 5258 namespace { 5259 struct IntrinToName { 5260 uint32_t Id; 5261 int32_t FullName; 5262 int32_t ShortName; 5263 }; 5264 } // unnamed namespace 5265 5266 static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName, 5267 ArrayRef<IntrinToName> Map, 5268 const char *IntrinNames) { 5269 if (AliasName.startswith("__arm_")) 5270 AliasName = AliasName.substr(6); 5271 const IntrinToName *It = std::lower_bound( 5272 Map.begin(), Map.end(), BuiltinID, 5273 [](const IntrinToName &L, unsigned Id) { return L.Id < Id; }); 5274 if (It == Map.end() || It->Id != BuiltinID) 5275 return false; 5276 StringRef FullName(&IntrinNames[It->FullName]); 5277 if (AliasName == FullName) 5278 return true; 5279 if (It->ShortName == -1) 5280 return false; 5281 StringRef ShortName(&IntrinNames[It->ShortName]); 5282 return AliasName == ShortName; 5283 } 5284 5285 static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) { 5286 #include "clang/Basic/arm_mve_builtin_aliases.inc" 5287 // The included file defines: 5288 // - ArrayRef<IntrinToName> Map 5289 // - const char IntrinNames[] 5290 return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames); 5291 } 5292 5293 static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) { 5294 #include "clang/Basic/arm_cde_builtin_aliases.inc" 5295 return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames); 5296 } 5297 5298 static bool ArmSveAliasValid(ASTContext &Context, unsigned BuiltinID, 5299 StringRef AliasName) { 5300 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 5301 BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(BuiltinID); 5302 return BuiltinID >= AArch64::FirstSVEBuiltin && 5303 BuiltinID <= AArch64::LastSVEBuiltin; 5304 } 5305 5306 static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5307 if (!AL.isArgIdent(0)) { 5308 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 5309 << AL << 1 << AANT_ArgumentIdentifier; 5310 return; 5311 } 5312 5313 IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident; 5314 unsigned BuiltinID = Ident->getBuiltinID(); 5315 StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName(); 5316 5317 bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 5318 if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) || 5319 (!IsAArch64 && !ArmMveAliasValid(BuiltinID, AliasName) && 5320 !ArmCdeAliasValid(BuiltinID, AliasName))) { 5321 S.Diag(AL.getLoc(), diag::err_attribute_arm_builtin_alias); 5322 return; 5323 } 5324 5325 D->addAttr(::new (S.Context) ArmBuiltinAliasAttr(S.Context, AL, Ident)); 5326 } 5327 5328 static bool RISCVAliasValid(unsigned BuiltinID, StringRef AliasName) { 5329 return BuiltinID >= Builtin::FirstTSBuiltin && 5330 BuiltinID < RISCV::LastTSBuiltin; 5331 } 5332 5333 static void handleBuiltinAliasAttr(Sema &S, Decl *D, 5334 const ParsedAttr &AL) { 5335 if (!AL.isArgIdent(0)) { 5336 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 5337 << AL << 1 << AANT_ArgumentIdentifier; 5338 return; 5339 } 5340 5341 IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident; 5342 unsigned BuiltinID = Ident->getBuiltinID(); 5343 StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName(); 5344 5345 bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 5346 bool IsARM = S.Context.getTargetInfo().getTriple().isARM(); 5347 bool IsRISCV = S.Context.getTargetInfo().getTriple().isRISCV(); 5348 if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) || 5349 (IsARM && !ArmMveAliasValid(BuiltinID, AliasName) && 5350 !ArmCdeAliasValid(BuiltinID, AliasName)) || 5351 (IsRISCV && !RISCVAliasValid(BuiltinID, AliasName)) || 5352 (!IsAArch64 && !IsARM && !IsRISCV)) { 5353 S.Diag(AL.getLoc(), diag::err_attribute_builtin_alias) << AL; 5354 return; 5355 } 5356 5357 D->addAttr(::new (S.Context) BuiltinAliasAttr(S.Context, AL, Ident)); 5358 } 5359 5360 //===----------------------------------------------------------------------===// 5361 // Checker-specific attribute handlers. 5362 //===----------------------------------------------------------------------===// 5363 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) { 5364 return QT->isDependentType() || QT->isObjCRetainableType(); 5365 } 5366 5367 static bool isValidSubjectOfNSAttribute(QualType QT) { 5368 return QT->isDependentType() || QT->isObjCObjectPointerType() || 5369 QT->isObjCNSObjectType(); 5370 } 5371 5372 static bool isValidSubjectOfCFAttribute(QualType QT) { 5373 return QT->isDependentType() || QT->isPointerType() || 5374 isValidSubjectOfNSAttribute(QT); 5375 } 5376 5377 static bool isValidSubjectOfOSAttribute(QualType QT) { 5378 if (QT->isDependentType()) 5379 return true; 5380 QualType PT = QT->getPointeeType(); 5381 return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr; 5382 } 5383 5384 void Sema::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, 5385 RetainOwnershipKind K, 5386 bool IsTemplateInstantiation) { 5387 ValueDecl *VD = cast<ValueDecl>(D); 5388 switch (K) { 5389 case RetainOwnershipKind::OS: 5390 handleSimpleAttributeOrDiagnose<OSConsumedAttr>( 5391 *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()), 5392 diag::warn_ns_attribute_wrong_parameter_type, 5393 /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1); 5394 return; 5395 case RetainOwnershipKind::NS: 5396 handleSimpleAttributeOrDiagnose<NSConsumedAttr>( 5397 *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()), 5398 5399 // These attributes are normally just advisory, but in ARC, ns_consumed 5400 // is significant. Allow non-dependent code to contain inappropriate 5401 // attributes even in ARC, but require template instantiations to be 5402 // set up correctly. 5403 ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount) 5404 ? diag::err_ns_attribute_wrong_parameter_type 5405 : diag::warn_ns_attribute_wrong_parameter_type), 5406 /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0); 5407 return; 5408 case RetainOwnershipKind::CF: 5409 handleSimpleAttributeOrDiagnose<CFConsumedAttr>( 5410 *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()), 5411 diag::warn_ns_attribute_wrong_parameter_type, 5412 /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1); 5413 return; 5414 } 5415 } 5416 5417 static Sema::RetainOwnershipKind 5418 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) { 5419 switch (AL.getKind()) { 5420 case ParsedAttr::AT_CFConsumed: 5421 case ParsedAttr::AT_CFReturnsRetained: 5422 case ParsedAttr::AT_CFReturnsNotRetained: 5423 return Sema::RetainOwnershipKind::CF; 5424 case ParsedAttr::AT_OSConsumesThis: 5425 case ParsedAttr::AT_OSConsumed: 5426 case ParsedAttr::AT_OSReturnsRetained: 5427 case ParsedAttr::AT_OSReturnsNotRetained: 5428 case ParsedAttr::AT_OSReturnsRetainedOnZero: 5429 case ParsedAttr::AT_OSReturnsRetainedOnNonZero: 5430 return Sema::RetainOwnershipKind::OS; 5431 case ParsedAttr::AT_NSConsumesSelf: 5432 case ParsedAttr::AT_NSConsumed: 5433 case ParsedAttr::AT_NSReturnsRetained: 5434 case ParsedAttr::AT_NSReturnsNotRetained: 5435 case ParsedAttr::AT_NSReturnsAutoreleased: 5436 return Sema::RetainOwnershipKind::NS; 5437 default: 5438 llvm_unreachable("Wrong argument supplied"); 5439 } 5440 } 5441 5442 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) { 5443 if (isValidSubjectOfNSReturnsRetainedAttribute(QT)) 5444 return false; 5445 5446 Diag(Loc, diag::warn_ns_attribute_wrong_return_type) 5447 << "'ns_returns_retained'" << 0 << 0; 5448 return true; 5449 } 5450 5451 /// \return whether the parameter is a pointer to OSObject pointer. 5452 static bool isValidOSObjectOutParameter(const Decl *D) { 5453 const auto *PVD = dyn_cast<ParmVarDecl>(D); 5454 if (!PVD) 5455 return false; 5456 QualType QT = PVD->getType(); 5457 QualType PT = QT->getPointeeType(); 5458 return !PT.isNull() && isValidSubjectOfOSAttribute(PT); 5459 } 5460 5461 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D, 5462 const ParsedAttr &AL) { 5463 QualType ReturnType; 5464 Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL); 5465 5466 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 5467 ReturnType = MD->getReturnType(); 5468 } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) && 5469 (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) { 5470 return; // ignore: was handled as a type attribute 5471 } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) { 5472 ReturnType = PD->getType(); 5473 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 5474 ReturnType = FD->getReturnType(); 5475 } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) { 5476 // Attributes on parameters are used for out-parameters, 5477 // passed as pointers-to-pointers. 5478 unsigned DiagID = K == Sema::RetainOwnershipKind::CF 5479 ? /*pointer-to-CF-pointer*/2 5480 : /*pointer-to-OSObject-pointer*/3; 5481 ReturnType = Param->getType()->getPointeeType(); 5482 if (ReturnType.isNull()) { 5483 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type) 5484 << AL << DiagID << AL.getRange(); 5485 return; 5486 } 5487 } else if (AL.isUsedAsTypeAttr()) { 5488 return; 5489 } else { 5490 AttributeDeclKind ExpectedDeclKind; 5491 switch (AL.getKind()) { 5492 default: llvm_unreachable("invalid ownership attribute"); 5493 case ParsedAttr::AT_NSReturnsRetained: 5494 case ParsedAttr::AT_NSReturnsAutoreleased: 5495 case ParsedAttr::AT_NSReturnsNotRetained: 5496 ExpectedDeclKind = ExpectedFunctionOrMethod; 5497 break; 5498 5499 case ParsedAttr::AT_OSReturnsRetained: 5500 case ParsedAttr::AT_OSReturnsNotRetained: 5501 case ParsedAttr::AT_CFReturnsRetained: 5502 case ParsedAttr::AT_CFReturnsNotRetained: 5503 ExpectedDeclKind = ExpectedFunctionMethodOrParameter; 5504 break; 5505 } 5506 S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type) 5507 << AL.getRange() << AL << ExpectedDeclKind; 5508 return; 5509 } 5510 5511 bool TypeOK; 5512 bool Cf; 5513 unsigned ParmDiagID = 2; // Pointer-to-CF-pointer 5514 switch (AL.getKind()) { 5515 default: llvm_unreachable("invalid ownership attribute"); 5516 case ParsedAttr::AT_NSReturnsRetained: 5517 TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType); 5518 Cf = false; 5519 break; 5520 5521 case ParsedAttr::AT_NSReturnsAutoreleased: 5522 case ParsedAttr::AT_NSReturnsNotRetained: 5523 TypeOK = isValidSubjectOfNSAttribute(ReturnType); 5524 Cf = false; 5525 break; 5526 5527 case ParsedAttr::AT_CFReturnsRetained: 5528 case ParsedAttr::AT_CFReturnsNotRetained: 5529 TypeOK = isValidSubjectOfCFAttribute(ReturnType); 5530 Cf = true; 5531 break; 5532 5533 case ParsedAttr::AT_OSReturnsRetained: 5534 case ParsedAttr::AT_OSReturnsNotRetained: 5535 TypeOK = isValidSubjectOfOSAttribute(ReturnType); 5536 Cf = true; 5537 ParmDiagID = 3; // Pointer-to-OSObject-pointer 5538 break; 5539 } 5540 5541 if (!TypeOK) { 5542 if (AL.isUsedAsTypeAttr()) 5543 return; 5544 5545 if (isa<ParmVarDecl>(D)) { 5546 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type) 5547 << AL << ParmDiagID << AL.getRange(); 5548 } else { 5549 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type. 5550 enum : unsigned { 5551 Function, 5552 Method, 5553 Property 5554 } SubjectKind = Function; 5555 if (isa<ObjCMethodDecl>(D)) 5556 SubjectKind = Method; 5557 else if (isa<ObjCPropertyDecl>(D)) 5558 SubjectKind = Property; 5559 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type) 5560 << AL << SubjectKind << Cf << AL.getRange(); 5561 } 5562 return; 5563 } 5564 5565 switch (AL.getKind()) { 5566 default: 5567 llvm_unreachable("invalid ownership attribute"); 5568 case ParsedAttr::AT_NSReturnsAutoreleased: 5569 handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL); 5570 return; 5571 case ParsedAttr::AT_CFReturnsNotRetained: 5572 handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL); 5573 return; 5574 case ParsedAttr::AT_NSReturnsNotRetained: 5575 handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL); 5576 return; 5577 case ParsedAttr::AT_CFReturnsRetained: 5578 handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL); 5579 return; 5580 case ParsedAttr::AT_NSReturnsRetained: 5581 handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL); 5582 return; 5583 case ParsedAttr::AT_OSReturnsRetained: 5584 handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL); 5585 return; 5586 case ParsedAttr::AT_OSReturnsNotRetained: 5587 handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL); 5588 return; 5589 }; 5590 } 5591 5592 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D, 5593 const ParsedAttr &Attrs) { 5594 const int EP_ObjCMethod = 1; 5595 const int EP_ObjCProperty = 2; 5596 5597 SourceLocation loc = Attrs.getLoc(); 5598 QualType resultType; 5599 if (isa<ObjCMethodDecl>(D)) 5600 resultType = cast<ObjCMethodDecl>(D)->getReturnType(); 5601 else 5602 resultType = cast<ObjCPropertyDecl>(D)->getType(); 5603 5604 if (!resultType->isReferenceType() && 5605 (!resultType->isPointerType() || resultType->isObjCRetainableType())) { 5606 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type) 5607 << SourceRange(loc) << Attrs 5608 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty) 5609 << /*non-retainable pointer*/ 2; 5610 5611 // Drop the attribute. 5612 return; 5613 } 5614 5615 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs)); 5616 } 5617 5618 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D, 5619 const ParsedAttr &Attrs) { 5620 const auto *Method = cast<ObjCMethodDecl>(D); 5621 5622 const DeclContext *DC = Method->getDeclContext(); 5623 if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) { 5624 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs 5625 << 0; 5626 S.Diag(PDecl->getLocation(), diag::note_protocol_decl); 5627 return; 5628 } 5629 if (Method->getMethodFamily() == OMF_dealloc) { 5630 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs 5631 << 1; 5632 return; 5633 } 5634 5635 D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs)); 5636 } 5637 5638 static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &AL) { 5639 auto *E = AL.getArgAsExpr(0); 5640 auto Loc = E ? E->getBeginLoc() : AL.getLoc(); 5641 5642 auto *DRE = dyn_cast<DeclRefExpr>(AL.getArgAsExpr(0)); 5643 if (!DRE) { 5644 S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 0; 5645 return; 5646 } 5647 5648 auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 5649 if (!VD) { 5650 S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 1 << DRE->getDecl(); 5651 return; 5652 } 5653 5654 if (!isNSStringType(VD->getType(), S.Context) && 5655 !isCFStringType(VD->getType(), S.Context)) { 5656 S.Diag(Loc, diag::err_nserrordomain_wrong_type) << VD; 5657 return; 5658 } 5659 5660 D->addAttr(::new (S.Context) NSErrorDomainAttr(S.Context, AL, VD)); 5661 } 5662 5663 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5664 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr; 5665 5666 if (!Parm) { 5667 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0; 5668 return; 5669 } 5670 5671 // Typedefs only allow objc_bridge(id) and have some additional checking. 5672 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 5673 if (!Parm->Ident->isStr("id")) { 5674 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL; 5675 return; 5676 } 5677 5678 // Only allow 'cv void *'. 5679 QualType T = TD->getUnderlyingType(); 5680 if (!T->isVoidPointerType()) { 5681 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer); 5682 return; 5683 } 5684 } 5685 5686 D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident)); 5687 } 5688 5689 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D, 5690 const ParsedAttr &AL) { 5691 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr; 5692 5693 if (!Parm) { 5694 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0; 5695 return; 5696 } 5697 5698 D->addAttr(::new (S.Context) 5699 ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident)); 5700 } 5701 5702 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D, 5703 const ParsedAttr &AL) { 5704 IdentifierInfo *RelatedClass = 5705 AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr; 5706 if (!RelatedClass) { 5707 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0; 5708 return; 5709 } 5710 IdentifierInfo *ClassMethod = 5711 AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr; 5712 IdentifierInfo *InstanceMethod = 5713 AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr; 5714 D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr( 5715 S.Context, AL, RelatedClass, ClassMethod, InstanceMethod)); 5716 } 5717 5718 static void handleObjCDesignatedInitializer(Sema &S, Decl *D, 5719 const ParsedAttr &AL) { 5720 DeclContext *Ctx = D->getDeclContext(); 5721 5722 // This attribute can only be applied to methods in interfaces or class 5723 // extensions. 5724 if (!isa<ObjCInterfaceDecl>(Ctx) && 5725 !(isa<ObjCCategoryDecl>(Ctx) && 5726 cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) { 5727 S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init); 5728 return; 5729 } 5730 5731 ObjCInterfaceDecl *IFace; 5732 if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx)) 5733 IFace = CatDecl->getClassInterface(); 5734 else 5735 IFace = cast<ObjCInterfaceDecl>(Ctx); 5736 5737 if (!IFace) 5738 return; 5739 5740 IFace->setHasDesignatedInitializers(); 5741 D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL)); 5742 } 5743 5744 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) { 5745 StringRef MetaDataName; 5746 if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName)) 5747 return; 5748 D->addAttr(::new (S.Context) 5749 ObjCRuntimeNameAttr(S.Context, AL, MetaDataName)); 5750 } 5751 5752 // When a user wants to use objc_boxable with a union or struct 5753 // but they don't have access to the declaration (legacy/third-party code) 5754 // then they can 'enable' this feature with a typedef: 5755 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct; 5756 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) { 5757 bool notify = false; 5758 5759 auto *RD = dyn_cast<RecordDecl>(D); 5760 if (RD && RD->getDefinition()) { 5761 RD = RD->getDefinition(); 5762 notify = true; 5763 } 5764 5765 if (RD) { 5766 ObjCBoxableAttr *BoxableAttr = 5767 ::new (S.Context) ObjCBoxableAttr(S.Context, AL); 5768 RD->addAttr(BoxableAttr); 5769 if (notify) { 5770 // we need to notify ASTReader/ASTWriter about 5771 // modification of existing declaration 5772 if (ASTMutationListener *L = S.getASTMutationListener()) 5773 L->AddedAttributeToRecord(BoxableAttr, RD); 5774 } 5775 } 5776 } 5777 5778 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5779 if (hasDeclarator(D)) return; 5780 5781 S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type) 5782 << AL.getRange() << AL << ExpectedVariable; 5783 } 5784 5785 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D, 5786 const ParsedAttr &AL) { 5787 const auto *VD = cast<ValueDecl>(D); 5788 QualType QT = VD->getType(); 5789 5790 if (!QT->isDependentType() && 5791 !QT->isObjCLifetimeType()) { 5792 S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type) 5793 << QT; 5794 return; 5795 } 5796 5797 Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime(); 5798 5799 // If we have no lifetime yet, check the lifetime we're presumably 5800 // going to infer. 5801 if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType()) 5802 Lifetime = QT->getObjCARCImplicitLifetime(); 5803 5804 switch (Lifetime) { 5805 case Qualifiers::OCL_None: 5806 assert(QT->isDependentType() && 5807 "didn't infer lifetime for non-dependent type?"); 5808 break; 5809 5810 case Qualifiers::OCL_Weak: // meaningful 5811 case Qualifiers::OCL_Strong: // meaningful 5812 break; 5813 5814 case Qualifiers::OCL_ExplicitNone: 5815 case Qualifiers::OCL_Autoreleasing: 5816 S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless) 5817 << (Lifetime == Qualifiers::OCL_Autoreleasing); 5818 break; 5819 } 5820 5821 D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL)); 5822 } 5823 5824 static void handleSwiftAttrAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5825 // Make sure that there is a string literal as the annotation's single 5826 // argument. 5827 StringRef Str; 5828 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 5829 return; 5830 5831 D->addAttr(::new (S.Context) SwiftAttrAttr(S.Context, AL, Str)); 5832 } 5833 5834 static void handleSwiftBridge(Sema &S, Decl *D, const ParsedAttr &AL) { 5835 // Make sure that there is a string literal as the annotation's single 5836 // argument. 5837 StringRef BT; 5838 if (!S.checkStringLiteralArgumentAttr(AL, 0, BT)) 5839 return; 5840 5841 // Warn about duplicate attributes if they have different arguments, but drop 5842 // any duplicate attributes regardless. 5843 if (const auto *Other = D->getAttr<SwiftBridgeAttr>()) { 5844 if (Other->getSwiftType() != BT) 5845 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 5846 return; 5847 } 5848 5849 D->addAttr(::new (S.Context) SwiftBridgeAttr(S.Context, AL, BT)); 5850 } 5851 5852 static bool isErrorParameter(Sema &S, QualType QT) { 5853 const auto *PT = QT->getAs<PointerType>(); 5854 if (!PT) 5855 return false; 5856 5857 QualType Pointee = PT->getPointeeType(); 5858 5859 // Check for NSError**. 5860 if (const auto *OPT = Pointee->getAs<ObjCObjectPointerType>()) 5861 if (const auto *ID = OPT->getInterfaceDecl()) 5862 if (ID->getIdentifier() == S.getNSErrorIdent()) 5863 return true; 5864 5865 // Check for CFError**. 5866 if (const auto *PT = Pointee->getAs<PointerType>()) 5867 if (const auto *RT = PT->getPointeeType()->getAs<RecordType>()) 5868 if (S.isCFError(RT->getDecl())) 5869 return true; 5870 5871 return false; 5872 } 5873 5874 static void handleSwiftError(Sema &S, Decl *D, const ParsedAttr &AL) { 5875 auto hasErrorParameter = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool { 5876 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) { 5877 if (isErrorParameter(S, getFunctionOrMethodParamType(D, I))) 5878 return true; 5879 } 5880 5881 S.Diag(AL.getLoc(), diag::err_attr_swift_error_no_error_parameter) 5882 << AL << isa<ObjCMethodDecl>(D); 5883 return false; 5884 }; 5885 5886 auto hasPointerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool { 5887 // - C, ObjC, and block pointers are definitely okay. 5888 // - References are definitely not okay. 5889 // - nullptr_t is weird, but acceptable. 5890 QualType RT = getFunctionOrMethodResultType(D); 5891 if (RT->hasPointerRepresentation() && !RT->isReferenceType()) 5892 return true; 5893 5894 S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type) 5895 << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D) 5896 << /*pointer*/ 1; 5897 return false; 5898 }; 5899 5900 auto hasIntegerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool { 5901 QualType RT = getFunctionOrMethodResultType(D); 5902 if (RT->isIntegralType(S.Context)) 5903 return true; 5904 5905 S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type) 5906 << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D) 5907 << /*integral*/ 0; 5908 return false; 5909 }; 5910 5911 if (D->isInvalidDecl()) 5912 return; 5913 5914 IdentifierLoc *Loc = AL.getArgAsIdent(0); 5915 SwiftErrorAttr::ConventionKind Convention; 5916 if (!SwiftErrorAttr::ConvertStrToConventionKind(Loc->Ident->getName(), 5917 Convention)) { 5918 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 5919 << AL << Loc->Ident; 5920 return; 5921 } 5922 5923 switch (Convention) { 5924 case SwiftErrorAttr::None: 5925 // No additional validation required. 5926 break; 5927 5928 case SwiftErrorAttr::NonNullError: 5929 if (!hasErrorParameter(S, D, AL)) 5930 return; 5931 break; 5932 5933 case SwiftErrorAttr::NullResult: 5934 if (!hasErrorParameter(S, D, AL) || !hasPointerResult(S, D, AL)) 5935 return; 5936 break; 5937 5938 case SwiftErrorAttr::NonZeroResult: 5939 case SwiftErrorAttr::ZeroResult: 5940 if (!hasErrorParameter(S, D, AL) || !hasIntegerResult(S, D, AL)) 5941 return; 5942 break; 5943 } 5944 5945 D->addAttr(::new (S.Context) SwiftErrorAttr(S.Context, AL, Convention)); 5946 } 5947 5948 static void checkSwiftAsyncErrorBlock(Sema &S, Decl *D, 5949 const SwiftAsyncErrorAttr *ErrorAttr, 5950 const SwiftAsyncAttr *AsyncAttr) { 5951 if (AsyncAttr->getKind() == SwiftAsyncAttr::None) { 5952 if (ErrorAttr->getConvention() != SwiftAsyncErrorAttr::None) { 5953 S.Diag(AsyncAttr->getLocation(), 5954 diag::err_swift_async_error_without_swift_async) 5955 << AsyncAttr << isa<ObjCMethodDecl>(D); 5956 } 5957 return; 5958 } 5959 5960 const ParmVarDecl *HandlerParam = getFunctionOrMethodParam( 5961 D, AsyncAttr->getCompletionHandlerIndex().getASTIndex()); 5962 // handleSwiftAsyncAttr already verified the type is correct, so no need to 5963 // double-check it here. 5964 const auto *FuncTy = HandlerParam->getType() 5965 ->castAs<BlockPointerType>() 5966 ->getPointeeType() 5967 ->getAs<FunctionProtoType>(); 5968 ArrayRef<QualType> BlockParams; 5969 if (FuncTy) 5970 BlockParams = FuncTy->getParamTypes(); 5971 5972 switch (ErrorAttr->getConvention()) { 5973 case SwiftAsyncErrorAttr::ZeroArgument: 5974 case SwiftAsyncErrorAttr::NonZeroArgument: { 5975 uint32_t ParamIdx = ErrorAttr->getHandlerParamIdx(); 5976 if (ParamIdx == 0 || ParamIdx > BlockParams.size()) { 5977 S.Diag(ErrorAttr->getLocation(), 5978 diag::err_attribute_argument_out_of_bounds) << ErrorAttr << 2; 5979 return; 5980 } 5981 QualType ErrorParam = BlockParams[ParamIdx - 1]; 5982 if (!ErrorParam->isIntegralType(S.Context)) { 5983 StringRef ConvStr = 5984 ErrorAttr->getConvention() == SwiftAsyncErrorAttr::ZeroArgument 5985 ? "zero_argument" 5986 : "nonzero_argument"; 5987 S.Diag(ErrorAttr->getLocation(), diag::err_swift_async_error_non_integral) 5988 << ErrorAttr << ConvStr << ParamIdx << ErrorParam; 5989 return; 5990 } 5991 break; 5992 } 5993 case SwiftAsyncErrorAttr::NonNullError: { 5994 bool AnyErrorParams = false; 5995 for (QualType Param : BlockParams) { 5996 // Check for NSError *. 5997 if (const auto *ObjCPtrTy = Param->getAs<ObjCObjectPointerType>()) { 5998 if (const auto *ID = ObjCPtrTy->getInterfaceDecl()) { 5999 if (ID->getIdentifier() == S.getNSErrorIdent()) { 6000 AnyErrorParams = true; 6001 break; 6002 } 6003 } 6004 } 6005 // Check for CFError *. 6006 if (const auto *PtrTy = Param->getAs<PointerType>()) { 6007 if (const auto *RT = PtrTy->getPointeeType()->getAs<RecordType>()) { 6008 if (S.isCFError(RT->getDecl())) { 6009 AnyErrorParams = true; 6010 break; 6011 } 6012 } 6013 } 6014 } 6015 6016 if (!AnyErrorParams) { 6017 S.Diag(ErrorAttr->getLocation(), 6018 diag::err_swift_async_error_no_error_parameter) 6019 << ErrorAttr << isa<ObjCMethodDecl>(D); 6020 return; 6021 } 6022 break; 6023 } 6024 case SwiftAsyncErrorAttr::None: 6025 break; 6026 } 6027 } 6028 6029 static void handleSwiftAsyncError(Sema &S, Decl *D, const ParsedAttr &AL) { 6030 IdentifierLoc *IDLoc = AL.getArgAsIdent(0); 6031 SwiftAsyncErrorAttr::ConventionKind ConvKind; 6032 if (!SwiftAsyncErrorAttr::ConvertStrToConventionKind(IDLoc->Ident->getName(), 6033 ConvKind)) { 6034 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 6035 << AL << IDLoc->Ident; 6036 return; 6037 } 6038 6039 uint32_t ParamIdx = 0; 6040 switch (ConvKind) { 6041 case SwiftAsyncErrorAttr::ZeroArgument: 6042 case SwiftAsyncErrorAttr::NonZeroArgument: { 6043 if (!AL.checkExactlyNumArgs(S, 2)) 6044 return; 6045 6046 Expr *IdxExpr = AL.getArgAsExpr(1); 6047 if (!checkUInt32Argument(S, AL, IdxExpr, ParamIdx)) 6048 return; 6049 break; 6050 } 6051 case SwiftAsyncErrorAttr::NonNullError: 6052 case SwiftAsyncErrorAttr::None: { 6053 if (!AL.checkExactlyNumArgs(S, 1)) 6054 return; 6055 break; 6056 } 6057 } 6058 6059 auto *ErrorAttr = 6060 ::new (S.Context) SwiftAsyncErrorAttr(S.Context, AL, ConvKind, ParamIdx); 6061 D->addAttr(ErrorAttr); 6062 6063 if (auto *AsyncAttr = D->getAttr<SwiftAsyncAttr>()) 6064 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr); 6065 } 6066 6067 // For a function, this will validate a compound Swift name, e.g. 6068 // <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, and 6069 // the function will output the number of parameter names, and whether this is a 6070 // single-arg initializer. 6071 // 6072 // For a type, enum constant, property, or variable declaration, this will 6073 // validate either a simple identifier, or a qualified 6074 // <code>context.identifier</code> name. 6075 static bool 6076 validateSwiftFunctionName(Sema &S, const ParsedAttr &AL, SourceLocation Loc, 6077 StringRef Name, unsigned &SwiftParamCount, 6078 bool &IsSingleParamInit) { 6079 SwiftParamCount = 0; 6080 IsSingleParamInit = false; 6081 6082 // Check whether this will be mapped to a getter or setter of a property. 6083 bool IsGetter = false, IsSetter = false; 6084 if (Name.startswith("getter:")) { 6085 IsGetter = true; 6086 Name = Name.substr(7); 6087 } else if (Name.startswith("setter:")) { 6088 IsSetter = true; 6089 Name = Name.substr(7); 6090 } 6091 6092 if (Name.back() != ')') { 6093 S.Diag(Loc, diag::warn_attr_swift_name_function) << AL; 6094 return false; 6095 } 6096 6097 bool IsMember = false; 6098 StringRef ContextName, BaseName, Parameters; 6099 6100 std::tie(BaseName, Parameters) = Name.split('('); 6101 6102 // Split at the first '.', if it exists, which separates the context name 6103 // from the base name. 6104 std::tie(ContextName, BaseName) = BaseName.split('.'); 6105 if (BaseName.empty()) { 6106 BaseName = ContextName; 6107 ContextName = StringRef(); 6108 } else if (ContextName.empty() || !isValidIdentifier(ContextName)) { 6109 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) 6110 << AL << /*context*/ 1; 6111 return false; 6112 } else { 6113 IsMember = true; 6114 } 6115 6116 if (!isValidIdentifier(BaseName) || BaseName == "_") { 6117 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) 6118 << AL << /*basename*/ 0; 6119 return false; 6120 } 6121 6122 bool IsSubscript = BaseName == "subscript"; 6123 // A subscript accessor must be a getter or setter. 6124 if (IsSubscript && !IsGetter && !IsSetter) { 6125 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter) 6126 << AL << /* getter or setter */ 0; 6127 return false; 6128 } 6129 6130 if (Parameters.empty()) { 6131 S.Diag(Loc, diag::warn_attr_swift_name_missing_parameters) << AL; 6132 return false; 6133 } 6134 6135 assert(Parameters.back() == ')' && "expected ')'"); 6136 Parameters = Parameters.drop_back(); // ')' 6137 6138 if (Parameters.empty()) { 6139 // Setters and subscripts must have at least one parameter. 6140 if (IsSubscript) { 6141 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter) 6142 << AL << /* have at least one parameter */1; 6143 return false; 6144 } 6145 6146 if (IsSetter) { 6147 S.Diag(Loc, diag::warn_attr_swift_name_setter_parameters) << AL; 6148 return false; 6149 } 6150 6151 return true; 6152 } 6153 6154 if (Parameters.back() != ':') { 6155 S.Diag(Loc, diag::warn_attr_swift_name_function) << AL; 6156 return false; 6157 } 6158 6159 StringRef CurrentParam; 6160 llvm::Optional<unsigned> SelfLocation; 6161 unsigned NewValueCount = 0; 6162 llvm::Optional<unsigned> NewValueLocation; 6163 do { 6164 std::tie(CurrentParam, Parameters) = Parameters.split(':'); 6165 6166 if (!isValidIdentifier(CurrentParam)) { 6167 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) 6168 << AL << /*parameter*/2; 6169 return false; 6170 } 6171 6172 if (IsMember && CurrentParam == "self") { 6173 // "self" indicates the "self" argument for a member. 6174 6175 // More than one "self"? 6176 if (SelfLocation) { 6177 S.Diag(Loc, diag::warn_attr_swift_name_multiple_selfs) << AL; 6178 return false; 6179 } 6180 6181 // The "self" location is the current parameter. 6182 SelfLocation = SwiftParamCount; 6183 } else if (CurrentParam == "newValue") { 6184 // "newValue" indicates the "newValue" argument for a setter. 6185 6186 // There should only be one 'newValue', but it's only significant for 6187 // subscript accessors, so don't error right away. 6188 ++NewValueCount; 6189 6190 NewValueLocation = SwiftParamCount; 6191 } 6192 6193 ++SwiftParamCount; 6194 } while (!Parameters.empty()); 6195 6196 // Only instance subscripts are currently supported. 6197 if (IsSubscript && !SelfLocation) { 6198 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter) 6199 << AL << /*have a 'self:' parameter*/2; 6200 return false; 6201 } 6202 6203 IsSingleParamInit = 6204 SwiftParamCount == 1 && BaseName == "init" && CurrentParam != "_"; 6205 6206 // Check the number of parameters for a getter/setter. 6207 if (IsGetter || IsSetter) { 6208 // Setters have one parameter for the new value. 6209 unsigned NumExpectedParams = IsGetter ? 0 : 1; 6210 unsigned ParamDiag = 6211 IsGetter ? diag::warn_attr_swift_name_getter_parameters 6212 : diag::warn_attr_swift_name_setter_parameters; 6213 6214 // Instance methods have one parameter for "self". 6215 if (SelfLocation) 6216 ++NumExpectedParams; 6217 6218 // Subscripts may have additional parameters beyond the expected params for 6219 // the index. 6220 if (IsSubscript) { 6221 if (SwiftParamCount < NumExpectedParams) { 6222 S.Diag(Loc, ParamDiag) << AL; 6223 return false; 6224 } 6225 6226 // A subscript setter must explicitly label its newValue parameter to 6227 // distinguish it from index parameters. 6228 if (IsSetter) { 6229 if (!NewValueLocation) { 6230 S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_no_newValue) 6231 << AL; 6232 return false; 6233 } 6234 if (NewValueCount > 1) { 6235 S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_multiple_newValues) 6236 << AL; 6237 return false; 6238 } 6239 } else { 6240 // Subscript getters should have no 'newValue:' parameter. 6241 if (NewValueLocation) { 6242 S.Diag(Loc, diag::warn_attr_swift_name_subscript_getter_newValue) 6243 << AL; 6244 return false; 6245 } 6246 } 6247 } else { 6248 // Property accessors must have exactly the number of expected params. 6249 if (SwiftParamCount != NumExpectedParams) { 6250 S.Diag(Loc, ParamDiag) << AL; 6251 return false; 6252 } 6253 } 6254 } 6255 6256 return true; 6257 } 6258 6259 bool Sema::DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, 6260 const ParsedAttr &AL, bool IsAsync) { 6261 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 6262 ArrayRef<ParmVarDecl*> Params; 6263 unsigned ParamCount; 6264 6265 if (const auto *Method = dyn_cast<ObjCMethodDecl>(D)) { 6266 ParamCount = Method->getSelector().getNumArgs(); 6267 Params = Method->parameters().slice(0, ParamCount); 6268 } else { 6269 const auto *F = cast<FunctionDecl>(D); 6270 6271 ParamCount = F->getNumParams(); 6272 Params = F->parameters(); 6273 6274 if (!F->hasWrittenPrototype()) { 6275 Diag(Loc, diag::warn_attribute_wrong_decl_type) << AL 6276 << ExpectedFunctionWithProtoType; 6277 return false; 6278 } 6279 } 6280 6281 // The async name drops the last callback parameter. 6282 if (IsAsync) { 6283 if (ParamCount == 0) { 6284 Diag(Loc, diag::warn_attr_swift_name_decl_missing_params) 6285 << AL << isa<ObjCMethodDecl>(D); 6286 return false; 6287 } 6288 ParamCount -= 1; 6289 } 6290 6291 unsigned SwiftParamCount; 6292 bool IsSingleParamInit; 6293 if (!validateSwiftFunctionName(*this, AL, Loc, Name, 6294 SwiftParamCount, IsSingleParamInit)) 6295 return false; 6296 6297 bool ParamCountValid; 6298 if (SwiftParamCount == ParamCount) { 6299 ParamCountValid = true; 6300 } else if (SwiftParamCount > ParamCount) { 6301 ParamCountValid = IsSingleParamInit && ParamCount == 0; 6302 } else { 6303 // We have fewer Swift parameters than Objective-C parameters, but that 6304 // might be because we've transformed some of them. Check for potential 6305 // "out" parameters and err on the side of not warning. 6306 unsigned MaybeOutParamCount = 6307 std::count_if(Params.begin(), Params.end(), 6308 [](const ParmVarDecl *Param) -> bool { 6309 QualType ParamTy = Param->getType(); 6310 if (ParamTy->isReferenceType() || ParamTy->isPointerType()) 6311 return !ParamTy->getPointeeType().isConstQualified(); 6312 return false; 6313 }); 6314 6315 ParamCountValid = SwiftParamCount + MaybeOutParamCount >= ParamCount; 6316 } 6317 6318 if (!ParamCountValid) { 6319 Diag(Loc, diag::warn_attr_swift_name_num_params) 6320 << (SwiftParamCount > ParamCount) << AL << ParamCount 6321 << SwiftParamCount; 6322 return false; 6323 } 6324 } else if ((isa<EnumConstantDecl>(D) || isa<ObjCProtocolDecl>(D) || 6325 isa<ObjCInterfaceDecl>(D) || isa<ObjCPropertyDecl>(D) || 6326 isa<VarDecl>(D) || isa<TypedefNameDecl>(D) || isa<TagDecl>(D) || 6327 isa<IndirectFieldDecl>(D) || isa<FieldDecl>(D)) && 6328 !IsAsync) { 6329 StringRef ContextName, BaseName; 6330 6331 std::tie(ContextName, BaseName) = Name.split('.'); 6332 if (BaseName.empty()) { 6333 BaseName = ContextName; 6334 ContextName = StringRef(); 6335 } else if (!isValidIdentifier(ContextName)) { 6336 Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL 6337 << /*context*/1; 6338 return false; 6339 } 6340 6341 if (!isValidIdentifier(BaseName)) { 6342 Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL 6343 << /*basename*/0; 6344 return false; 6345 } 6346 } else { 6347 Diag(Loc, diag::warn_attr_swift_name_decl_kind) << AL; 6348 return false; 6349 } 6350 return true; 6351 } 6352 6353 static void handleSwiftName(Sema &S, Decl *D, const ParsedAttr &AL) { 6354 StringRef Name; 6355 SourceLocation Loc; 6356 if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc)) 6357 return; 6358 6359 if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/false)) 6360 return; 6361 6362 D->addAttr(::new (S.Context) SwiftNameAttr(S.Context, AL, Name)); 6363 } 6364 6365 static void handleSwiftAsyncName(Sema &S, Decl *D, const ParsedAttr &AL) { 6366 StringRef Name; 6367 SourceLocation Loc; 6368 if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc)) 6369 return; 6370 6371 if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/true)) 6372 return; 6373 6374 D->addAttr(::new (S.Context) SwiftAsyncNameAttr(S.Context, AL, Name)); 6375 } 6376 6377 static void handleSwiftNewType(Sema &S, Decl *D, const ParsedAttr &AL) { 6378 // Make sure that there is an identifier as the annotation's single argument. 6379 if (!AL.checkExactlyNumArgs(S, 1)) 6380 return; 6381 6382 if (!AL.isArgIdent(0)) { 6383 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 6384 << AL << AANT_ArgumentIdentifier; 6385 return; 6386 } 6387 6388 SwiftNewTypeAttr::NewtypeKind Kind; 6389 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 6390 if (!SwiftNewTypeAttr::ConvertStrToNewtypeKind(II->getName(), Kind)) { 6391 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; 6392 return; 6393 } 6394 6395 if (!isa<TypedefNameDecl>(D)) { 6396 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str) 6397 << AL << "typedefs"; 6398 return; 6399 } 6400 6401 D->addAttr(::new (S.Context) SwiftNewTypeAttr(S.Context, AL, Kind)); 6402 } 6403 6404 static void handleSwiftAsyncAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6405 if (!AL.isArgIdent(0)) { 6406 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 6407 << AL << 1 << AANT_ArgumentIdentifier; 6408 return; 6409 } 6410 6411 SwiftAsyncAttr::Kind Kind; 6412 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 6413 if (!SwiftAsyncAttr::ConvertStrToKind(II->getName(), Kind)) { 6414 S.Diag(AL.getLoc(), diag::err_swift_async_no_access) << AL << II; 6415 return; 6416 } 6417 6418 ParamIdx Idx; 6419 if (Kind == SwiftAsyncAttr::None) { 6420 // If this is 'none', then there shouldn't be any additional arguments. 6421 if (!AL.checkExactlyNumArgs(S, 1)) 6422 return; 6423 } else { 6424 // Non-none swift_async requires a completion handler index argument. 6425 if (!AL.checkExactlyNumArgs(S, 2)) 6426 return; 6427 6428 Expr *HandlerIdx = AL.getArgAsExpr(1); 6429 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, HandlerIdx, Idx)) 6430 return; 6431 6432 const ParmVarDecl *CompletionBlock = 6433 getFunctionOrMethodParam(D, Idx.getASTIndex()); 6434 QualType CompletionBlockType = CompletionBlock->getType(); 6435 if (!CompletionBlockType->isBlockPointerType()) { 6436 S.Diag(CompletionBlock->getLocation(), 6437 diag::err_swift_async_bad_block_type) 6438 << CompletionBlock->getType(); 6439 return; 6440 } 6441 QualType BlockTy = 6442 CompletionBlockType->castAs<BlockPointerType>()->getPointeeType(); 6443 if (!BlockTy->castAs<FunctionType>()->getReturnType()->isVoidType()) { 6444 S.Diag(CompletionBlock->getLocation(), 6445 diag::err_swift_async_bad_block_type) 6446 << CompletionBlock->getType(); 6447 return; 6448 } 6449 } 6450 6451 auto *AsyncAttr = 6452 ::new (S.Context) SwiftAsyncAttr(S.Context, AL, Kind, Idx); 6453 D->addAttr(AsyncAttr); 6454 6455 if (auto *ErrorAttr = D->getAttr<SwiftAsyncErrorAttr>()) 6456 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr); 6457 } 6458 6459 //===----------------------------------------------------------------------===// 6460 // Microsoft specific attribute handlers. 6461 //===----------------------------------------------------------------------===// 6462 6463 UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, 6464 StringRef UuidAsWritten, MSGuidDecl *GuidDecl) { 6465 if (const auto *UA = D->getAttr<UuidAttr>()) { 6466 if (declaresSameEntity(UA->getGuidDecl(), GuidDecl)) 6467 return nullptr; 6468 if (!UA->getGuid().empty()) { 6469 Diag(UA->getLocation(), diag::err_mismatched_uuid); 6470 Diag(CI.getLoc(), diag::note_previous_uuid); 6471 D->dropAttr<UuidAttr>(); 6472 } 6473 } 6474 6475 return ::new (Context) UuidAttr(Context, CI, UuidAsWritten, GuidDecl); 6476 } 6477 6478 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6479 if (!S.LangOpts.CPlusPlus) { 6480 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang) 6481 << AL << AttributeLangSupport::C; 6482 return; 6483 } 6484 6485 StringRef OrigStrRef; 6486 SourceLocation LiteralLoc; 6487 if (!S.checkStringLiteralArgumentAttr(AL, 0, OrigStrRef, &LiteralLoc)) 6488 return; 6489 6490 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or 6491 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former. 6492 StringRef StrRef = OrigStrRef; 6493 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}') 6494 StrRef = StrRef.drop_front().drop_back(); 6495 6496 // Validate GUID length. 6497 if (StrRef.size() != 36) { 6498 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 6499 return; 6500 } 6501 6502 for (unsigned i = 0; i < 36; ++i) { 6503 if (i == 8 || i == 13 || i == 18 || i == 23) { 6504 if (StrRef[i] != '-') { 6505 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 6506 return; 6507 } 6508 } else if (!isHexDigit(StrRef[i])) { 6509 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 6510 return; 6511 } 6512 } 6513 6514 // Convert to our parsed format and canonicalize. 6515 MSGuidDecl::Parts Parsed; 6516 StrRef.substr(0, 8).getAsInteger(16, Parsed.Part1); 6517 StrRef.substr(9, 4).getAsInteger(16, Parsed.Part2); 6518 StrRef.substr(14, 4).getAsInteger(16, Parsed.Part3); 6519 for (unsigned i = 0; i != 8; ++i) 6520 StrRef.substr(19 + 2 * i + (i >= 2 ? 1 : 0), 2) 6521 .getAsInteger(16, Parsed.Part4And5[i]); 6522 MSGuidDecl *Guid = S.Context.getMSGuidDecl(Parsed); 6523 6524 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's 6525 // the only thing in the [] list, the [] too), and add an insertion of 6526 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas 6527 // separating attributes nor of the [ and the ] are in the AST. 6528 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc" 6529 // on cfe-dev. 6530 if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling. 6531 S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated); 6532 6533 UuidAttr *UA = S.mergeUuidAttr(D, AL, OrigStrRef, Guid); 6534 if (UA) 6535 D->addAttr(UA); 6536 } 6537 6538 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6539 if (!S.LangOpts.CPlusPlus) { 6540 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang) 6541 << AL << AttributeLangSupport::C; 6542 return; 6543 } 6544 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr( 6545 D, AL, /*BestCase=*/true, (MSInheritanceModel)AL.getSemanticSpelling()); 6546 if (IA) { 6547 D->addAttr(IA); 6548 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 6549 } 6550 } 6551 6552 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6553 const auto *VD = cast<VarDecl>(D); 6554 if (!S.Context.getTargetInfo().isTLSSupported()) { 6555 S.Diag(AL.getLoc(), diag::err_thread_unsupported); 6556 return; 6557 } 6558 if (VD->getTSCSpec() != TSCS_unspecified) { 6559 S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable); 6560 return; 6561 } 6562 if (VD->hasLocalStorage()) { 6563 S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)"; 6564 return; 6565 } 6566 D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL)); 6567 } 6568 6569 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6570 SmallVector<StringRef, 4> Tags; 6571 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 6572 StringRef Tag; 6573 if (!S.checkStringLiteralArgumentAttr(AL, I, Tag)) 6574 return; 6575 Tags.push_back(Tag); 6576 } 6577 6578 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) { 6579 if (!NS->isInline()) { 6580 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0; 6581 return; 6582 } 6583 if (NS->isAnonymousNamespace()) { 6584 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1; 6585 return; 6586 } 6587 if (AL.getNumArgs() == 0) 6588 Tags.push_back(NS->getName()); 6589 } else if (!AL.checkAtLeastNumArgs(S, 1)) 6590 return; 6591 6592 // Store tags sorted and without duplicates. 6593 llvm::sort(Tags); 6594 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end()); 6595 6596 D->addAttr(::new (S.Context) 6597 AbiTagAttr(S.Context, AL, Tags.data(), Tags.size())); 6598 } 6599 6600 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6601 // Check the attribute arguments. 6602 if (AL.getNumArgs() > 1) { 6603 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1; 6604 return; 6605 } 6606 6607 StringRef Str; 6608 SourceLocation ArgLoc; 6609 6610 if (AL.getNumArgs() == 0) 6611 Str = ""; 6612 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 6613 return; 6614 6615 ARMInterruptAttr::InterruptType Kind; 6616 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 6617 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str 6618 << ArgLoc; 6619 return; 6620 } 6621 6622 D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind)); 6623 } 6624 6625 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6626 // MSP430 'interrupt' attribute is applied to 6627 // a function with no parameters and void return type. 6628 if (!isFunctionOrMethod(D)) { 6629 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 6630 << "'interrupt'" << ExpectedFunctionOrMethod; 6631 return; 6632 } 6633 6634 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { 6635 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 6636 << /*MSP430*/ 1 << 0; 6637 return; 6638 } 6639 6640 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 6641 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 6642 << /*MSP430*/ 1 << 1; 6643 return; 6644 } 6645 6646 // The attribute takes one integer argument. 6647 if (!AL.checkExactlyNumArgs(S, 1)) 6648 return; 6649 6650 if (!AL.isArgExpr(0)) { 6651 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 6652 << AL << AANT_ArgumentIntegerConstant; 6653 return; 6654 } 6655 6656 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0)); 6657 Optional<llvm::APSInt> NumParams = llvm::APSInt(32); 6658 if (!(NumParams = NumParamsExpr->getIntegerConstantExpr(S.Context))) { 6659 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 6660 << AL << AANT_ArgumentIntegerConstant 6661 << NumParamsExpr->getSourceRange(); 6662 return; 6663 } 6664 // The argument should be in range 0..63. 6665 unsigned Num = NumParams->getLimitedValue(255); 6666 if (Num > 63) { 6667 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 6668 << AL << (int)NumParams->getSExtValue() 6669 << NumParamsExpr->getSourceRange(); 6670 return; 6671 } 6672 6673 D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num)); 6674 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 6675 } 6676 6677 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6678 // Only one optional argument permitted. 6679 if (AL.getNumArgs() > 1) { 6680 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1; 6681 return; 6682 } 6683 6684 StringRef Str; 6685 SourceLocation ArgLoc; 6686 6687 if (AL.getNumArgs() == 0) 6688 Str = ""; 6689 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 6690 return; 6691 6692 // Semantic checks for a function with the 'interrupt' attribute for MIPS: 6693 // a) Must be a function. 6694 // b) Must have no parameters. 6695 // c) Must have the 'void' return type. 6696 // d) Cannot have the 'mips16' attribute, as that instruction set 6697 // lacks the 'eret' instruction. 6698 // e) The attribute itself must either have no argument or one of the 6699 // valid interrupt types, see [MipsInterruptDocs]. 6700 6701 if (!isFunctionOrMethod(D)) { 6702 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 6703 << "'interrupt'" << ExpectedFunctionOrMethod; 6704 return; 6705 } 6706 6707 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { 6708 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 6709 << /*MIPS*/ 0 << 0; 6710 return; 6711 } 6712 6713 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 6714 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 6715 << /*MIPS*/ 0 << 1; 6716 return; 6717 } 6718 6719 // We still have to do this manually because the Interrupt attributes are 6720 // a bit special due to sharing their spellings across targets. 6721 if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL)) 6722 return; 6723 6724 MipsInterruptAttr::InterruptType Kind; 6725 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 6726 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 6727 << AL << "'" + std::string(Str) + "'"; 6728 return; 6729 } 6730 6731 D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind)); 6732 } 6733 6734 static void handleM68kInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6735 if (!AL.checkExactlyNumArgs(S, 1)) 6736 return; 6737 6738 if (!AL.isArgExpr(0)) { 6739 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 6740 << AL << AANT_ArgumentIntegerConstant; 6741 return; 6742 } 6743 6744 // FIXME: Check for decl - it should be void ()(void). 6745 6746 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0)); 6747 auto MaybeNumParams = NumParamsExpr->getIntegerConstantExpr(S.Context); 6748 if (!MaybeNumParams) { 6749 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 6750 << AL << AANT_ArgumentIntegerConstant 6751 << NumParamsExpr->getSourceRange(); 6752 return; 6753 } 6754 6755 unsigned Num = MaybeNumParams->getLimitedValue(255); 6756 if ((Num & 1) || Num > 30) { 6757 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 6758 << AL << (int)MaybeNumParams->getSExtValue() 6759 << NumParamsExpr->getSourceRange(); 6760 return; 6761 } 6762 6763 D->addAttr(::new (S.Context) M68kInterruptAttr(S.Context, AL, Num)); 6764 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 6765 } 6766 6767 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6768 // Semantic checks for a function with the 'interrupt' attribute. 6769 // a) Must be a function. 6770 // b) Must have the 'void' return type. 6771 // c) Must take 1 or 2 arguments. 6772 // d) The 1st argument must be a pointer. 6773 // e) The 2nd argument (if any) must be an unsigned integer. 6774 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) || 6775 CXXMethodDecl::isStaticOverloadedOperator( 6776 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) { 6777 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 6778 << AL << ExpectedFunctionWithProtoType; 6779 return; 6780 } 6781 // Interrupt handler must have void return type. 6782 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 6783 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(), 6784 diag::err_anyx86_interrupt_attribute) 6785 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 6786 ? 0 6787 : 1) 6788 << 0; 6789 return; 6790 } 6791 // Interrupt handler must have 1 or 2 parameters. 6792 unsigned NumParams = getFunctionOrMethodNumParams(D); 6793 if (NumParams < 1 || NumParams > 2) { 6794 S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute) 6795 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 6796 ? 0 6797 : 1) 6798 << 1; 6799 return; 6800 } 6801 // The first argument must be a pointer. 6802 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) { 6803 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(), 6804 diag::err_anyx86_interrupt_attribute) 6805 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 6806 ? 0 6807 : 1) 6808 << 2; 6809 return; 6810 } 6811 // The second argument, if present, must be an unsigned integer. 6812 unsigned TypeSize = 6813 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64 6814 ? 64 6815 : 32; 6816 if (NumParams == 2 && 6817 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() || 6818 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) { 6819 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(), 6820 diag::err_anyx86_interrupt_attribute) 6821 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 6822 ? 0 6823 : 1) 6824 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false); 6825 return; 6826 } 6827 D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL)); 6828 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 6829 } 6830 6831 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6832 if (!isFunctionOrMethod(D)) { 6833 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 6834 << "'interrupt'" << ExpectedFunction; 6835 return; 6836 } 6837 6838 if (!AL.checkExactlyNumArgs(S, 0)) 6839 return; 6840 6841 handleSimpleAttribute<AVRInterruptAttr>(S, D, AL); 6842 } 6843 6844 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6845 if (!isFunctionOrMethod(D)) { 6846 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 6847 << "'signal'" << ExpectedFunction; 6848 return; 6849 } 6850 6851 if (!AL.checkExactlyNumArgs(S, 0)) 6852 return; 6853 6854 handleSimpleAttribute<AVRSignalAttr>(S, D, AL); 6855 } 6856 6857 static void handleBPFPreserveAIRecord(Sema &S, RecordDecl *RD) { 6858 // Add preserve_access_index attribute to all fields and inner records. 6859 for (auto D : RD->decls()) { 6860 if (D->hasAttr<BPFPreserveAccessIndexAttr>()) 6861 continue; 6862 6863 D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S.Context)); 6864 if (auto *Rec = dyn_cast<RecordDecl>(D)) 6865 handleBPFPreserveAIRecord(S, Rec); 6866 } 6867 } 6868 6869 static void handleBPFPreserveAccessIndexAttr(Sema &S, Decl *D, 6870 const ParsedAttr &AL) { 6871 auto *Rec = cast<RecordDecl>(D); 6872 handleBPFPreserveAIRecord(S, Rec); 6873 Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL)); 6874 } 6875 6876 static bool hasBTFTagAttr(Decl *D, StringRef Tag) { 6877 for (const auto *I : D->specific_attrs<BTFTagAttr>()) { 6878 if (I->getBTFTag() == Tag) 6879 return true; 6880 } 6881 return false; 6882 } 6883 6884 static void handleBTFTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6885 StringRef Str; 6886 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 6887 return; 6888 if (hasBTFTagAttr(D, Str)) 6889 return; 6890 6891 D->addAttr(::new (S.Context) BTFTagAttr(S.Context, AL, Str)); 6892 } 6893 6894 BTFTagAttr *Sema::mergeBTFTagAttr(Decl *D, const BTFTagAttr &AL) { 6895 if (hasBTFTagAttr(D, AL.getBTFTag())) 6896 return nullptr; 6897 return ::new (Context) BTFTagAttr(Context, AL, AL.getBTFTag()); 6898 } 6899 6900 static void handleWebAssemblyExportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6901 if (!isFunctionOrMethod(D)) { 6902 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 6903 << "'export_name'" << ExpectedFunction; 6904 return; 6905 } 6906 6907 auto *FD = cast<FunctionDecl>(D); 6908 if (FD->isThisDeclarationADefinition()) { 6909 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0; 6910 return; 6911 } 6912 6913 StringRef Str; 6914 SourceLocation ArgLoc; 6915 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 6916 return; 6917 6918 D->addAttr(::new (S.Context) WebAssemblyExportNameAttr(S.Context, AL, Str)); 6919 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 6920 } 6921 6922 WebAssemblyImportModuleAttr * 6923 Sema::mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL) { 6924 auto *FD = cast<FunctionDecl>(D); 6925 6926 if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 6927 if (ExistingAttr->getImportModule() == AL.getImportModule()) 6928 return nullptr; 6929 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 0 6930 << ExistingAttr->getImportModule() << AL.getImportModule(); 6931 Diag(AL.getLoc(), diag::note_previous_attribute); 6932 return nullptr; 6933 } 6934 if (FD->hasBody()) { 6935 Diag(AL.getLoc(), diag::warn_import_on_definition) << 0; 6936 return nullptr; 6937 } 6938 return ::new (Context) WebAssemblyImportModuleAttr(Context, AL, 6939 AL.getImportModule()); 6940 } 6941 6942 WebAssemblyImportNameAttr * 6943 Sema::mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL) { 6944 auto *FD = cast<FunctionDecl>(D); 6945 6946 if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportNameAttr>()) { 6947 if (ExistingAttr->getImportName() == AL.getImportName()) 6948 return nullptr; 6949 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 1 6950 << ExistingAttr->getImportName() << AL.getImportName(); 6951 Diag(AL.getLoc(), diag::note_previous_attribute); 6952 return nullptr; 6953 } 6954 if (FD->hasBody()) { 6955 Diag(AL.getLoc(), diag::warn_import_on_definition) << 1; 6956 return nullptr; 6957 } 6958 return ::new (Context) WebAssemblyImportNameAttr(Context, AL, 6959 AL.getImportName()); 6960 } 6961 6962 static void 6963 handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6964 auto *FD = cast<FunctionDecl>(D); 6965 6966 StringRef Str; 6967 SourceLocation ArgLoc; 6968 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 6969 return; 6970 if (FD->hasBody()) { 6971 S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 0; 6972 return; 6973 } 6974 6975 FD->addAttr(::new (S.Context) 6976 WebAssemblyImportModuleAttr(S.Context, AL, Str)); 6977 } 6978 6979 static void 6980 handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6981 auto *FD = cast<FunctionDecl>(D); 6982 6983 StringRef Str; 6984 SourceLocation ArgLoc; 6985 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 6986 return; 6987 if (FD->hasBody()) { 6988 S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 1; 6989 return; 6990 } 6991 6992 FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str)); 6993 } 6994 6995 static void handleRISCVInterruptAttr(Sema &S, Decl *D, 6996 const ParsedAttr &AL) { 6997 // Warn about repeated attributes. 6998 if (const auto *A = D->getAttr<RISCVInterruptAttr>()) { 6999 S.Diag(AL.getRange().getBegin(), 7000 diag::warn_riscv_repeated_interrupt_attribute); 7001 S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute); 7002 return; 7003 } 7004 7005 // Check the attribute argument. Argument is optional. 7006 if (!AL.checkAtMostNumArgs(S, 1)) 7007 return; 7008 7009 StringRef Str; 7010 SourceLocation ArgLoc; 7011 7012 // 'machine'is the default interrupt mode. 7013 if (AL.getNumArgs() == 0) 7014 Str = "machine"; 7015 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 7016 return; 7017 7018 // Semantic checks for a function with the 'interrupt' attribute: 7019 // - Must be a function. 7020 // - Must have no parameters. 7021 // - Must have the 'void' return type. 7022 // - The attribute itself must either have no argument or one of the 7023 // valid interrupt types, see [RISCVInterruptDocs]. 7024 7025 if (D->getFunctionType() == nullptr) { 7026 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 7027 << "'interrupt'" << ExpectedFunction; 7028 return; 7029 } 7030 7031 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { 7032 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 7033 << /*RISC-V*/ 2 << 0; 7034 return; 7035 } 7036 7037 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 7038 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 7039 << /*RISC-V*/ 2 << 1; 7040 return; 7041 } 7042 7043 RISCVInterruptAttr::InterruptType Kind; 7044 if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 7045 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str 7046 << ArgLoc; 7047 return; 7048 } 7049 7050 D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind)); 7051 } 7052 7053 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7054 // Dispatch the interrupt attribute based on the current target. 7055 switch (S.Context.getTargetInfo().getTriple().getArch()) { 7056 case llvm::Triple::msp430: 7057 handleMSP430InterruptAttr(S, D, AL); 7058 break; 7059 case llvm::Triple::mipsel: 7060 case llvm::Triple::mips: 7061 handleMipsInterruptAttr(S, D, AL); 7062 break; 7063 case llvm::Triple::m68k: 7064 handleM68kInterruptAttr(S, D, AL); 7065 break; 7066 case llvm::Triple::x86: 7067 case llvm::Triple::x86_64: 7068 handleAnyX86InterruptAttr(S, D, AL); 7069 break; 7070 case llvm::Triple::avr: 7071 handleAVRInterruptAttr(S, D, AL); 7072 break; 7073 case llvm::Triple::riscv32: 7074 case llvm::Triple::riscv64: 7075 handleRISCVInterruptAttr(S, D, AL); 7076 break; 7077 default: 7078 handleARMInterruptAttr(S, D, AL); 7079 break; 7080 } 7081 } 7082 7083 static bool 7084 checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr, 7085 const AMDGPUFlatWorkGroupSizeAttr &Attr) { 7086 // Accept template arguments for now as they depend on something else. 7087 // We'll get to check them when they eventually get instantiated. 7088 if (MinExpr->isValueDependent() || MaxExpr->isValueDependent()) 7089 return false; 7090 7091 uint32_t Min = 0; 7092 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0)) 7093 return true; 7094 7095 uint32_t Max = 0; 7096 if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1)) 7097 return true; 7098 7099 if (Min == 0 && Max != 0) { 7100 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid) 7101 << &Attr << 0; 7102 return true; 7103 } 7104 if (Min > Max) { 7105 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid) 7106 << &Attr << 1; 7107 return true; 7108 } 7109 7110 return false; 7111 } 7112 7113 void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl *D, 7114 const AttributeCommonInfo &CI, 7115 Expr *MinExpr, Expr *MaxExpr) { 7116 AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr); 7117 7118 if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr)) 7119 return; 7120 7121 D->addAttr(::new (Context) 7122 AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr)); 7123 } 7124 7125 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D, 7126 const ParsedAttr &AL) { 7127 Expr *MinExpr = AL.getArgAsExpr(0); 7128 Expr *MaxExpr = AL.getArgAsExpr(1); 7129 7130 S.addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr); 7131 } 7132 7133 static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr, 7134 Expr *MaxExpr, 7135 const AMDGPUWavesPerEUAttr &Attr) { 7136 if (S.DiagnoseUnexpandedParameterPack(MinExpr) || 7137 (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr))) 7138 return true; 7139 7140 // Accept template arguments for now as they depend on something else. 7141 // We'll get to check them when they eventually get instantiated. 7142 if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent())) 7143 return false; 7144 7145 uint32_t Min = 0; 7146 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0)) 7147 return true; 7148 7149 uint32_t Max = 0; 7150 if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1)) 7151 return true; 7152 7153 if (Min == 0 && Max != 0) { 7154 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid) 7155 << &Attr << 0; 7156 return true; 7157 } 7158 if (Max != 0 && Min > Max) { 7159 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid) 7160 << &Attr << 1; 7161 return true; 7162 } 7163 7164 return false; 7165 } 7166 7167 void Sema::addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, 7168 Expr *MinExpr, Expr *MaxExpr) { 7169 AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr); 7170 7171 if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr)) 7172 return; 7173 7174 D->addAttr(::new (Context) 7175 AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr)); 7176 } 7177 7178 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7179 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2)) 7180 return; 7181 7182 Expr *MinExpr = AL.getArgAsExpr(0); 7183 Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr; 7184 7185 S.addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr); 7186 } 7187 7188 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7189 uint32_t NumSGPR = 0; 7190 Expr *NumSGPRExpr = AL.getArgAsExpr(0); 7191 if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR)) 7192 return; 7193 7194 D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR)); 7195 } 7196 7197 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7198 uint32_t NumVGPR = 0; 7199 Expr *NumVGPRExpr = AL.getArgAsExpr(0); 7200 if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR)) 7201 return; 7202 7203 D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR)); 7204 } 7205 7206 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D, 7207 const ParsedAttr &AL) { 7208 // If we try to apply it to a function pointer, don't warn, but don't 7209 // do anything, either. It doesn't matter anyway, because there's nothing 7210 // special about calling a force_align_arg_pointer function. 7211 const auto *VD = dyn_cast<ValueDecl>(D); 7212 if (VD && VD->getType()->isFunctionPointerType()) 7213 return; 7214 // Also don't warn on function pointer typedefs. 7215 const auto *TD = dyn_cast<TypedefNameDecl>(D); 7216 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() || 7217 TD->getUnderlyingType()->isFunctionType())) 7218 return; 7219 // Attribute can only be applied to function types. 7220 if (!isa<FunctionDecl>(D)) { 7221 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 7222 << AL << ExpectedFunction; 7223 return; 7224 } 7225 7226 D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL)); 7227 } 7228 7229 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) { 7230 uint32_t Version; 7231 Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0)); 7232 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version)) 7233 return; 7234 7235 // TODO: Investigate what happens with the next major version of MSVC. 7236 if (Version != LangOptions::MSVC2015 / 100) { 7237 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 7238 << AL << Version << VersionExpr->getSourceRange(); 7239 return; 7240 } 7241 7242 // The attribute expects a "major" version number like 19, but new versions of 7243 // MSVC have moved to updating the "minor", or less significant numbers, so we 7244 // have to multiply by 100 now. 7245 Version *= 100; 7246 7247 D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version)); 7248 } 7249 7250 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, 7251 const AttributeCommonInfo &CI) { 7252 if (D->hasAttr<DLLExportAttr>()) { 7253 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'"; 7254 return nullptr; 7255 } 7256 7257 if (D->hasAttr<DLLImportAttr>()) 7258 return nullptr; 7259 7260 return ::new (Context) DLLImportAttr(Context, CI); 7261 } 7262 7263 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, 7264 const AttributeCommonInfo &CI) { 7265 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) { 7266 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import; 7267 D->dropAttr<DLLImportAttr>(); 7268 } 7269 7270 if (D->hasAttr<DLLExportAttr>()) 7271 return nullptr; 7272 7273 return ::new (Context) DLLExportAttr(Context, CI); 7274 } 7275 7276 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) { 7277 if (isa<ClassTemplatePartialSpecializationDecl>(D) && 7278 (S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) { 7279 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A; 7280 return; 7281 } 7282 7283 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 7284 if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport && 7285 !(S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) { 7286 // MinGW doesn't allow dllimport on inline functions. 7287 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline) 7288 << A; 7289 return; 7290 } 7291 } 7292 7293 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 7294 if ((S.Context.getTargetInfo().shouldDLLImportComdatSymbols()) && 7295 MD->getParent()->isLambda()) { 7296 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A; 7297 return; 7298 } 7299 } 7300 7301 Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport 7302 ? (Attr *)S.mergeDLLExportAttr(D, A) 7303 : (Attr *)S.mergeDLLImportAttr(D, A); 7304 if (NewAttr) 7305 D->addAttr(NewAttr); 7306 } 7307 7308 MSInheritanceAttr * 7309 Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, 7310 bool BestCase, 7311 MSInheritanceModel Model) { 7312 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) { 7313 if (IA->getInheritanceModel() == Model) 7314 return nullptr; 7315 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance) 7316 << 1 /*previous declaration*/; 7317 Diag(CI.getLoc(), diag::note_previous_ms_inheritance); 7318 D->dropAttr<MSInheritanceAttr>(); 7319 } 7320 7321 auto *RD = cast<CXXRecordDecl>(D); 7322 if (RD->hasDefinition()) { 7323 if (checkMSInheritanceAttrOnDefinition(RD, CI.getRange(), BestCase, 7324 Model)) { 7325 return nullptr; 7326 } 7327 } else { 7328 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) { 7329 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance) 7330 << 1 /*partial specialization*/; 7331 return nullptr; 7332 } 7333 if (RD->getDescribedClassTemplate()) { 7334 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance) 7335 << 0 /*primary template*/; 7336 return nullptr; 7337 } 7338 } 7339 7340 return ::new (Context) MSInheritanceAttr(Context, CI, BestCase); 7341 } 7342 7343 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7344 // The capability attributes take a single string parameter for the name of 7345 // the capability they represent. The lockable attribute does not take any 7346 // parameters. However, semantically, both attributes represent the same 7347 // concept, and so they use the same semantic attribute. Eventually, the 7348 // lockable attribute will be removed. 7349 // 7350 // For backward compatibility, any capability which has no specified string 7351 // literal will be considered a "mutex." 7352 StringRef N("mutex"); 7353 SourceLocation LiteralLoc; 7354 if (AL.getKind() == ParsedAttr::AT_Capability && 7355 !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc)) 7356 return; 7357 7358 D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N)); 7359 } 7360 7361 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7362 SmallVector<Expr*, 1> Args; 7363 if (!checkLockFunAttrCommon(S, D, AL, Args)) 7364 return; 7365 7366 D->addAttr(::new (S.Context) 7367 AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size())); 7368 } 7369 7370 static void handleAcquireCapabilityAttr(Sema &S, Decl *D, 7371 const ParsedAttr &AL) { 7372 SmallVector<Expr*, 1> Args; 7373 if (!checkLockFunAttrCommon(S, D, AL, Args)) 7374 return; 7375 7376 D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(), 7377 Args.size())); 7378 } 7379 7380 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D, 7381 const ParsedAttr &AL) { 7382 SmallVector<Expr*, 2> Args; 7383 if (!checkTryLockFunAttrCommon(S, D, AL, Args)) 7384 return; 7385 7386 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr( 7387 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size())); 7388 } 7389 7390 static void handleReleaseCapabilityAttr(Sema &S, Decl *D, 7391 const ParsedAttr &AL) { 7392 // Check that all arguments are lockable objects. 7393 SmallVector<Expr *, 1> Args; 7394 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true); 7395 7396 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(), 7397 Args.size())); 7398 } 7399 7400 static void handleRequiresCapabilityAttr(Sema &S, Decl *D, 7401 const ParsedAttr &AL) { 7402 if (!AL.checkAtLeastNumArgs(S, 1)) 7403 return; 7404 7405 // check that all arguments are lockable objects 7406 SmallVector<Expr*, 1> Args; 7407 checkAttrArgsAreCapabilityObjs(S, D, AL, Args); 7408 if (Args.empty()) 7409 return; 7410 7411 RequiresCapabilityAttr *RCA = ::new (S.Context) 7412 RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size()); 7413 7414 D->addAttr(RCA); 7415 } 7416 7417 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7418 if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) { 7419 if (NSD->isAnonymousNamespace()) { 7420 S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace); 7421 // Do not want to attach the attribute to the namespace because that will 7422 // cause confusing diagnostic reports for uses of declarations within the 7423 // namespace. 7424 return; 7425 } 7426 } else if (isa<UsingDecl, UnresolvedUsingTypenameDecl, 7427 UnresolvedUsingValueDecl>(D)) { 7428 S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using) 7429 << AL; 7430 return; 7431 } 7432 7433 // Handle the cases where the attribute has a text message. 7434 StringRef Str, Replacement; 7435 if (AL.isArgExpr(0) && AL.getArgAsExpr(0) && 7436 !S.checkStringLiteralArgumentAttr(AL, 0, Str)) 7437 return; 7438 7439 // Support a single optional message only for Declspec and [[]] spellings. 7440 if (AL.isDeclspecAttribute() || AL.isStandardAttributeSyntax()) 7441 AL.checkAtMostNumArgs(S, 1); 7442 else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) && 7443 !S.checkStringLiteralArgumentAttr(AL, 1, Replacement)) 7444 return; 7445 7446 if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope()) 7447 S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL; 7448 7449 D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement)); 7450 } 7451 7452 static bool isGlobalVar(const Decl *D) { 7453 if (const auto *S = dyn_cast<VarDecl>(D)) 7454 return S->hasGlobalStorage(); 7455 return false; 7456 } 7457 7458 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7459 if (!AL.checkAtLeastNumArgs(S, 1)) 7460 return; 7461 7462 std::vector<StringRef> Sanitizers; 7463 7464 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 7465 StringRef SanitizerName; 7466 SourceLocation LiteralLoc; 7467 7468 if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc)) 7469 return; 7470 7471 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 7472 SanitizerMask() && 7473 SanitizerName != "coverage") 7474 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName; 7475 else if (isGlobalVar(D) && SanitizerName != "address") 7476 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 7477 << AL << ExpectedFunctionOrMethod; 7478 Sanitizers.push_back(SanitizerName); 7479 } 7480 7481 D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(), 7482 Sanitizers.size())); 7483 } 7484 7485 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D, 7486 const ParsedAttr &AL) { 7487 StringRef AttrName = AL.getAttrName()->getName(); 7488 normalizeName(AttrName); 7489 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName) 7490 .Case("no_address_safety_analysis", "address") 7491 .Case("no_sanitize_address", "address") 7492 .Case("no_sanitize_thread", "thread") 7493 .Case("no_sanitize_memory", "memory"); 7494 if (isGlobalVar(D) && SanitizerName != "address") 7495 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 7496 << AL << ExpectedFunction; 7497 7498 // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a 7499 // NoSanitizeAttr object; but we need to calculate the correct spelling list 7500 // index rather than incorrectly assume the index for NoSanitizeSpecificAttr 7501 // has the same spellings as the index for NoSanitizeAttr. We don't have a 7502 // general way to "translate" between the two, so this hack attempts to work 7503 // around the issue with hard-coded indicies. This is critical for calling 7504 // getSpelling() or prettyPrint() on the resulting semantic attribute object 7505 // without failing assertions. 7506 unsigned TranslatedSpellingIndex = 0; 7507 if (AL.isStandardAttributeSyntax()) 7508 TranslatedSpellingIndex = 1; 7509 7510 AttributeCommonInfo Info = AL; 7511 Info.setAttributeSpellingListIndex(TranslatedSpellingIndex); 7512 D->addAttr(::new (S.Context) 7513 NoSanitizeAttr(S.Context, Info, &SanitizerName, 1)); 7514 } 7515 7516 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7517 if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL)) 7518 D->addAttr(Internal); 7519 } 7520 7521 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7522 if (S.LangOpts.OpenCLVersion < 200 && !S.LangOpts.OpenCLCPlusPlusVersion) 7523 S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version) 7524 << AL << "2.0" << 1; 7525 else 7526 S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) 7527 << AL << S.LangOpts.getOpenCLVersionString(); 7528 } 7529 7530 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7531 if (D->isInvalidDecl()) 7532 return; 7533 7534 // Check if there is only one access qualifier. 7535 if (D->hasAttr<OpenCLAccessAttr>()) { 7536 if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() == 7537 AL.getSemanticSpelling()) { 7538 S.Diag(AL.getLoc(), diag::warn_duplicate_declspec) 7539 << AL.getAttrName()->getName() << AL.getRange(); 7540 } else { 7541 S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers) 7542 << D->getSourceRange(); 7543 D->setInvalidDecl(true); 7544 return; 7545 } 7546 } 7547 7548 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that 7549 // an image object can be read and written. OpenCL v2.0 s6.13.6 - A kernel 7550 // cannot read from and write to the same pipe object. Using the read_write 7551 // (or __read_write) qualifier with the pipe qualifier is a compilation error. 7552 // OpenCL v3.0 s6.8 - For OpenCL C 2.0, or with the 7553 // __opencl_c_read_write_images feature, image objects specified as arguments 7554 // to a kernel can additionally be declared to be read-write. 7555 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7556 if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) { 7557 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr(); 7558 if (AL.getAttrName()->getName().find("read_write") != StringRef::npos) { 7559 bool ReadWriteImagesUnsupportedForOCLC = 7560 (S.getLangOpts().OpenCLVersion < 200) || 7561 (S.getLangOpts().OpenCLVersion == 300 && 7562 !S.getOpenCLOptions().isSupported("__opencl_c_read_write_images", 7563 S.getLangOpts())); 7564 if ((!S.getLangOpts().OpenCLCPlusPlus && 7565 ReadWriteImagesUnsupportedForOCLC) || 7566 DeclTy->isPipeType()) { 7567 S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write) 7568 << AL << PDecl->getType() << DeclTy->isImageType(); 7569 D->setInvalidDecl(true); 7570 return; 7571 } 7572 } 7573 } 7574 7575 D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL)); 7576 } 7577 7578 static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7579 // The 'sycl_kernel' attribute applies only to function templates. 7580 const auto *FD = cast<FunctionDecl>(D); 7581 const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate(); 7582 assert(FT && "Function template is expected"); 7583 7584 // Function template must have at least two template parameters. 7585 const TemplateParameterList *TL = FT->getTemplateParameters(); 7586 if (TL->size() < 2) { 7587 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params); 7588 return; 7589 } 7590 7591 // Template parameters must be typenames. 7592 for (unsigned I = 0; I < 2; ++I) { 7593 const NamedDecl *TParam = TL->getParam(I); 7594 if (isa<NonTypeTemplateParmDecl>(TParam)) { 7595 S.Diag(FT->getLocation(), 7596 diag::warn_sycl_kernel_invalid_template_param_type); 7597 return; 7598 } 7599 } 7600 7601 // Function must have at least one argument. 7602 if (getFunctionOrMethodNumParams(D) != 1) { 7603 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_function_params); 7604 return; 7605 } 7606 7607 // Function must return void. 7608 QualType RetTy = getFunctionOrMethodResultType(D); 7609 if (!RetTy->isVoidType()) { 7610 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_return_type); 7611 return; 7612 } 7613 7614 handleSimpleAttribute<SYCLKernelAttr>(S, D, AL); 7615 } 7616 7617 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) { 7618 if (!cast<VarDecl>(D)->hasGlobalStorage()) { 7619 S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var) 7620 << (A.getKind() == ParsedAttr::AT_AlwaysDestroy); 7621 return; 7622 } 7623 7624 if (A.getKind() == ParsedAttr::AT_AlwaysDestroy) 7625 handleSimpleAttribute<AlwaysDestroyAttr>(S, D, A); 7626 else 7627 handleSimpleAttribute<NoDestroyAttr>(S, D, A); 7628 } 7629 7630 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7631 assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic && 7632 "uninitialized is only valid on automatic duration variables"); 7633 D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL)); 7634 } 7635 7636 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD, 7637 bool DiagnoseFailure) { 7638 QualType Ty = VD->getType(); 7639 if (!Ty->isObjCRetainableType()) { 7640 if (DiagnoseFailure) { 7641 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained) 7642 << 0; 7643 } 7644 return false; 7645 } 7646 7647 Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime(); 7648 7649 // Sema::inferObjCARCLifetime must run after processing decl attributes 7650 // (because __block lowers to an attribute), so if the lifetime hasn't been 7651 // explicitly specified, infer it locally now. 7652 if (LifetimeQual == Qualifiers::OCL_None) 7653 LifetimeQual = Ty->getObjCARCImplicitLifetime(); 7654 7655 // The attributes only really makes sense for __strong variables; ignore any 7656 // attempts to annotate a parameter with any other lifetime qualifier. 7657 if (LifetimeQual != Qualifiers::OCL_Strong) { 7658 if (DiagnoseFailure) { 7659 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained) 7660 << 1; 7661 } 7662 return false; 7663 } 7664 7665 // Tampering with the type of a VarDecl here is a bit of a hack, but we need 7666 // to ensure that the variable is 'const' so that we can error on 7667 // modification, which can otherwise over-release. 7668 VD->setType(Ty.withConst()); 7669 VD->setARCPseudoStrong(true); 7670 return true; 7671 } 7672 7673 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D, 7674 const ParsedAttr &AL) { 7675 if (auto *VD = dyn_cast<VarDecl>(D)) { 7676 assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically"); 7677 if (!VD->hasLocalStorage()) { 7678 S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained) 7679 << 0; 7680 return; 7681 } 7682 7683 if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true)) 7684 return; 7685 7686 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL); 7687 return; 7688 } 7689 7690 // If D is a function-like declaration (method, block, or function), then we 7691 // make every parameter psuedo-strong. 7692 unsigned NumParams = 7693 hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0; 7694 for (unsigned I = 0; I != NumParams; ++I) { 7695 auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I)); 7696 QualType Ty = PVD->getType(); 7697 7698 // If a user wrote a parameter with __strong explicitly, then assume they 7699 // want "real" strong semantics for that parameter. This works because if 7700 // the parameter was written with __strong, then the strong qualifier will 7701 // be non-local. 7702 if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() == 7703 Qualifiers::OCL_Strong) 7704 continue; 7705 7706 tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false); 7707 } 7708 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL); 7709 } 7710 7711 static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7712 // Check that the return type is a `typedef int kern_return_t` or a typedef 7713 // around it, because otherwise MIG convention checks make no sense. 7714 // BlockDecl doesn't store a return type, so it's annoying to check, 7715 // so let's skip it for now. 7716 if (!isa<BlockDecl>(D)) { 7717 QualType T = getFunctionOrMethodResultType(D); 7718 bool IsKernReturnT = false; 7719 while (const auto *TT = T->getAs<TypedefType>()) { 7720 IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t"); 7721 T = TT->desugar(); 7722 } 7723 if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) { 7724 S.Diag(D->getBeginLoc(), 7725 diag::warn_mig_server_routine_does_not_return_kern_return_t); 7726 return; 7727 } 7728 } 7729 7730 handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL); 7731 } 7732 7733 static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7734 // Warn if the return type is not a pointer or reference type. 7735 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 7736 QualType RetTy = FD->getReturnType(); 7737 if (!RetTy->isPointerType() && !RetTy->isReferenceType()) { 7738 S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer) 7739 << AL.getRange() << RetTy; 7740 return; 7741 } 7742 } 7743 7744 handleSimpleAttribute<MSAllocatorAttr>(S, D, AL); 7745 } 7746 7747 static void handleAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7748 if (AL.isUsedAsTypeAttr()) 7749 return; 7750 // Warn if the parameter is definitely not an output parameter. 7751 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) { 7752 if (PVD->getType()->isIntegerType()) { 7753 S.Diag(AL.getLoc(), diag::err_attribute_output_parameter) 7754 << AL.getRange(); 7755 return; 7756 } 7757 } 7758 StringRef Argument; 7759 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument)) 7760 return; 7761 D->addAttr(AcquireHandleAttr::Create(S.Context, Argument, AL)); 7762 } 7763 7764 template<typename Attr> 7765 static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7766 StringRef Argument; 7767 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument)) 7768 return; 7769 D->addAttr(Attr::Create(S.Context, Argument, AL)); 7770 } 7771 7772 static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7773 // The guard attribute takes a single identifier argument. 7774 7775 if (!AL.isArgIdent(0)) { 7776 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 7777 << AL << AANT_ArgumentIdentifier; 7778 return; 7779 } 7780 7781 CFGuardAttr::GuardArg Arg; 7782 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 7783 if (!CFGuardAttr::ConvertStrToGuardArg(II->getName(), Arg)) { 7784 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; 7785 return; 7786 } 7787 7788 D->addAttr(::new (S.Context) CFGuardAttr(S.Context, AL, Arg)); 7789 } 7790 7791 7792 template <typename AttrTy> 7793 static const AttrTy *findEnforceTCBAttrByName(Decl *D, StringRef Name) { 7794 auto Attrs = D->specific_attrs<AttrTy>(); 7795 auto I = llvm::find_if(Attrs, 7796 [Name](const AttrTy *A) { 7797 return A->getTCBName() == Name; 7798 }); 7799 return I == Attrs.end() ? nullptr : *I; 7800 } 7801 7802 template <typename AttrTy, typename ConflictingAttrTy> 7803 static void handleEnforceTCBAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7804 StringRef Argument; 7805 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument)) 7806 return; 7807 7808 // A function cannot be have both regular and leaf membership in the same TCB. 7809 if (const ConflictingAttrTy *ConflictingAttr = 7810 findEnforceTCBAttrByName<ConflictingAttrTy>(D, Argument)) { 7811 // We could attach a note to the other attribute but in this case 7812 // there's no need given how the two are very close to each other. 7813 S.Diag(AL.getLoc(), diag::err_tcb_conflicting_attributes) 7814 << AL.getAttrName()->getName() << ConflictingAttr->getAttrName()->getName() 7815 << Argument; 7816 7817 // Error recovery: drop the non-leaf attribute so that to suppress 7818 // all future warnings caused by erroneous attributes. The leaf attribute 7819 // needs to be kept because it can only suppresses warnings, not cause them. 7820 D->dropAttr<EnforceTCBAttr>(); 7821 return; 7822 } 7823 7824 D->addAttr(AttrTy::Create(S.Context, Argument, AL)); 7825 } 7826 7827 template <typename AttrTy, typename ConflictingAttrTy> 7828 static AttrTy *mergeEnforceTCBAttrImpl(Sema &S, Decl *D, const AttrTy &AL) { 7829 // Check if the new redeclaration has different leaf-ness in the same TCB. 7830 StringRef TCBName = AL.getTCBName(); 7831 if (const ConflictingAttrTy *ConflictingAttr = 7832 findEnforceTCBAttrByName<ConflictingAttrTy>(D, TCBName)) { 7833 S.Diag(ConflictingAttr->getLoc(), diag::err_tcb_conflicting_attributes) 7834 << ConflictingAttr->getAttrName()->getName() 7835 << AL.getAttrName()->getName() << TCBName; 7836 7837 // Add a note so that the user could easily find the conflicting attribute. 7838 S.Diag(AL.getLoc(), diag::note_conflicting_attribute); 7839 7840 // More error recovery. 7841 D->dropAttr<EnforceTCBAttr>(); 7842 return nullptr; 7843 } 7844 7845 ASTContext &Context = S.getASTContext(); 7846 return ::new(Context) AttrTy(Context, AL, AL.getTCBName()); 7847 } 7848 7849 EnforceTCBAttr *Sema::mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL) { 7850 return mergeEnforceTCBAttrImpl<EnforceTCBAttr, EnforceTCBLeafAttr>( 7851 *this, D, AL); 7852 } 7853 7854 EnforceTCBLeafAttr *Sema::mergeEnforceTCBLeafAttr( 7855 Decl *D, const EnforceTCBLeafAttr &AL) { 7856 return mergeEnforceTCBAttrImpl<EnforceTCBLeafAttr, EnforceTCBAttr>( 7857 *this, D, AL); 7858 } 7859 7860 //===----------------------------------------------------------------------===// 7861 // Top Level Sema Entry Points 7862 //===----------------------------------------------------------------------===// 7863 7864 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if 7865 /// the attribute applies to decls. If the attribute is a type attribute, just 7866 /// silently ignore it if a GNU attribute. 7867 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, 7868 const ParsedAttr &AL, 7869 bool IncludeCXX11Attributes) { 7870 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 7871 return; 7872 7873 // Ignore C++11 attributes on declarator chunks: they appertain to the type 7874 // instead. 7875 if (AL.isCXX11Attribute() && !IncludeCXX11Attributes) 7876 return; 7877 7878 // Unknown attributes are automatically warned on. Target-specific attributes 7879 // which do not apply to the current target architecture are treated as 7880 // though they were unknown attributes. 7881 if (AL.getKind() == ParsedAttr::UnknownAttribute || 7882 !AL.existsInTarget(S.Context.getTargetInfo())) { 7883 S.Diag(AL.getLoc(), 7884 AL.isDeclspecAttribute() 7885 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored 7886 : (unsigned)diag::warn_unknown_attribute_ignored) 7887 << AL << AL.getRange(); 7888 return; 7889 } 7890 7891 if (S.checkCommonAttributeFeatures(D, AL)) 7892 return; 7893 7894 switch (AL.getKind()) { 7895 default: 7896 if (AL.getInfo().handleDeclAttribute(S, D, AL) != ParsedAttrInfo::NotHandled) 7897 break; 7898 if (!AL.isStmtAttr()) { 7899 // Type attributes are handled elsewhere; silently move on. 7900 assert(AL.isTypeAttr() && "Non-type attribute not handled"); 7901 break; 7902 } 7903 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a 7904 // statement attribute is not written on a declaration, but this code is 7905 // needed for attributes in Attr.td that do not list any subjects. 7906 S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl) 7907 << AL << D->getLocation(); 7908 break; 7909 case ParsedAttr::AT_Interrupt: 7910 handleInterruptAttr(S, D, AL); 7911 break; 7912 case ParsedAttr::AT_X86ForceAlignArgPointer: 7913 handleX86ForceAlignArgPointerAttr(S, D, AL); 7914 break; 7915 case ParsedAttr::AT_DLLExport: 7916 case ParsedAttr::AT_DLLImport: 7917 handleDLLAttr(S, D, AL); 7918 break; 7919 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize: 7920 handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL); 7921 break; 7922 case ParsedAttr::AT_AMDGPUWavesPerEU: 7923 handleAMDGPUWavesPerEUAttr(S, D, AL); 7924 break; 7925 case ParsedAttr::AT_AMDGPUNumSGPR: 7926 handleAMDGPUNumSGPRAttr(S, D, AL); 7927 break; 7928 case ParsedAttr::AT_AMDGPUNumVGPR: 7929 handleAMDGPUNumVGPRAttr(S, D, AL); 7930 break; 7931 case ParsedAttr::AT_AVRSignal: 7932 handleAVRSignalAttr(S, D, AL); 7933 break; 7934 case ParsedAttr::AT_BPFPreserveAccessIndex: 7935 handleBPFPreserveAccessIndexAttr(S, D, AL); 7936 break; 7937 case ParsedAttr::AT_BTFTag: 7938 handleBTFTagAttr(S, D, AL); 7939 break; 7940 case ParsedAttr::AT_WebAssemblyExportName: 7941 handleWebAssemblyExportNameAttr(S, D, AL); 7942 break; 7943 case ParsedAttr::AT_WebAssemblyImportModule: 7944 handleWebAssemblyImportModuleAttr(S, D, AL); 7945 break; 7946 case ParsedAttr::AT_WebAssemblyImportName: 7947 handleWebAssemblyImportNameAttr(S, D, AL); 7948 break; 7949 case ParsedAttr::AT_IBOutlet: 7950 handleIBOutlet(S, D, AL); 7951 break; 7952 case ParsedAttr::AT_IBOutletCollection: 7953 handleIBOutletCollection(S, D, AL); 7954 break; 7955 case ParsedAttr::AT_IFunc: 7956 handleIFuncAttr(S, D, AL); 7957 break; 7958 case ParsedAttr::AT_Alias: 7959 handleAliasAttr(S, D, AL); 7960 break; 7961 case ParsedAttr::AT_Aligned: 7962 handleAlignedAttr(S, D, AL); 7963 break; 7964 case ParsedAttr::AT_AlignValue: 7965 handleAlignValueAttr(S, D, AL); 7966 break; 7967 case ParsedAttr::AT_AllocSize: 7968 handleAllocSizeAttr(S, D, AL); 7969 break; 7970 case ParsedAttr::AT_AlwaysInline: 7971 handleAlwaysInlineAttr(S, D, AL); 7972 break; 7973 case ParsedAttr::AT_AnalyzerNoReturn: 7974 handleAnalyzerNoReturnAttr(S, D, AL); 7975 break; 7976 case ParsedAttr::AT_TLSModel: 7977 handleTLSModelAttr(S, D, AL); 7978 break; 7979 case ParsedAttr::AT_Annotate: 7980 handleAnnotateAttr(S, D, AL); 7981 break; 7982 case ParsedAttr::AT_Availability: 7983 handleAvailabilityAttr(S, D, AL); 7984 break; 7985 case ParsedAttr::AT_CarriesDependency: 7986 handleDependencyAttr(S, scope, D, AL); 7987 break; 7988 case ParsedAttr::AT_CPUDispatch: 7989 case ParsedAttr::AT_CPUSpecific: 7990 handleCPUSpecificAttr(S, D, AL); 7991 break; 7992 case ParsedAttr::AT_Common: 7993 handleCommonAttr(S, D, AL); 7994 break; 7995 case ParsedAttr::AT_CUDAConstant: 7996 handleConstantAttr(S, D, AL); 7997 break; 7998 case ParsedAttr::AT_PassObjectSize: 7999 handlePassObjectSizeAttr(S, D, AL); 8000 break; 8001 case ParsedAttr::AT_Constructor: 8002 handleConstructorAttr(S, D, AL); 8003 break; 8004 case ParsedAttr::AT_Deprecated: 8005 handleDeprecatedAttr(S, D, AL); 8006 break; 8007 case ParsedAttr::AT_Destructor: 8008 handleDestructorAttr(S, D, AL); 8009 break; 8010 case ParsedAttr::AT_EnableIf: 8011 handleEnableIfAttr(S, D, AL); 8012 break; 8013 case ParsedAttr::AT_Error: 8014 handleErrorAttr(S, D, AL); 8015 break; 8016 case ParsedAttr::AT_DiagnoseIf: 8017 handleDiagnoseIfAttr(S, D, AL); 8018 break; 8019 case ParsedAttr::AT_NoBuiltin: 8020 handleNoBuiltinAttr(S, D, AL); 8021 break; 8022 case ParsedAttr::AT_ExtVectorType: 8023 handleExtVectorTypeAttr(S, D, AL); 8024 break; 8025 case ParsedAttr::AT_ExternalSourceSymbol: 8026 handleExternalSourceSymbolAttr(S, D, AL); 8027 break; 8028 case ParsedAttr::AT_MinSize: 8029 handleMinSizeAttr(S, D, AL); 8030 break; 8031 case ParsedAttr::AT_OptimizeNone: 8032 handleOptimizeNoneAttr(S, D, AL); 8033 break; 8034 case ParsedAttr::AT_EnumExtensibility: 8035 handleEnumExtensibilityAttr(S, D, AL); 8036 break; 8037 case ParsedAttr::AT_SYCLKernel: 8038 handleSYCLKernelAttr(S, D, AL); 8039 break; 8040 case ParsedAttr::AT_Format: 8041 handleFormatAttr(S, D, AL); 8042 break; 8043 case ParsedAttr::AT_FormatArg: 8044 handleFormatArgAttr(S, D, AL); 8045 break; 8046 case ParsedAttr::AT_Callback: 8047 handleCallbackAttr(S, D, AL); 8048 break; 8049 case ParsedAttr::AT_CalledOnce: 8050 handleCalledOnceAttr(S, D, AL); 8051 break; 8052 case ParsedAttr::AT_CUDAGlobal: 8053 handleGlobalAttr(S, D, AL); 8054 break; 8055 case ParsedAttr::AT_CUDADevice: 8056 handleDeviceAttr(S, D, AL); 8057 break; 8058 case ParsedAttr::AT_HIPManaged: 8059 handleManagedAttr(S, D, AL); 8060 break; 8061 case ParsedAttr::AT_GNUInline: 8062 handleGNUInlineAttr(S, D, AL); 8063 break; 8064 case ParsedAttr::AT_CUDALaunchBounds: 8065 handleLaunchBoundsAttr(S, D, AL); 8066 break; 8067 case ParsedAttr::AT_Restrict: 8068 handleRestrictAttr(S, D, AL); 8069 break; 8070 case ParsedAttr::AT_Mode: 8071 handleModeAttr(S, D, AL); 8072 break; 8073 case ParsedAttr::AT_NonNull: 8074 if (auto *PVD = dyn_cast<ParmVarDecl>(D)) 8075 handleNonNullAttrParameter(S, PVD, AL); 8076 else 8077 handleNonNullAttr(S, D, AL); 8078 break; 8079 case ParsedAttr::AT_ReturnsNonNull: 8080 handleReturnsNonNullAttr(S, D, AL); 8081 break; 8082 case ParsedAttr::AT_NoEscape: 8083 handleNoEscapeAttr(S, D, AL); 8084 break; 8085 case ParsedAttr::AT_AssumeAligned: 8086 handleAssumeAlignedAttr(S, D, AL); 8087 break; 8088 case ParsedAttr::AT_AllocAlign: 8089 handleAllocAlignAttr(S, D, AL); 8090 break; 8091 case ParsedAttr::AT_Ownership: 8092 handleOwnershipAttr(S, D, AL); 8093 break; 8094 case ParsedAttr::AT_Naked: 8095 handleNakedAttr(S, D, AL); 8096 break; 8097 case ParsedAttr::AT_NoReturn: 8098 handleNoReturnAttr(S, D, AL); 8099 break; 8100 case ParsedAttr::AT_AnyX86NoCfCheck: 8101 handleNoCfCheckAttr(S, D, AL); 8102 break; 8103 case ParsedAttr::AT_NoThrow: 8104 if (!AL.isUsedAsTypeAttr()) 8105 handleSimpleAttribute<NoThrowAttr>(S, D, AL); 8106 break; 8107 case ParsedAttr::AT_CUDAShared: 8108 handleSharedAttr(S, D, AL); 8109 break; 8110 case ParsedAttr::AT_VecReturn: 8111 handleVecReturnAttr(S, D, AL); 8112 break; 8113 case ParsedAttr::AT_ObjCOwnership: 8114 handleObjCOwnershipAttr(S, D, AL); 8115 break; 8116 case ParsedAttr::AT_ObjCPreciseLifetime: 8117 handleObjCPreciseLifetimeAttr(S, D, AL); 8118 break; 8119 case ParsedAttr::AT_ObjCReturnsInnerPointer: 8120 handleObjCReturnsInnerPointerAttr(S, D, AL); 8121 break; 8122 case ParsedAttr::AT_ObjCRequiresSuper: 8123 handleObjCRequiresSuperAttr(S, D, AL); 8124 break; 8125 case ParsedAttr::AT_ObjCBridge: 8126 handleObjCBridgeAttr(S, D, AL); 8127 break; 8128 case ParsedAttr::AT_ObjCBridgeMutable: 8129 handleObjCBridgeMutableAttr(S, D, AL); 8130 break; 8131 case ParsedAttr::AT_ObjCBridgeRelated: 8132 handleObjCBridgeRelatedAttr(S, D, AL); 8133 break; 8134 case ParsedAttr::AT_ObjCDesignatedInitializer: 8135 handleObjCDesignatedInitializer(S, D, AL); 8136 break; 8137 case ParsedAttr::AT_ObjCRuntimeName: 8138 handleObjCRuntimeName(S, D, AL); 8139 break; 8140 case ParsedAttr::AT_ObjCBoxable: 8141 handleObjCBoxable(S, D, AL); 8142 break; 8143 case ParsedAttr::AT_NSErrorDomain: 8144 handleNSErrorDomain(S, D, AL); 8145 break; 8146 case ParsedAttr::AT_CFConsumed: 8147 case ParsedAttr::AT_NSConsumed: 8148 case ParsedAttr::AT_OSConsumed: 8149 S.AddXConsumedAttr(D, AL, parsedAttrToRetainOwnershipKind(AL), 8150 /*IsTemplateInstantiation=*/false); 8151 break; 8152 case ParsedAttr::AT_OSReturnsRetainedOnZero: 8153 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>( 8154 S, D, AL, isValidOSObjectOutParameter(D), 8155 diag::warn_ns_attribute_wrong_parameter_type, 8156 /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange()); 8157 break; 8158 case ParsedAttr::AT_OSReturnsRetainedOnNonZero: 8159 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>( 8160 S, D, AL, isValidOSObjectOutParameter(D), 8161 diag::warn_ns_attribute_wrong_parameter_type, 8162 /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange()); 8163 break; 8164 case ParsedAttr::AT_NSReturnsAutoreleased: 8165 case ParsedAttr::AT_NSReturnsNotRetained: 8166 case ParsedAttr::AT_NSReturnsRetained: 8167 case ParsedAttr::AT_CFReturnsNotRetained: 8168 case ParsedAttr::AT_CFReturnsRetained: 8169 case ParsedAttr::AT_OSReturnsNotRetained: 8170 case ParsedAttr::AT_OSReturnsRetained: 8171 handleXReturnsXRetainedAttr(S, D, AL); 8172 break; 8173 case ParsedAttr::AT_WorkGroupSizeHint: 8174 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL); 8175 break; 8176 case ParsedAttr::AT_ReqdWorkGroupSize: 8177 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL); 8178 break; 8179 case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize: 8180 handleSubGroupSize(S, D, AL); 8181 break; 8182 case ParsedAttr::AT_VecTypeHint: 8183 handleVecTypeHint(S, D, AL); 8184 break; 8185 case ParsedAttr::AT_InitPriority: 8186 handleInitPriorityAttr(S, D, AL); 8187 break; 8188 case ParsedAttr::AT_Packed: 8189 handlePackedAttr(S, D, AL); 8190 break; 8191 case ParsedAttr::AT_PreferredName: 8192 handlePreferredName(S, D, AL); 8193 break; 8194 case ParsedAttr::AT_Section: 8195 handleSectionAttr(S, D, AL); 8196 break; 8197 case ParsedAttr::AT_CodeSeg: 8198 handleCodeSegAttr(S, D, AL); 8199 break; 8200 case ParsedAttr::AT_Target: 8201 handleTargetAttr(S, D, AL); 8202 break; 8203 case ParsedAttr::AT_MinVectorWidth: 8204 handleMinVectorWidthAttr(S, D, AL); 8205 break; 8206 case ParsedAttr::AT_Unavailable: 8207 handleAttrWithMessage<UnavailableAttr>(S, D, AL); 8208 break; 8209 case ParsedAttr::AT_Assumption: 8210 handleAssumumptionAttr(S, D, AL); 8211 break; 8212 case ParsedAttr::AT_ObjCDirect: 8213 handleObjCDirectAttr(S, D, AL); 8214 break; 8215 case ParsedAttr::AT_ObjCDirectMembers: 8216 handleObjCDirectMembersAttr(S, D, AL); 8217 handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL); 8218 break; 8219 case ParsedAttr::AT_ObjCExplicitProtocolImpl: 8220 handleObjCSuppresProtocolAttr(S, D, AL); 8221 break; 8222 case ParsedAttr::AT_Unused: 8223 handleUnusedAttr(S, D, AL); 8224 break; 8225 case ParsedAttr::AT_Visibility: 8226 handleVisibilityAttr(S, D, AL, false); 8227 break; 8228 case ParsedAttr::AT_TypeVisibility: 8229 handleVisibilityAttr(S, D, AL, true); 8230 break; 8231 case ParsedAttr::AT_WarnUnusedResult: 8232 handleWarnUnusedResult(S, D, AL); 8233 break; 8234 case ParsedAttr::AT_WeakRef: 8235 handleWeakRefAttr(S, D, AL); 8236 break; 8237 case ParsedAttr::AT_WeakImport: 8238 handleWeakImportAttr(S, D, AL); 8239 break; 8240 case ParsedAttr::AT_TransparentUnion: 8241 handleTransparentUnionAttr(S, D, AL); 8242 break; 8243 case ParsedAttr::AT_ObjCMethodFamily: 8244 handleObjCMethodFamilyAttr(S, D, AL); 8245 break; 8246 case ParsedAttr::AT_ObjCNSObject: 8247 handleObjCNSObject(S, D, AL); 8248 break; 8249 case ParsedAttr::AT_ObjCIndependentClass: 8250 handleObjCIndependentClass(S, D, AL); 8251 break; 8252 case ParsedAttr::AT_Blocks: 8253 handleBlocksAttr(S, D, AL); 8254 break; 8255 case ParsedAttr::AT_Sentinel: 8256 handleSentinelAttr(S, D, AL); 8257 break; 8258 case ParsedAttr::AT_Cleanup: 8259 handleCleanupAttr(S, D, AL); 8260 break; 8261 case ParsedAttr::AT_NoDebug: 8262 handleNoDebugAttr(S, D, AL); 8263 break; 8264 case ParsedAttr::AT_CmseNSEntry: 8265 handleCmseNSEntryAttr(S, D, AL); 8266 break; 8267 case ParsedAttr::AT_StdCall: 8268 case ParsedAttr::AT_CDecl: 8269 case ParsedAttr::AT_FastCall: 8270 case ParsedAttr::AT_ThisCall: 8271 case ParsedAttr::AT_Pascal: 8272 case ParsedAttr::AT_RegCall: 8273 case ParsedAttr::AT_SwiftCall: 8274 case ParsedAttr::AT_SwiftAsyncCall: 8275 case ParsedAttr::AT_VectorCall: 8276 case ParsedAttr::AT_MSABI: 8277 case ParsedAttr::AT_SysVABI: 8278 case ParsedAttr::AT_Pcs: 8279 case ParsedAttr::AT_IntelOclBicc: 8280 case ParsedAttr::AT_PreserveMost: 8281 case ParsedAttr::AT_PreserveAll: 8282 case ParsedAttr::AT_AArch64VectorPcs: 8283 handleCallConvAttr(S, D, AL); 8284 break; 8285 case ParsedAttr::AT_Suppress: 8286 handleSuppressAttr(S, D, AL); 8287 break; 8288 case ParsedAttr::AT_Owner: 8289 case ParsedAttr::AT_Pointer: 8290 handleLifetimeCategoryAttr(S, D, AL); 8291 break; 8292 case ParsedAttr::AT_OpenCLAccess: 8293 handleOpenCLAccessAttr(S, D, AL); 8294 break; 8295 case ParsedAttr::AT_OpenCLNoSVM: 8296 handleOpenCLNoSVMAttr(S, D, AL); 8297 break; 8298 case ParsedAttr::AT_SwiftContext: 8299 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftContext); 8300 break; 8301 case ParsedAttr::AT_SwiftAsyncContext: 8302 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftAsyncContext); 8303 break; 8304 case ParsedAttr::AT_SwiftErrorResult: 8305 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftErrorResult); 8306 break; 8307 case ParsedAttr::AT_SwiftIndirectResult: 8308 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftIndirectResult); 8309 break; 8310 case ParsedAttr::AT_InternalLinkage: 8311 handleInternalLinkageAttr(S, D, AL); 8312 break; 8313 8314 // Microsoft attributes: 8315 case ParsedAttr::AT_LayoutVersion: 8316 handleLayoutVersion(S, D, AL); 8317 break; 8318 case ParsedAttr::AT_Uuid: 8319 handleUuidAttr(S, D, AL); 8320 break; 8321 case ParsedAttr::AT_MSInheritance: 8322 handleMSInheritanceAttr(S, D, AL); 8323 break; 8324 case ParsedAttr::AT_Thread: 8325 handleDeclspecThreadAttr(S, D, AL); 8326 break; 8327 8328 case ParsedAttr::AT_AbiTag: 8329 handleAbiTagAttr(S, D, AL); 8330 break; 8331 case ParsedAttr::AT_CFGuard: 8332 handleCFGuardAttr(S, D, AL); 8333 break; 8334 8335 // Thread safety attributes: 8336 case ParsedAttr::AT_AssertExclusiveLock: 8337 handleAssertExclusiveLockAttr(S, D, AL); 8338 break; 8339 case ParsedAttr::AT_AssertSharedLock: 8340 handleAssertSharedLockAttr(S, D, AL); 8341 break; 8342 case ParsedAttr::AT_PtGuardedVar: 8343 handlePtGuardedVarAttr(S, D, AL); 8344 break; 8345 case ParsedAttr::AT_NoSanitize: 8346 handleNoSanitizeAttr(S, D, AL); 8347 break; 8348 case ParsedAttr::AT_NoSanitizeSpecific: 8349 handleNoSanitizeSpecificAttr(S, D, AL); 8350 break; 8351 case ParsedAttr::AT_GuardedBy: 8352 handleGuardedByAttr(S, D, AL); 8353 break; 8354 case ParsedAttr::AT_PtGuardedBy: 8355 handlePtGuardedByAttr(S, D, AL); 8356 break; 8357 case ParsedAttr::AT_ExclusiveTrylockFunction: 8358 handleExclusiveTrylockFunctionAttr(S, D, AL); 8359 break; 8360 case ParsedAttr::AT_LockReturned: 8361 handleLockReturnedAttr(S, D, AL); 8362 break; 8363 case ParsedAttr::AT_LocksExcluded: 8364 handleLocksExcludedAttr(S, D, AL); 8365 break; 8366 case ParsedAttr::AT_SharedTrylockFunction: 8367 handleSharedTrylockFunctionAttr(S, D, AL); 8368 break; 8369 case ParsedAttr::AT_AcquiredBefore: 8370 handleAcquiredBeforeAttr(S, D, AL); 8371 break; 8372 case ParsedAttr::AT_AcquiredAfter: 8373 handleAcquiredAfterAttr(S, D, AL); 8374 break; 8375 8376 // Capability analysis attributes. 8377 case ParsedAttr::AT_Capability: 8378 case ParsedAttr::AT_Lockable: 8379 handleCapabilityAttr(S, D, AL); 8380 break; 8381 case ParsedAttr::AT_RequiresCapability: 8382 handleRequiresCapabilityAttr(S, D, AL); 8383 break; 8384 8385 case ParsedAttr::AT_AssertCapability: 8386 handleAssertCapabilityAttr(S, D, AL); 8387 break; 8388 case ParsedAttr::AT_AcquireCapability: 8389 handleAcquireCapabilityAttr(S, D, AL); 8390 break; 8391 case ParsedAttr::AT_ReleaseCapability: 8392 handleReleaseCapabilityAttr(S, D, AL); 8393 break; 8394 case ParsedAttr::AT_TryAcquireCapability: 8395 handleTryAcquireCapabilityAttr(S, D, AL); 8396 break; 8397 8398 // Consumed analysis attributes. 8399 case ParsedAttr::AT_Consumable: 8400 handleConsumableAttr(S, D, AL); 8401 break; 8402 case ParsedAttr::AT_CallableWhen: 8403 handleCallableWhenAttr(S, D, AL); 8404 break; 8405 case ParsedAttr::AT_ParamTypestate: 8406 handleParamTypestateAttr(S, D, AL); 8407 break; 8408 case ParsedAttr::AT_ReturnTypestate: 8409 handleReturnTypestateAttr(S, D, AL); 8410 break; 8411 case ParsedAttr::AT_SetTypestate: 8412 handleSetTypestateAttr(S, D, AL); 8413 break; 8414 case ParsedAttr::AT_TestTypestate: 8415 handleTestTypestateAttr(S, D, AL); 8416 break; 8417 8418 // Type safety attributes. 8419 case ParsedAttr::AT_ArgumentWithTypeTag: 8420 handleArgumentWithTypeTagAttr(S, D, AL); 8421 break; 8422 case ParsedAttr::AT_TypeTagForDatatype: 8423 handleTypeTagForDatatypeAttr(S, D, AL); 8424 break; 8425 8426 // Swift attributes. 8427 case ParsedAttr::AT_SwiftAsyncName: 8428 handleSwiftAsyncName(S, D, AL); 8429 break; 8430 case ParsedAttr::AT_SwiftAttr: 8431 handleSwiftAttrAttr(S, D, AL); 8432 break; 8433 case ParsedAttr::AT_SwiftBridge: 8434 handleSwiftBridge(S, D, AL); 8435 break; 8436 case ParsedAttr::AT_SwiftError: 8437 handleSwiftError(S, D, AL); 8438 break; 8439 case ParsedAttr::AT_SwiftName: 8440 handleSwiftName(S, D, AL); 8441 break; 8442 case ParsedAttr::AT_SwiftNewType: 8443 handleSwiftNewType(S, D, AL); 8444 break; 8445 case ParsedAttr::AT_SwiftAsync: 8446 handleSwiftAsyncAttr(S, D, AL); 8447 break; 8448 case ParsedAttr::AT_SwiftAsyncError: 8449 handleSwiftAsyncError(S, D, AL); 8450 break; 8451 8452 // XRay attributes. 8453 case ParsedAttr::AT_XRayLogArgs: 8454 handleXRayLogArgsAttr(S, D, AL); 8455 break; 8456 8457 case ParsedAttr::AT_PatchableFunctionEntry: 8458 handlePatchableFunctionEntryAttr(S, D, AL); 8459 break; 8460 8461 case ParsedAttr::AT_AlwaysDestroy: 8462 case ParsedAttr::AT_NoDestroy: 8463 handleDestroyAttr(S, D, AL); 8464 break; 8465 8466 case ParsedAttr::AT_Uninitialized: 8467 handleUninitializedAttr(S, D, AL); 8468 break; 8469 8470 case ParsedAttr::AT_ObjCExternallyRetained: 8471 handleObjCExternallyRetainedAttr(S, D, AL); 8472 break; 8473 8474 case ParsedAttr::AT_MIGServerRoutine: 8475 handleMIGServerRoutineAttr(S, D, AL); 8476 break; 8477 8478 case ParsedAttr::AT_MSAllocator: 8479 handleMSAllocatorAttr(S, D, AL); 8480 break; 8481 8482 case ParsedAttr::AT_ArmBuiltinAlias: 8483 handleArmBuiltinAliasAttr(S, D, AL); 8484 break; 8485 8486 case ParsedAttr::AT_AcquireHandle: 8487 handleAcquireHandleAttr(S, D, AL); 8488 break; 8489 8490 case ParsedAttr::AT_ReleaseHandle: 8491 handleHandleAttr<ReleaseHandleAttr>(S, D, AL); 8492 break; 8493 8494 case ParsedAttr::AT_UseHandle: 8495 handleHandleAttr<UseHandleAttr>(S, D, AL); 8496 break; 8497 8498 case ParsedAttr::AT_EnforceTCB: 8499 handleEnforceTCBAttr<EnforceTCBAttr, EnforceTCBLeafAttr>(S, D, AL); 8500 break; 8501 8502 case ParsedAttr::AT_EnforceTCBLeaf: 8503 handleEnforceTCBAttr<EnforceTCBLeafAttr, EnforceTCBAttr>(S, D, AL); 8504 break; 8505 8506 case ParsedAttr::AT_BuiltinAlias: 8507 handleBuiltinAliasAttr(S, D, AL); 8508 break; 8509 8510 case ParsedAttr::AT_UsingIfExists: 8511 handleSimpleAttribute<UsingIfExistsAttr>(S, D, AL); 8512 break; 8513 } 8514 } 8515 8516 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified 8517 /// attribute list to the specified decl, ignoring any type attributes. 8518 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, 8519 const ParsedAttributesView &AttrList, 8520 bool IncludeCXX11Attributes) { 8521 if (AttrList.empty()) 8522 return; 8523 8524 for (const ParsedAttr &AL : AttrList) 8525 ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes); 8526 8527 // FIXME: We should be able to handle these cases in TableGen. 8528 // GCC accepts 8529 // static int a9 __attribute__((weakref)); 8530 // but that looks really pointless. We reject it. 8531 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) { 8532 Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias) 8533 << cast<NamedDecl>(D); 8534 D->dropAttr<WeakRefAttr>(); 8535 return; 8536 } 8537 8538 // FIXME: We should be able to handle this in TableGen as well. It would be 8539 // good to have a way to specify "these attributes must appear as a group", 8540 // for these. Additionally, it would be good to have a way to specify "these 8541 // attribute must never appear as a group" for attributes like cold and hot. 8542 if (!D->hasAttr<OpenCLKernelAttr>()) { 8543 // These attributes cannot be applied to a non-kernel function. 8544 if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) { 8545 // FIXME: This emits a different error message than 8546 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction. 8547 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 8548 D->setInvalidDecl(); 8549 } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) { 8550 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 8551 D->setInvalidDecl(); 8552 } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) { 8553 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 8554 D->setInvalidDecl(); 8555 } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) { 8556 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 8557 D->setInvalidDecl(); 8558 } else if (!D->hasAttr<CUDAGlobalAttr>()) { 8559 if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) { 8560 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 8561 << A << ExpectedKernelFunction; 8562 D->setInvalidDecl(); 8563 } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) { 8564 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 8565 << A << ExpectedKernelFunction; 8566 D->setInvalidDecl(); 8567 } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) { 8568 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 8569 << A << ExpectedKernelFunction; 8570 D->setInvalidDecl(); 8571 } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) { 8572 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 8573 << A << ExpectedKernelFunction; 8574 D->setInvalidDecl(); 8575 } 8576 } 8577 } 8578 8579 // Do this check after processing D's attributes because the attribute 8580 // objc_method_family can change whether the given method is in the init 8581 // family, and it can be applied after objc_designated_initializer. This is a 8582 // bit of a hack, but we need it to be compatible with versions of clang that 8583 // processed the attribute list in the wrong order. 8584 if (D->hasAttr<ObjCDesignatedInitializerAttr>() && 8585 cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) { 8586 Diag(D->getLocation(), diag::err_designated_init_attr_non_init); 8587 D->dropAttr<ObjCDesignatedInitializerAttr>(); 8588 } 8589 } 8590 8591 // Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr 8592 // attribute. 8593 void Sema::ProcessDeclAttributeDelayed(Decl *D, 8594 const ParsedAttributesView &AttrList) { 8595 for (const ParsedAttr &AL : AttrList) 8596 if (AL.getKind() == ParsedAttr::AT_TransparentUnion) { 8597 handleTransparentUnionAttr(*this, D, AL); 8598 break; 8599 } 8600 8601 // For BPFPreserveAccessIndexAttr, we want to populate the attributes 8602 // to fields and inner records as well. 8603 if (D && D->hasAttr<BPFPreserveAccessIndexAttr>()) 8604 handleBPFPreserveAIRecord(*this, cast<RecordDecl>(D)); 8605 } 8606 8607 // Annotation attributes are the only attributes allowed after an access 8608 // specifier. 8609 bool Sema::ProcessAccessDeclAttributeList( 8610 AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) { 8611 for (const ParsedAttr &AL : AttrList) { 8612 if (AL.getKind() == ParsedAttr::AT_Annotate) { 8613 ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute()); 8614 } else { 8615 Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec); 8616 return true; 8617 } 8618 } 8619 return false; 8620 } 8621 8622 /// checkUnusedDeclAttributes - Check a list of attributes to see if it 8623 /// contains any decl attributes that we should warn about. 8624 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) { 8625 for (const ParsedAttr &AL : A) { 8626 // Only warn if the attribute is an unignored, non-type attribute. 8627 if (AL.isUsedAsTypeAttr() || AL.isInvalid()) 8628 continue; 8629 if (AL.getKind() == ParsedAttr::IgnoredAttribute) 8630 continue; 8631 8632 if (AL.getKind() == ParsedAttr::UnknownAttribute) { 8633 S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) 8634 << AL << AL.getRange(); 8635 } else { 8636 S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL 8637 << AL.getRange(); 8638 } 8639 } 8640 } 8641 8642 /// checkUnusedDeclAttributes - Given a declarator which is not being 8643 /// used to build a declaration, complain about any decl attributes 8644 /// which might be lying around on it. 8645 void Sema::checkUnusedDeclAttributes(Declarator &D) { 8646 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes()); 8647 ::checkUnusedDeclAttributes(*this, D.getAttributes()); 8648 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) 8649 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs()); 8650 } 8651 8652 /// DeclClonePragmaWeak - clone existing decl (maybe definition), 8653 /// \#pragma weak needs a non-definition decl and source may not have one. 8654 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 8655 SourceLocation Loc) { 8656 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND)); 8657 NamedDecl *NewD = nullptr; 8658 if (auto *FD = dyn_cast<FunctionDecl>(ND)) { 8659 FunctionDecl *NewFD; 8660 // FIXME: Missing call to CheckFunctionDeclaration(). 8661 // FIXME: Mangling? 8662 // FIXME: Is the qualifier info correct? 8663 // FIXME: Is the DeclContext correct? 8664 NewFD = FunctionDecl::Create( 8665 FD->getASTContext(), FD->getDeclContext(), Loc, Loc, 8666 DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None, 8667 getCurFPFeatures().isFPConstrained(), false /*isInlineSpecified*/, 8668 FD->hasPrototype(), ConstexprSpecKind::Unspecified, 8669 FD->getTrailingRequiresClause()); 8670 NewD = NewFD; 8671 8672 if (FD->getQualifier()) 8673 NewFD->setQualifierInfo(FD->getQualifierLoc()); 8674 8675 // Fake up parameter variables; they are declared as if this were 8676 // a typedef. 8677 QualType FDTy = FD->getType(); 8678 if (const auto *FT = FDTy->getAs<FunctionProtoType>()) { 8679 SmallVector<ParmVarDecl*, 16> Params; 8680 for (const auto &AI : FT->param_types()) { 8681 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI); 8682 Param->setScopeInfo(0, Params.size()); 8683 Params.push_back(Param); 8684 } 8685 NewFD->setParams(Params); 8686 } 8687 } else if (auto *VD = dyn_cast<VarDecl>(ND)) { 8688 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(), 8689 VD->getInnerLocStart(), VD->getLocation(), II, 8690 VD->getType(), VD->getTypeSourceInfo(), 8691 VD->getStorageClass()); 8692 if (VD->getQualifier()) 8693 cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc()); 8694 } 8695 return NewD; 8696 } 8697 8698 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak 8699 /// applied to it, possibly with an alias. 8700 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) { 8701 if (W.getUsed()) return; // only do this once 8702 W.setUsed(true); 8703 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...)) 8704 IdentifierInfo *NDId = ND->getIdentifier(); 8705 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation()); 8706 NewD->addAttr( 8707 AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation())); 8708 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(), 8709 AttributeCommonInfo::AS_Pragma)); 8710 WeakTopLevelDecl.push_back(NewD); 8711 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin 8712 // to insert Decl at TU scope, sorry. 8713 DeclContext *SavedContext = CurContext; 8714 CurContext = Context.getTranslationUnitDecl(); 8715 NewD->setDeclContext(CurContext); 8716 NewD->setLexicalDeclContext(CurContext); 8717 PushOnScopeChains(NewD, S); 8718 CurContext = SavedContext; 8719 } else { // just add weak to existing 8720 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(), 8721 AttributeCommonInfo::AS_Pragma)); 8722 } 8723 } 8724 8725 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) { 8726 // It's valid to "forward-declare" #pragma weak, in which case we 8727 // have to do this. 8728 LoadExternalWeakUndeclaredIdentifiers(); 8729 if (!WeakUndeclaredIdentifiers.empty()) { 8730 NamedDecl *ND = nullptr; 8731 if (auto *VD = dyn_cast<VarDecl>(D)) 8732 if (VD->isExternC()) 8733 ND = VD; 8734 if (auto *FD = dyn_cast<FunctionDecl>(D)) 8735 if (FD->isExternC()) 8736 ND = FD; 8737 if (ND) { 8738 if (IdentifierInfo *Id = ND->getIdentifier()) { 8739 auto I = WeakUndeclaredIdentifiers.find(Id); 8740 if (I != WeakUndeclaredIdentifiers.end()) { 8741 WeakInfo W = I->second; 8742 DeclApplyPragmaWeak(S, ND, W); 8743 WeakUndeclaredIdentifiers[Id] = W; 8744 } 8745 } 8746 } 8747 } 8748 } 8749 8750 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in 8751 /// it, apply them to D. This is a bit tricky because PD can have attributes 8752 /// specified in many different places, and we need to find and apply them all. 8753 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) { 8754 // Apply decl attributes from the DeclSpec if present. 8755 if (!PD.getDeclSpec().getAttributes().empty()) 8756 ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes()); 8757 8758 // Walk the declarator structure, applying decl attributes that were in a type 8759 // position to the decl itself. This handles cases like: 8760 // int *__attr__(x)** D; 8761 // when X is a decl attribute. 8762 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) 8763 ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(), 8764 /*IncludeCXX11Attributes=*/false); 8765 8766 // Finally, apply any attributes on the decl itself. 8767 ProcessDeclAttributeList(S, D, PD.getAttributes()); 8768 8769 // Apply additional attributes specified by '#pragma clang attribute'. 8770 AddPragmaAttributes(S, D); 8771 } 8772 8773 /// Is the given declaration allowed to use a forbidden type? 8774 /// If so, it'll still be annotated with an attribute that makes it 8775 /// illegal to actually use. 8776 static bool isForbiddenTypeAllowed(Sema &S, Decl *D, 8777 const DelayedDiagnostic &diag, 8778 UnavailableAttr::ImplicitReason &reason) { 8779 // Private ivars are always okay. Unfortunately, people don't 8780 // always properly make their ivars private, even in system headers. 8781 // Plus we need to make fields okay, too. 8782 if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) && 8783 !isa<FunctionDecl>(D)) 8784 return false; 8785 8786 // Silently accept unsupported uses of __weak in both user and system 8787 // declarations when it's been disabled, for ease of integration with 8788 // -fno-objc-arc files. We do have to take some care against attempts 8789 // to define such things; for now, we've only done that for ivars 8790 // and properties. 8791 if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) { 8792 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled || 8793 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) { 8794 reason = UnavailableAttr::IR_ForbiddenWeak; 8795 return true; 8796 } 8797 } 8798 8799 // Allow all sorts of things in system headers. 8800 if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) { 8801 // Currently, all the failures dealt with this way are due to ARC 8802 // restrictions. 8803 reason = UnavailableAttr::IR_ARCForbiddenType; 8804 return true; 8805 } 8806 8807 return false; 8808 } 8809 8810 /// Handle a delayed forbidden-type diagnostic. 8811 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD, 8812 Decl *D) { 8813 auto Reason = UnavailableAttr::IR_None; 8814 if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) { 8815 assert(Reason && "didn't set reason?"); 8816 D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc)); 8817 return; 8818 } 8819 if (S.getLangOpts().ObjCAutoRefCount) 8820 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 8821 // FIXME: we may want to suppress diagnostics for all 8822 // kind of forbidden type messages on unavailable functions. 8823 if (FD->hasAttr<UnavailableAttr>() && 8824 DD.getForbiddenTypeDiagnostic() == 8825 diag::err_arc_array_param_no_ownership) { 8826 DD.Triggered = true; 8827 return; 8828 } 8829 } 8830 8831 S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic()) 8832 << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument(); 8833 DD.Triggered = true; 8834 } 8835 8836 8837 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) { 8838 assert(DelayedDiagnostics.getCurrentPool()); 8839 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool(); 8840 DelayedDiagnostics.popWithoutEmitting(state); 8841 8842 // When delaying diagnostics to run in the context of a parsed 8843 // declaration, we only want to actually emit anything if parsing 8844 // succeeds. 8845 if (!decl) return; 8846 8847 // We emit all the active diagnostics in this pool or any of its 8848 // parents. In general, we'll get one pool for the decl spec 8849 // and a child pool for each declarator; in a decl group like: 8850 // deprecated_typedef foo, *bar, baz(); 8851 // only the declarator pops will be passed decls. This is correct; 8852 // we really do need to consider delayed diagnostics from the decl spec 8853 // for each of the different declarations. 8854 const DelayedDiagnosticPool *pool = &poppedPool; 8855 do { 8856 bool AnyAccessFailures = false; 8857 for (DelayedDiagnosticPool::pool_iterator 8858 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) { 8859 // This const_cast is a bit lame. Really, Triggered should be mutable. 8860 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i); 8861 if (diag.Triggered) 8862 continue; 8863 8864 switch (diag.Kind) { 8865 case DelayedDiagnostic::Availability: 8866 // Don't bother giving deprecation/unavailable diagnostics if 8867 // the decl is invalid. 8868 if (!decl->isInvalidDecl()) 8869 handleDelayedAvailabilityCheck(diag, decl); 8870 break; 8871 8872 case DelayedDiagnostic::Access: 8873 // Only produce one access control diagnostic for a structured binding 8874 // declaration: we don't need to tell the user that all the fields are 8875 // inaccessible one at a time. 8876 if (AnyAccessFailures && isa<DecompositionDecl>(decl)) 8877 continue; 8878 HandleDelayedAccessCheck(diag, decl); 8879 if (diag.Triggered) 8880 AnyAccessFailures = true; 8881 break; 8882 8883 case DelayedDiagnostic::ForbiddenType: 8884 handleDelayedForbiddenType(*this, diag, decl); 8885 break; 8886 } 8887 } 8888 } while ((pool = pool->getParent())); 8889 } 8890 8891 /// Given a set of delayed diagnostics, re-emit them as if they had 8892 /// been delayed in the current context instead of in the given pool. 8893 /// Essentially, this just moves them to the current pool. 8894 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) { 8895 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool(); 8896 assert(curPool && "re-emitting in undelayed context not supported"); 8897 curPool->steal(pool); 8898 } 8899