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