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