clang  14.0.0git
SemaDeclAttr.cpp
Go to the documentation of this file.
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"
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"
24 #include "clang/AST/Type.h"
25 #include "clang/Basic/CharInfo.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedAttr.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
40 #include "llvm/ADT/Optional.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/IR/Assumptions.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/Error.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/raw_ostream.h"
48 
49 using namespace clang;
50 using namespace sema;
51 
53  enum LANG {
54  C,
55  Cpp,
57  };
58 } // end namespace AttributeLangSupport
59 
60 //===----------------------------------------------------------------------===//
61 // Helper functions
62 //===----------------------------------------------------------------------===//
63 
64 /// isFunctionOrMethod - Return true if the given decl has function
65 /// type (function or function-typed variable) or an Objective-C
66 /// method.
67 static bool isFunctionOrMethod(const Decl *D) {
68  return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
69 }
70 
71 /// Return true if the given decl has function type (function or
72 /// function-typed variable) or an Objective-C method or a block.
73 static bool isFunctionOrMethodOrBlock(const Decl *D) {
74  return isFunctionOrMethod(D) || isa<BlockDecl>(D);
75 }
76 
77 /// Return true if the given decl has a declarator that should have
78 /// been processed by Sema::GetTypeForDeclarator.
79 static bool hasDeclarator(const Decl *D) {
80  // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
81  return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
82  isa<ObjCPropertyDecl>(D);
83 }
84 
85 /// hasFunctionProto - Return true if the given decl has a argument
86 /// information. This decl should have already passed
87 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
88 static bool hasFunctionProto(const Decl *D) {
89  if (const FunctionType *FnTy = D->getFunctionType())
90  return isa<FunctionProtoType>(FnTy);
91  return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
92 }
93 
94 /// getFunctionOrMethodNumParams - Return number of function or method
95 /// parameters. It is an error to call this on a K&R function (use
96 /// hasFunctionProto first).
97 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
98  if (const FunctionType *FnTy = D->getFunctionType())
99  return cast<FunctionProtoType>(FnTy)->getNumParams();
100  if (const auto *BD = dyn_cast<BlockDecl>(D))
101  return BD->getNumParams();
102  return cast<ObjCMethodDecl>(D)->param_size();
103 }
104 
106  unsigned Idx) {
107  if (const auto *FD = dyn_cast<FunctionDecl>(D))
108  return FD->getParamDecl(Idx);
109  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
110  return MD->getParamDecl(Idx);
111  if (const auto *BD = dyn_cast<BlockDecl>(D))
112  return BD->getParamDecl(Idx);
113  return nullptr;
114 }
115 
116 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
117  if (const FunctionType *FnTy = D->getFunctionType())
118  return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
119  if (const auto *BD = dyn_cast<BlockDecl>(D))
120  return BD->getParamDecl(Idx)->getType();
121 
122  return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
123 }
124 
125 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
126  if (auto *PVD = getFunctionOrMethodParam(D, Idx))
127  return PVD->getSourceRange();
128  return SourceRange();
129 }
130 
132  if (const FunctionType *FnTy = D->getFunctionType())
133  return FnTy->getReturnType();
134  return cast<ObjCMethodDecl>(D)->getReturnType();
135 }
136 
138  if (const auto *FD = dyn_cast<FunctionDecl>(D))
139  return FD->getReturnTypeSourceRange();
140  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
141  return MD->getReturnTypeSourceRange();
142  return SourceRange();
143 }
144 
145 static bool isFunctionOrMethodVariadic(const Decl *D) {
146  if (const FunctionType *FnTy = D->getFunctionType())
147  return cast<FunctionProtoType>(FnTy)->isVariadic();
148  if (const auto *BD = dyn_cast<BlockDecl>(D))
149  return BD->isVariadic();
150  return cast<ObjCMethodDecl>(D)->isVariadic();
151 }
152 
153 static bool isInstanceMethod(const Decl *D) {
154  if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
155  return MethodDecl->isInstance();
156  return false;
157 }
158 
159 static inline bool isNSStringType(QualType T, ASTContext &Ctx,
160  bool AllowNSAttributedString = false) {
161  const auto *PT = T->getAs<ObjCObjectPointerType>();
162  if (!PT)
163  return false;
164 
165  ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
166  if (!Cls)
167  return false;
168 
169  IdentifierInfo* ClsName = Cls->getIdentifier();
170 
171  if (AllowNSAttributedString &&
172  ClsName == &Ctx.Idents.get("NSAttributedString"))
173  return true;
174  // FIXME: Should we walk the chain of classes?
175  return ClsName == &Ctx.Idents.get("NSString") ||
176  ClsName == &Ctx.Idents.get("NSMutableString");
177 }
178 
179 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
180  const auto *PT = T->getAs<PointerType>();
181  if (!PT)
182  return false;
183 
184  const auto *RT = PT->getPointeeType()->getAs<RecordType>();
185  if (!RT)
186  return false;
187 
188  const RecordDecl *RD = RT->getDecl();
189  if (RD->getTagKind() != TTK_Struct)
190  return false;
191 
192  return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
193 }
194 
195 static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
196  // FIXME: Include the type in the argument list.
197  return AL.getNumArgs() + AL.hasParsedType();
198 }
199 
200 /// A helper function to provide Attribute Location for the Attr types
201 /// AND the ParsedAttr.
202 template <typename AttrInfo>
203 static std::enable_if_t<std::is_base_of<Attr, AttrInfo>::value, SourceLocation>
204 getAttrLoc(const AttrInfo &AL) {
205  return AL.getLocation();
206 }
207 static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
208 
209 /// If Expr is a valid integer constant, get the value of the integer
210 /// expression and return success or failure. May output an error.
211 ///
212 /// Negative argument is implicitly converted to unsigned, unless
213 /// \p StrictlyUnsigned is true.
214 template <typename AttrInfo>
215 static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
216  uint32_t &Val, unsigned Idx = UINT_MAX,
217  bool StrictlyUnsigned = false) {
219  if (Expr->isTypeDependent() || Expr->isValueDependent() ||
220  !(I = Expr->getIntegerConstantExpr(S.Context))) {
221  if (Idx != UINT_MAX)
222  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
223  << &AI << Idx << AANT_ArgumentIntegerConstant
224  << Expr->getSourceRange();
225  else
226  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
228  return false;
229  }
230 
231  if (!I->isIntN(32)) {
232  S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
233  << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
234  return false;
235  }
236 
237  if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
238  S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
239  << &AI << /*non-negative*/ 1;
240  return false;
241  }
242 
243  Val = (uint32_t)I->getZExtValue();
244  return true;
245 }
246 
247 /// Wrapper around checkUInt32Argument, with an extra check to be sure
248 /// that the result will fit into a regular (signed) int. All args have the same
249 /// purpose as they do in checkUInt32Argument.
250 template <typename AttrInfo>
251 static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
252  int &Val, unsigned Idx = UINT_MAX) {
253  uint32_t UVal;
254  if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
255  return false;
256 
257  if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
258  llvm::APSInt I(32); // for toString
259  I = UVal;
260  S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
261  << toString(I, 10, false) << 32 << /* Unsigned */ 0;
262  return false;
263  }
264 
265  Val = UVal;
266  return true;
267 }
268 
269 /// Diagnose mutually exclusive attributes when present on a given
270 /// declaration. Returns true if diagnosed.
271 template <typename AttrTy>
272 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
273  if (const auto *A = D->getAttr<AttrTy>()) {
274  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
275  S.Diag(A->getLocation(), diag::note_conflicting_attribute);
276  return true;
277  }
278  return false;
279 }
280 
281 template <typename AttrTy>
282 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
283  if (const auto *A = D->getAttr<AttrTy>()) {
284  S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL
285  << A;
286  S.Diag(A->getLocation(), diag::note_conflicting_attribute);
287  return true;
288  }
289  return false;
290 }
291 
292 /// Check if IdxExpr is a valid parameter index for a function or
293 /// instance method D. May output an error.
294 ///
295 /// \returns true if IdxExpr is a valid index.
296 template <typename AttrInfo>
298  Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
299  const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
300  assert(isFunctionOrMethodOrBlock(D));
301 
302  // In C++ the implicit 'this' function parameter also counts.
303  // Parameters are counted from one.
304  bool HP = hasFunctionProto(D);
305  bool HasImplicitThisParam = isInstanceMethod(D);
306  bool IV = HP && isFunctionOrMethodVariadic(D);
307  unsigned NumParams =
308  (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
309 
310  Optional<llvm::APSInt> IdxInt;
311  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
312  !(IdxInt = IdxExpr->getIntegerConstantExpr(S.Context))) {
313  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
314  << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
315  << IdxExpr->getSourceRange();
316  return false;
317  }
318 
319  unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX);
320  if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
321  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
322  << &AI << AttrArgNum << IdxExpr->getSourceRange();
323  return false;
324  }
325  if (HasImplicitThisParam && !CanIndexImplicitThis) {
326  if (IdxSource == 1) {
327  S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
328  << &AI << IdxExpr->getSourceRange();
329  return false;
330  }
331  }
332 
333  Idx = ParamIdx(IdxSource, D);
334  return true;
335 }
336 
337 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
338 /// If not emit an error and return false. If the argument is an identifier it
339 /// will emit an error with a fixit hint and treat it as if it was a string
340 /// literal.
341 bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
342  StringRef &Str,
343  SourceLocation *ArgLocation) {
344  // Look for identifiers. If we have one emit a hint to fix it to a literal.
345  if (AL.isArgIdent(ArgNum)) {
346  IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
347  Diag(Loc->Loc, diag::err_attribute_argument_type)
348  << AL << AANT_ArgumentString
349  << FixItHint::CreateInsertion(Loc->Loc, "\"")
350  << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
351  Str = Loc->Ident->getName();
352  if (ArgLocation)
353  *ArgLocation = Loc->Loc;
354  return true;
355  }
356 
357  // Now check for an actual string literal.
358  Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
359  const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
360  if (ArgLocation)
361  *ArgLocation = ArgExpr->getBeginLoc();
362 
363  if (!Literal || !Literal->isAscii()) {
364  Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
365  << AL << AANT_ArgumentString;
366  return false;
367  }
368 
369  Str = Literal->getString();
370  return true;
371 }
372 
373 /// Applies the given attribute to the Decl without performing any
374 /// additional semantic checking.
375 template <typename AttrType>
376 static void handleSimpleAttribute(Sema &S, Decl *D,
377  const AttributeCommonInfo &CI) {
378  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379 }
380 
381 template <typename... DiagnosticArgs>
382 static const Sema::SemaDiagnosticBuilder&
384  return Bldr;
385 }
386 
387 template <typename T, typename... DiagnosticArgs>
388 static const Sema::SemaDiagnosticBuilder&
390  DiagnosticArgs &&... ExtraArgs) {
391  return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
392  std::forward<DiagnosticArgs>(ExtraArgs)...);
393 }
394 
395 /// Add an attribute @c AttrType to declaration @c D, provided that
396 /// @c PassesCheck is true.
397 /// Otherwise, emit diagnostic @c DiagID, passing in all parameters
398 /// specified in @c ExtraArgs.
399 template <typename AttrType, typename... DiagnosticArgs>
401  const AttributeCommonInfo &CI,
402  bool PassesCheck, unsigned DiagID,
403  DiagnosticArgs &&... ExtraArgs) {
404  if (!PassesCheck) {
405  Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
406  appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
407  return;
408  }
409  handleSimpleAttribute<AttrType>(S, D, CI);
410 }
411 
412 /// Check if the passed-in expression is of type int or bool.
413 static bool isIntOrBool(Expr *Exp) {
414  QualType QT = Exp->getType();
415  return QT->isBooleanType() || QT->isIntegerType();
416 }
417 
418 
419 // Check to see if the type is a smart pointer of some kind. We assume
420 // it's a smart pointer if it defines both operator-> and operator*.
421 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
422  auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
424  DeclContextLookupResult Result =
426  return !Result.empty();
427  };
428 
429  const RecordDecl *Record = RT->getDecl();
430  bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
431  bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
432  if (foundStarOperator && foundArrowOperator)
433  return true;
434 
435  const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
436  if (!CXXRecord)
437  return false;
438 
439  for (auto BaseSpecifier : CXXRecord->bases()) {
440  if (!foundStarOperator)
441  foundStarOperator = IsOverloadedOperatorPresent(
442  BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
443  if (!foundArrowOperator)
444  foundArrowOperator = IsOverloadedOperatorPresent(
445  BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
446  }
447 
448  if (foundStarOperator && foundArrowOperator)
449  return true;
450 
451  return false;
452 }
453 
454 /// Check if passed in Decl is a pointer type.
455 /// Note that this function may produce an error message.
456 /// \return true if the Decl is a pointer type; false otherwise
457 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
458  const ParsedAttr &AL) {
459  const auto *VD = cast<ValueDecl>(D);
460  QualType QT = VD->getType();
461  if (QT->isAnyPointerType())
462  return true;
463 
464  if (const auto *RT = QT->getAs<RecordType>()) {
465  // If it's an incomplete type, it could be a smart pointer; skip it.
466  // (We don't want to force template instantiation if we can avoid it,
467  // since that would alter the order in which templates are instantiated.)
468  if (RT->isIncompleteType())
469  return true;
470 
472  return true;
473  }
474 
475  S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
476  return false;
477 }
478 
479 /// Checks that the passed in QualType either is of RecordType or points
480 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
481 static const RecordType *getRecordType(QualType QT) {
482  if (const auto *RT = QT->getAs<RecordType>())
483  return RT;
484 
485  // Now check if we point to record type.
486  if (const auto *PT = QT->getAs<PointerType>())
487  return PT->getPointeeType()->getAs<RecordType>();
488 
489  return nullptr;
490 }
491 
492 template <typename AttrType>
493 static bool checkRecordDeclForAttr(const RecordDecl *RD) {
494  // Check if the record itself has the attribute.
495  if (RD->hasAttr<AttrType>())
496  return true;
497 
498  // Else check if any base classes have the attribute.
499  if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
500  if (!CRD->forallBases([](const CXXRecordDecl *Base) {
501  return !Base->hasAttr<AttrType>();
502  }))
503  return true;
504  }
505  return false;
506 }
507 
509  const RecordType *RT = getRecordType(Ty);
510 
511  if (!RT)
512  return false;
513 
514  // Don't check for the capability if the class hasn't been defined yet.
515  if (RT->isIncompleteType())
516  return true;
517 
518  // Allow smart pointers to be used as capability objects.
519  // FIXME -- Check the type that the smart pointer points to.
521  return true;
522 
523  return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
524 }
525 
527  const auto *TD = Ty->getAs<TypedefType>();
528  if (!TD)
529  return false;
530 
531  TypedefNameDecl *TN = TD->getDecl();
532  if (!TN)
533  return false;
534 
535  return TN->hasAttr<CapabilityAttr>();
536 }
537 
538 static bool typeHasCapability(Sema &S, QualType Ty) {
540  return true;
541 
542  if (checkRecordTypeForCapability(S, Ty))
543  return true;
544 
545  return false;
546 }
547 
548 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
549  // Capability expressions are simple expressions involving the boolean logic
550  // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
551  // a DeclRefExpr is found, its type should be checked to determine whether it
552  // is a capability or not.
553 
554  if (const auto *E = dyn_cast<CastExpr>(Ex))
555  return isCapabilityExpr(S, E->getSubExpr());
556  else if (const auto *E = dyn_cast<ParenExpr>(Ex))
557  return isCapabilityExpr(S, E->getSubExpr());
558  else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
559  if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
560  E->getOpcode() == UO_Deref)
561  return isCapabilityExpr(S, E->getSubExpr());
562  return false;
563  } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
564  if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
565  return isCapabilityExpr(S, E->getLHS()) &&
566  isCapabilityExpr(S, E->getRHS());
567  return false;
568  }
569 
570  return typeHasCapability(S, Ex->getType());
571 }
572 
573 /// Checks that all attribute arguments, starting from Sidx, resolve to
574 /// a capability object.
575 /// \param Sidx The attribute argument index to start checking with.
576 /// \param ParamIdxOk Whether an argument can be indexing into a function
577 /// parameter list.
579  const ParsedAttr &AL,
581  unsigned Sidx = 0,
582  bool ParamIdxOk = false) {
583  if (Sidx == AL.getNumArgs()) {
584  // If we don't have any capability arguments, the attribute implicitly
585  // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
586  // a non-static method, and that the class is a (scoped) capability.
587  const auto *MD = dyn_cast<const CXXMethodDecl>(D);
588  if (MD && !MD->isStatic()) {
589  const CXXRecordDecl *RD = MD->getParent();
590  // FIXME -- need to check this again on template instantiation
591  if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
592  !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
593  S.Diag(AL.getLoc(),
594  diag::warn_thread_attribute_not_on_capability_member)
595  << AL << MD->getParent();
596  } else {
597  S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
598  << AL;
599  }
600  }
601 
602  for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
603  Expr *ArgExp = AL.getArgAsExpr(Idx);
604 
605  if (ArgExp->isTypeDependent()) {
606  // FIXME -- need to check this again on template instantiation
607  Args.push_back(ArgExp);
608  continue;
609  }
610 
611  if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
612  if (StrLit->getLength() == 0 ||
613  (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
614  // Pass empty strings to the analyzer without warnings.
615  // Treat "*" as the universal lock.
616  Args.push_back(ArgExp);
617  continue;
618  }
619 
620  // We allow constant strings to be used as a placeholder for expressions
621  // that are not valid C++ syntax, but warn that they are ignored.
622  S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
623  Args.push_back(ArgExp);
624  continue;
625  }
626 
627  QualType ArgTy = ArgExp->getType();
628 
629  // A pointer to member expression of the form &MyClass::mu is treated
630  // specially -- we need to look at the type of the member.
631  if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
632  if (UOp->getOpcode() == UO_AddrOf)
633  if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
634  if (DRE->getDecl()->isCXXInstanceMember())
635  ArgTy = DRE->getDecl()->getType();
636 
637  // First see if we can just cast to record type, or pointer to record type.
638  const RecordType *RT = getRecordType(ArgTy);
639 
640  // Now check if we index into a record type function param.
641  if(!RT && ParamIdxOk) {
642  const auto *FD = dyn_cast<FunctionDecl>(D);
643  const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
644  if(FD && IL) {
645  unsigned int NumParams = FD->getNumParams();
646  llvm::APInt ArgValue = IL->getValue();
647  uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
648  uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
649  if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
650  S.Diag(AL.getLoc(),
651  diag::err_attribute_argument_out_of_bounds_extra_info)
652  << AL << Idx + 1 << NumParams;
653  continue;
654  }
655  ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
656  }
657  }
658 
659  // If the type does not have a capability, see if the components of the
660  // expression have capabilities. This allows for writing C code where the
661  // capability may be on the type, and the expression is a capability
662  // boolean logic expression. Eg) requires_capability(A || B && !C)
663  if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
664  S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
665  << AL << ArgTy;
666 
667  Args.push_back(ArgExp);
668  }
669 }
670 
671 //===----------------------------------------------------------------------===//
672 // Attribute Implementations
673 //===----------------------------------------------------------------------===//
674 
675 static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
676  if (!threadSafetyCheckIsPointer(S, D, AL))
677  return;
678 
679  D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL));
680 }
681 
682 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
683  Expr *&Arg) {
685  // check that all arguments are lockable objects
686  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
687  unsigned Size = Args.size();
688  if (Size != 1)
689  return false;
690 
691  Arg = Args[0];
692 
693  return true;
694 }
695 
696 static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
697  Expr *Arg = nullptr;
698  if (!checkGuardedByAttrCommon(S, D, AL, Arg))
699  return;
700 
701  D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg));
702 }
703 
704 static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
705  Expr *Arg = nullptr;
706  if (!checkGuardedByAttrCommon(S, D, AL, Arg))
707  return;
708 
709  if (!threadSafetyCheckIsPointer(S, D, AL))
710  return;
711 
712  D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg));
713 }
714 
715 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
716  SmallVectorImpl<Expr *> &Args) {
717  if (!AL.checkAtLeastNumArgs(S, 1))
718  return false;
719 
720  // Check that this attribute only applies to lockable types.
721  QualType QT = cast<ValueDecl>(D)->getType();
722  if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
723  S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
724  return false;
725  }
726 
727  // Check that all arguments are lockable objects.
728  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
729  if (Args.empty())
730  return false;
731 
732  return true;
733 }
734 
735 static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
737  if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
738  return;
739 
740  Expr **StartArg = &Args[0];
741  D->addAttr(::new (S.Context)
742  AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
743 }
744 
745 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
747  if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
748  return;
749 
750  Expr **StartArg = &Args[0];
751  D->addAttr(::new (S.Context)
752  AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
753 }
754 
755 static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
756  SmallVectorImpl<Expr *> &Args) {
757  // zero or more arguments ok
758  // check that all arguments are lockable objects
759  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
760 
761  return true;
762 }
763 
764 static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
766  if (!checkLockFunAttrCommon(S, D, AL, Args))
767  return;
768 
769  unsigned Size = Args.size();
770  Expr **StartArg = Size == 0 ? nullptr : &Args[0];
771  D->addAttr(::new (S.Context)
772  AssertSharedLockAttr(S.Context, AL, StartArg, Size));
773 }
774 
776  const ParsedAttr &AL) {
778  if (!checkLockFunAttrCommon(S, D, AL, Args))
779  return;
780 
781  unsigned Size = Args.size();
782  Expr **StartArg = Size == 0 ? nullptr : &Args[0];
783  D->addAttr(::new (S.Context)
784  AssertExclusiveLockAttr(S.Context, AL, StartArg, Size));
785 }
786 
787 /// Checks to be sure that the given parameter number is in bounds, and
788 /// is an integral type. Will emit appropriate diagnostics if this returns
789 /// false.
790 ///
791 /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
792 template <typename AttrInfo>
793 static bool checkParamIsIntegerType(Sema &S, const Decl *D, const AttrInfo &AI,
794  unsigned AttrArgNo) {
795  assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
796  Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
797  ParamIdx Idx;
798  if (!checkFunctionOrMethodParameterIndex(S, D, AI, AttrArgNo + 1, AttrArg,
799  Idx))
800  return false;
801 
803  if (!ParamTy->isIntegerType() && !ParamTy->isCharType()) {
804  SourceLocation SrcLoc = AttrArg->getBeginLoc();
805  S.Diag(SrcLoc, diag::err_attribute_integers_only)
806  << AI << getFunctionOrMethodParamRange(D, Idx.getASTIndex());
807  return false;
808  }
809  return true;
810 }
811 
812 static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
813  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
814  return;
815 
816  assert(isFunctionOrMethod(D) && hasFunctionProto(D));
817 
819  if (!RetTy->isPointerType()) {
820  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
821  return;
822  }
823 
824  const Expr *SizeExpr = AL.getArgAsExpr(0);
825  int SizeArgNoVal;
826  // Parameter indices are 1-indexed, hence Index=1
827  if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1))
828  return;
829  if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/0))
830  return;
831  ParamIdx SizeArgNo(SizeArgNoVal, D);
832 
833  ParamIdx NumberArgNo;
834  if (AL.getNumArgs() == 2) {
835  const Expr *NumberExpr = AL.getArgAsExpr(1);
836  int Val;
837  // Parameter indices are 1-based, hence Index=2
838  if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2))
839  return;
840  if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/1))
841  return;
842  NumberArgNo = ParamIdx(Val, D);
843  }
844 
845  D->addAttr(::new (S.Context)
846  AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
847 }
848 
849 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
850  SmallVectorImpl<Expr *> &Args) {
851  if (!AL.checkAtLeastNumArgs(S, 1))
852  return false;
853 
854  if (!isIntOrBool(AL.getArgAsExpr(0))) {
855  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
856  << AL << 1 << AANT_ArgumentIntOrBool;
857  return false;
858  }
859 
860  // check that all arguments are lockable objects
861  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
862 
863  return true;
864 }
865 
867  const ParsedAttr &AL) {
869  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
870  return;
871 
872  D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
873  S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
874 }
875 
877  const ParsedAttr &AL) {
879  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
880  return;
881 
882  D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
883  S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
884 }
885 
886 static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
887  // check that the argument is lockable object
889  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
890  unsigned Size = Args.size();
891  if (Size == 0)
892  return;
893 
894  D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
895 }
896 
897 static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
898  if (!AL.checkAtLeastNumArgs(S, 1))
899  return;
900 
901  // check that all arguments are lockable objects
903  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
904  unsigned Size = Args.size();
905  if (Size == 0)
906  return;
907  Expr **StartArg = &Args[0];
908 
909  D->addAttr(::new (S.Context)
910  LocksExcludedAttr(S.Context, AL, StartArg, Size));
911 }
912 
913 static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
914  Expr *&Cond, StringRef &Msg) {
915  Cond = AL.getArgAsExpr(0);
916  if (!Cond->isTypeDependent()) {
917  ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
918  if (Converted.isInvalid())
919  return false;
920  Cond = Converted.get();
921  }
922 
923  if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
924  return false;
925 
926  if (Msg.empty())
927  Msg = "<no message provided>";
928 
930  if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
931  !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
932  Diags)) {
933  S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
934  for (const PartialDiagnosticAt &PDiag : Diags)
935  S.Diag(PDiag.first, PDiag.second);
936  return false;
937  }
938  return true;
939 }
940 
941 static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
942  S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
943 
944  Expr *Cond;
945  StringRef Msg;
946  if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
947  D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
948 }
949 
950 static void handleErrorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
951  StringRef NewUserDiagnostic;
952  if (!S.checkStringLiteralArgumentAttr(AL, 0, NewUserDiagnostic))
953  return;
954  if (ErrorAttr *EA = S.mergeErrorAttr(D, AL, NewUserDiagnostic))
955  D->addAttr(EA);
956 }
957 
958 namespace {
959 /// Determines if a given Expr references any of the given function's
960 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
961 class ArgumentDependenceChecker
962  : public RecursiveASTVisitor<ArgumentDependenceChecker> {
963 #ifndef NDEBUG
964  const CXXRecordDecl *ClassType;
965 #endif
967  bool Result;
968 
969 public:
970  ArgumentDependenceChecker(const FunctionDecl *FD) {
971 #ifndef NDEBUG
972  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
973  ClassType = MD->getParent();
974  else
975  ClassType = nullptr;
976 #endif
977  Parms.insert(FD->param_begin(), FD->param_end());
978  }
979 
980  bool referencesArgs(Expr *E) {
981  Result = false;
982  TraverseStmt(E);
983  return Result;
984  }
985 
986  bool VisitCXXThisExpr(CXXThisExpr *E) {
987  assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
988  "`this` doesn't refer to the enclosing class?");
989  Result = true;
990  return false;
991  }
992 
993  bool VisitDeclRefExpr(DeclRefExpr *DRE) {
994  if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
995  if (Parms.count(PVD)) {
996  Result = true;
997  return false;
998  }
999  return true;
1000  }
1001 };
1002 }
1003 
1004 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1005  S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
1006 
1007  Expr *Cond;
1008  StringRef Msg;
1009  if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1010  return;
1011 
1012  StringRef DiagTypeStr;
1013  if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
1014  return;
1015 
1016  DiagnoseIfAttr::DiagnosticType DiagType;
1017  if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1018  S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1019  diag::err_diagnose_if_invalid_diagnostic_type);
1020  return;
1021  }
1022 
1023  bool ArgDependent = false;
1024  if (const auto *FD = dyn_cast<FunctionDecl>(D))
1025  ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1026  D->addAttr(::new (S.Context) DiagnoseIfAttr(
1027  S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D)));
1028 }
1029 
1030 static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1031  static constexpr const StringRef kWildcard = "*";
1032 
1034  bool HasWildcard = false;
1035 
1036  const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) {
1037  if (Name == kWildcard)
1038  HasWildcard = true;
1039  Names.push_back(Name);
1040  };
1041 
1042  // Add previously defined attributes.
1043  if (const auto *NBA = D->getAttr<NoBuiltinAttr>())
1044  for (StringRef BuiltinName : NBA->builtinNames())
1045  AddBuiltinName(BuiltinName);
1046 
1047  // Add current attributes.
1048  if (AL.getNumArgs() == 0)
1049  AddBuiltinName(kWildcard);
1050  else
1051  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
1052  StringRef BuiltinName;
1053  SourceLocation LiteralLoc;
1054  if (!S.checkStringLiteralArgumentAttr(AL, I, BuiltinName, &LiteralLoc))
1055  return;
1056 
1057  if (Builtin::Context::isBuiltinFunc(BuiltinName))
1058  AddBuiltinName(BuiltinName);
1059  else
1060  S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name)
1061  << BuiltinName << AL;
1062  }
1063 
1064  // Repeating the same attribute is fine.
1065  llvm::sort(Names);
1066  Names.erase(std::unique(Names.begin(), Names.end()), Names.end());
1067 
1068  // Empty no_builtin must be on its own.
1069  if (HasWildcard && Names.size() > 1)
1070  S.Diag(D->getLocation(),
1071  diag::err_attribute_no_builtin_wildcard_or_builtin_name)
1072  << AL;
1073 
1074  if (D->hasAttr<NoBuiltinAttr>())
1075  D->dropAttr<NoBuiltinAttr>();
1076  D->addAttr(::new (S.Context)
1077  NoBuiltinAttr(S.Context, AL, Names.data(), Names.size()));
1078 }
1079 
1080 static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1081  if (D->hasAttr<PassObjectSizeAttr>()) {
1082  S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1083  return;
1084  }
1085 
1086  Expr *E = AL.getArgAsExpr(0);
1087  uint32_t Type;
1088  if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1089  return;
1090 
1091  // pass_object_size's argument is passed in as the second argument of
1092  // __builtin_object_size. So, it has the same constraints as that second
1093  // argument; namely, it must be in the range [0, 3].
1094  if (Type > 3) {
1095  S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
1096  << AL << 0 << 3 << E->getSourceRange();
1097  return;
1098  }
1099 
1100  // pass_object_size is only supported on constant pointer parameters; as a
1101  // kindness to users, we allow the parameter to be non-const for declarations.
1102  // At this point, we have no clue if `D` belongs to a function declaration or
1103  // definition, so we defer the constness check until later.
1104  if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1105  S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1106  return;
1107  }
1108 
1109  D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
1110 }
1111 
1112 static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1113  ConsumableAttr::ConsumedState DefaultState;
1114 
1115  if (AL.isArgIdent(0)) {
1116  IdentifierLoc *IL = AL.getArgAsIdent(0);
1117  if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1118  DefaultState)) {
1119  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1120  << IL->Ident;
1121  return;
1122  }
1123  } else {
1124  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1125  << AL << AANT_ArgumentIdentifier;
1126  return;
1127  }
1128 
1129  D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
1130 }
1131 
1132 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1133  const ParsedAttr &AL) {
1134  QualType ThisType = MD->getThisType()->getPointeeType();
1135 
1136  if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1137  if (!RD->hasAttr<ConsumableAttr>()) {
1138  S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD;
1139 
1140  return false;
1141  }
1142  }
1143 
1144  return true;
1145 }
1146 
1147 static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1148  if (!AL.checkAtLeastNumArgs(S, 1))
1149  return;
1150 
1151  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1152  return;
1153 
1155  for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1156  CallableWhenAttr::ConsumedState CallableState;
1157 
1158  StringRef StateString;
1159  SourceLocation Loc;
1160  if (AL.isArgIdent(ArgIndex)) {
1161  IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1162  StateString = Ident->Ident->getName();
1163  Loc = Ident->Loc;
1164  } else {
1165  if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1166  return;
1167  }
1168 
1169  if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1170  CallableState)) {
1171  S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1172  return;
1173  }
1174 
1175  States.push_back(CallableState);
1176  }
1177 
1178  D->addAttr(::new (S.Context)
1179  CallableWhenAttr(S.Context, AL, States.data(), States.size()));
1180 }
1181 
1182 static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1184 
1185  if (AL.isArgIdent(0)) {
1186  IdentifierLoc *Ident = AL.getArgAsIdent(0);
1187  StringRef StateString = Ident->Ident->getName();
1188 
1189  if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1190  ParamState)) {
1191  S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1192  << AL << StateString;
1193  return;
1194  }
1195  } else {
1196  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1197  << AL << AANT_ArgumentIdentifier;
1198  return;
1199  }
1200 
1201  // FIXME: This check is currently being done in the analysis. It can be
1202  // enabled here only after the parser propagates attributes at
1203  // template specialization definition, not declaration.
1204  //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1205  //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1206  //
1207  //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1208  // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1209  // ReturnType.getAsString();
1210  // return;
1211  //}
1212 
1213  D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
1214 }
1215 
1216 static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1218 
1219  if (AL.isArgIdent(0)) {
1220  IdentifierLoc *IL = AL.getArgAsIdent(0);
1221  if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1222  ReturnState)) {
1223  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1224  << IL->Ident;
1225  return;
1226  }
1227  } else {
1228  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1229  << AL << AANT_ArgumentIdentifier;
1230  return;
1231  }
1232 
1233  // FIXME: This check is currently being done in the analysis. It can be
1234  // enabled here only after the parser propagates attributes at
1235  // template specialization definition, not declaration.
1236  //QualType ReturnType;
1237  //
1238  //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1239  // ReturnType = Param->getType();
1240  //
1241  //} else if (const CXXConstructorDecl *Constructor =
1242  // dyn_cast<CXXConstructorDecl>(D)) {
1243  // ReturnType = Constructor->getThisType()->getPointeeType();
1244  //
1245  //} else {
1246  //
1247  // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1248  //}
1249  //
1250  //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1251  //
1252  //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1253  // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1254  // ReturnType.getAsString();
1255  // return;
1256  //}
1257 
1258  D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
1259 }
1260 
1261 static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1262  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1263  return;
1264 
1266  if (AL.isArgIdent(0)) {
1267  IdentifierLoc *Ident = AL.getArgAsIdent(0);
1268  StringRef Param = Ident->Ident->getName();
1269  if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1270  S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1271  << Param;
1272  return;
1273  }
1274  } else {
1275  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1276  << AL << AANT_ArgumentIdentifier;
1277  return;
1278  }
1279 
1280  D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
1281 }
1282 
1283 static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1284  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1285  return;
1286 
1288  if (AL.isArgIdent(0)) {
1289  IdentifierLoc *Ident = AL.getArgAsIdent(0);
1290  StringRef Param = Ident->Ident->getName();
1291  if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1292  S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1293  << Param;
1294  return;
1295  }
1296  } else {
1297  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1298  << AL << AANT_ArgumentIdentifier;
1299  return;
1300  }
1301 
1302  D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
1303 }
1304 
1305 static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1306  // Remember this typedef decl, we will need it later for diagnostics.
1307  S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1308 }
1309 
1310 static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1311  if (auto *TD = dyn_cast<TagDecl>(D))
1312  TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1313  else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1314  bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1315  !FD->getType()->isIncompleteType() &&
1316  FD->isBitField() &&
1317  S.Context.getTypeAlign(FD->getType()) <= 8);
1318 
1319  if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
1320  if (BitfieldByteAligned)
1321  // The PS4 target needs to maintain ABI backwards compatibility.
1322  S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1323  << AL << FD->getType();
1324  else
1325  FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1326  } else {
1327  // Report warning about changed offset in the newer compiler versions.
1328  if (BitfieldByteAligned)
1329  S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1330 
1331  FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1332  }
1333 
1334  } else
1335  S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1336 }
1337 
1338 static void handlePreferredName(Sema &S, Decl *D, const ParsedAttr &AL) {
1339  auto *RD = cast<CXXRecordDecl>(D);
1340  ClassTemplateDecl *CTD = RD->getDescribedClassTemplate();
1341  assert(CTD && "attribute does not appertain to this declaration");
1342 
1343  ParsedType PT = AL.getTypeArg();
1344  TypeSourceInfo *TSI = nullptr;
1345  QualType T = S.GetTypeFromParser(PT, &TSI);
1346  if (!TSI)
1347  TSI = S.Context.getTrivialTypeSourceInfo(T, AL.getLoc());
1348 
1349  if (!T.hasQualifiers() && T->isTypedefNameType()) {
1350  // Find the template name, if this type names a template specialization.
1351  const TemplateDecl *Template = nullptr;
1352  if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1353  T->getAsCXXRecordDecl())) {
1354  Template = CTSD->getSpecializedTemplate();
1355  } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
1356  while (TST && TST->isTypeAlias())
1357  TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1358  if (TST)
1359  Template = TST->getTemplateName().getAsTemplateDecl();
1360  }
1361 
1362  if (Template && declaresSameEntity(Template, CTD)) {
1363  D->addAttr(::new (S.Context) PreferredNameAttr(S.Context, AL, TSI));
1364  return;
1365  }
1366  }
1367 
1368  S.Diag(AL.getLoc(), diag::err_attribute_preferred_name_arg_invalid)
1369  << T << CTD;
1370  if (const auto *TT = T->getAs<TypedefType>())
1371  S.Diag(TT->getDecl()->getLocation(), diag::note_entity_declared_at)
1372  << TT->getDecl();
1373 }
1374 
1375 static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1376  // The IBOutlet/IBOutletCollection attributes only apply to instance
1377  // variables or properties of Objective-C classes. The outlet must also
1378  // have an object reference type.
1379  if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1380  if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1381  S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1382  << AL << VD->getType() << 0;
1383  return false;
1384  }
1385  }
1386  else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1387  if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1388  S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1389  << AL << PD->getType() << 1;
1390  return false;
1391  }
1392  }
1393  else {
1394  S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1395  return false;
1396  }
1397 
1398  return true;
1399 }
1400 
1401 static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1402  if (!checkIBOutletCommon(S, D, AL))
1403  return;
1404 
1405  D->addAttr(::new (S.Context) IBOutletAttr(S.Context, AL));
1406 }
1407 
1408 static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1409 
1410  // The iboutletcollection attribute can have zero or one arguments.
1411  if (AL.getNumArgs() > 1) {
1412  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1413  return;
1414  }
1415 
1416  if (!checkIBOutletCommon(S, D, AL))
1417  return;
1418 
1419  ParsedType PT;
1420 
1421  if (AL.hasParsedType())
1422  PT = AL.getTypeArg();
1423  else {
1424  PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1426  if (!PT) {
1427  S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1428  return;
1429  }
1430  }
1431 
1432  TypeSourceInfo *QTLoc = nullptr;
1433  QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1434  if (!QTLoc)
1435  QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1436 
1437  // Diagnose use of non-object type in iboutletcollection attribute.
1438  // FIXME. Gnu attribute extension ignores use of builtin types in
1439  // attributes. So, __attribute__((iboutletcollection(char))) will be
1440  // treated as __attribute__((iboutletcollection())).
1441  if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1442  S.Diag(AL.getLoc(),
1443  QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1444  : diag::err_iboutletcollection_type) << QT;
1445  return;
1446  }
1447 
1448  D->addAttr(::new (S.Context) IBOutletCollectionAttr(S.Context, AL, QTLoc));
1449 }
1450 
1452  if (RefOkay) {
1453  if (T->isReferenceType())
1454  return true;
1455  } else {
1456  T = T.getNonReferenceType();
1457  }
1458 
1459  // The nonnull attribute, and other similar attributes, can be applied to a
1460  // transparent union that contains a pointer type.
1461  if (const RecordType *UT = T->getAsUnionType()) {
1462  if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1463  RecordDecl *UD = UT->getDecl();
1464  for (const auto *I : UD->fields()) {
1465  QualType QT = I->getType();
1466  if (QT->isAnyPointerType() || QT->isBlockPointerType())
1467  return true;
1468  }
1469  }
1470  }
1471 
1472  return T->isAnyPointerType() || T->isBlockPointerType();
1473 }
1474 
1475 static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1476  SourceRange AttrParmRange,
1477  SourceRange TypeRange,
1478  bool isReturnValue = false) {
1479  if (!S.isValidPointerAttrType(T)) {
1480  if (isReturnValue)
1481  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1482  << AL << AttrParmRange << TypeRange;
1483  else
1484  S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1485  << AL << AttrParmRange << TypeRange << 0;
1486  return false;
1487  }
1488  return true;
1489 }
1490 
1491 static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1492  SmallVector<ParamIdx, 8> NonNullArgs;
1493  for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1494  Expr *Ex = AL.getArgAsExpr(I);
1495  ParamIdx Idx;
1496  if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1497  return;
1498 
1499  // Is the function argument a pointer type?
1500  if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1502  S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1503  Ex->getSourceRange(),
1505  continue;
1506 
1507  NonNullArgs.push_back(Idx);
1508  }
1509 
1510  // If no arguments were specified to __attribute__((nonnull)) then all pointer
1511  // arguments have a nonnull attribute; warn if there aren't any. Skip this
1512  // check if the attribute came from a macro expansion or a template
1513  // instantiation.
1514  if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1515  !S.inTemplateInstantiation()) {
1516  bool AnyPointers = isFunctionOrMethodVariadic(D);
1517  for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1518  I != E && !AnyPointers; ++I) {
1520  if (T->isDependentType() || S.isValidPointerAttrType(T))
1521  AnyPointers = true;
1522  }
1523 
1524  if (!AnyPointers)
1525  S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1526  }
1527 
1528  ParamIdx *Start = NonNullArgs.data();
1529  unsigned Size = NonNullArgs.size();
1530  llvm::array_pod_sort(Start, Start + Size);
1531  D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
1532 }
1533 
1535  const ParsedAttr &AL) {
1536  if (AL.getNumArgs() > 0) {
1537  if (D->getFunctionType()) {
1538  handleNonNullAttr(S, D, AL);
1539  } else {
1540  S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1541  << D->getSourceRange();
1542  }
1543  return;
1544  }
1545 
1546  // Is the argument a pointer type?
1547  if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1548  D->getSourceRange()))
1549  return;
1550 
1551  D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
1552 }
1553 
1554 static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1555  QualType ResultType = getFunctionOrMethodResultType(D);
1557  if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1558  /* isReturnValue */ true))
1559  return;
1560 
1561  D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
1562 }
1563 
1564 static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1565  if (D->isInvalidDecl())
1566  return;
1567 
1568  // noescape only applies to pointer types.
1569  QualType T = cast<ParmVarDecl>(D)->getType();
1570  if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1571  S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1572  << AL << AL.getRange() << 0;
1573  return;
1574  }
1575 
1576  D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL));
1577 }
1578 
1579 static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1580  Expr *E = AL.getArgAsExpr(0),
1581  *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1582  S.AddAssumeAlignedAttr(D, AL, E, OE);
1583 }
1584 
1585 static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1586  S.AddAllocAlignAttr(D, AL, AL.getArgAsExpr(0));
1587 }
1588 
1590  Expr *OE) {
1591  QualType ResultType = getFunctionOrMethodResultType(D);
1593 
1594  AssumeAlignedAttr TmpAttr(Context, CI, E, OE);
1595  SourceLocation AttrLoc = TmpAttr.getLocation();
1596 
1597  if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1598  Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1599  << &TmpAttr << TmpAttr.getRange() << SR;
1600  return;
1601  }
1602 
1603  if (!E->isValueDependent()) {
1605  if (!(I = E->getIntegerConstantExpr(Context))) {
1606  if (OE)
1607  Diag(AttrLoc, diag::err_attribute_argument_n_type)
1608  << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1609  << E->getSourceRange();
1610  else
1611  Diag(AttrLoc, diag::err_attribute_argument_type)
1612  << &TmpAttr << AANT_ArgumentIntegerConstant
1613  << E->getSourceRange();
1614  return;
1615  }
1616 
1617  if (!I->isPowerOf2()) {
1618  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1619  << E->getSourceRange();
1620  return;
1621  }
1622 
1623  if (*I > Sema::MaximumAlignment)
1624  Diag(CI.getLoc(), diag::warn_assume_aligned_too_great)
1625  << CI.getRange() << Sema::MaximumAlignment;
1626  }
1627 
1628  if (OE && !OE->isValueDependent() && !OE->isIntegerConstantExpr(Context)) {
1629  Diag(AttrLoc, diag::err_attribute_argument_n_type)
1630  << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1631  << OE->getSourceRange();
1632  return;
1633  }
1634 
1635  D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
1636 }
1637 
1639  Expr *ParamExpr) {
1640  QualType ResultType = getFunctionOrMethodResultType(D);
1641 
1642  AllocAlignAttr TmpAttr(Context, CI, ParamIdx());
1643  SourceLocation AttrLoc = CI.getLoc();
1644 
1645  if (!ResultType->isDependentType() &&
1646  !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1647  Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1648  << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
1649  return;
1650  }
1651 
1652  ParamIdx Idx;
1653  const auto *FuncDecl = cast<FunctionDecl>(D);
1654  if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1655  /*AttrArgNum=*/1, ParamExpr, Idx))
1656  return;
1657 
1659  if (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
1660  !Ty->isAlignValT()) {
1661  Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1662  << &TmpAttr
1663  << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1664  return;
1665  }
1666 
1667  D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx));
1668 }
1669 
1670 /// Check if \p AssumptionStr is a known assumption and warn if not.
1672  StringRef AssumptionStr) {
1673  if (llvm::KnownAssumptionStrings.count(AssumptionStr))
1674  return;
1675 
1676  unsigned BestEditDistance = 3;
1677  StringRef Suggestion;
1678  for (const auto &KnownAssumptionIt : llvm::KnownAssumptionStrings) {
1679  unsigned EditDistance =
1680  AssumptionStr.edit_distance(KnownAssumptionIt.getKey());
1681  if (EditDistance < BestEditDistance) {
1682  Suggestion = KnownAssumptionIt.getKey();
1683  BestEditDistance = EditDistance;
1684  }
1685  }
1686 
1687  if (!Suggestion.empty())
1688  S.Diag(Loc, diag::warn_assume_attribute_string_unknown_suggested)
1689  << AssumptionStr << Suggestion;
1690  else
1691  S.Diag(Loc, diag::warn_assume_attribute_string_unknown) << AssumptionStr;
1692 }
1693 
1694 static void handleAssumumptionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1695  // Handle the case where the attribute has a text message.
1696  StringRef Str;
1697  SourceLocation AttrStrLoc;
1698  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &AttrStrLoc))
1699  return;
1700 
1701  checkAssumptionAttr(S, AttrStrLoc, Str);
1702 
1703  D->addAttr(::new (S.Context) AssumptionAttr(S.Context, AL, Str));
1704 }
1705 
1706 /// Normalize the attribute, __foo__ becomes foo.
1707 /// Returns true if normalization was applied.
1708 static bool normalizeName(StringRef &AttrName) {
1709  if (AttrName.size() > 4 && AttrName.startswith("__") &&
1710  AttrName.endswith("__")) {
1711  AttrName = AttrName.drop_front(2).drop_back(2);
1712  return true;
1713  }
1714  return false;
1715 }
1716 
1717 static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1718  // This attribute must be applied to a function declaration. The first
1719  // argument to the attribute must be an identifier, the name of the resource,
1720  // for example: malloc. The following arguments must be argument indexes, the
1721  // arguments must be of integer type for Returns, otherwise of pointer type.
1722  // The difference between Holds and Takes is that a pointer may still be used
1723  // after being held. free() should be __attribute((ownership_takes)), whereas
1724  // a list append function may well be __attribute((ownership_holds)).
1725 
1726  if (!AL.isArgIdent(0)) {
1727  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1728  << AL << 1 << AANT_ArgumentIdentifier;
1729  return;
1730  }
1731 
1732  // Figure out our Kind.
1733  OwnershipAttr::OwnershipKind K =
1734  OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
1735 
1736  // Check arguments.
1737  switch (K) {
1738  case OwnershipAttr::Takes:
1739  case OwnershipAttr::Holds:
1740  if (AL.getNumArgs() < 2) {
1741  S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1742  return;
1743  }
1744  break;
1745  case OwnershipAttr::Returns:
1746  if (AL.getNumArgs() > 2) {
1747  S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1748  return;
1749  }
1750  break;
1751  }
1752 
1754 
1755  StringRef ModuleName = Module->getName();
1756  if (normalizeName(ModuleName)) {
1757  Module = &S.PP.getIdentifierTable().get(ModuleName);
1758  }
1759 
1760  SmallVector<ParamIdx, 8> OwnershipArgs;
1761  for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1762  Expr *Ex = AL.getArgAsExpr(i);
1763  ParamIdx Idx;
1764  if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1765  return;
1766 
1767  // Is the function argument a pointer type?
1769  int Err = -1; // No error
1770  switch (K) {
1771  case OwnershipAttr::Takes:
1772  case OwnershipAttr::Holds:
1773  if (!T->isAnyPointerType() && !T->isBlockPointerType())
1774  Err = 0;
1775  break;
1776  case OwnershipAttr::Returns:
1777  if (!T->isIntegerType())
1778  Err = 1;
1779  break;
1780  }
1781  if (-1 != Err) {
1782  S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1783  << Ex->getSourceRange();
1784  return;
1785  }
1786 
1787  // Check we don't have a conflict with another ownership attribute.
1788  for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1789  // Cannot have two ownership attributes of different kinds for the same
1790  // index.
1791  if (I->getOwnKind() != K && I->args_end() !=
1792  std::find(I->args_begin(), I->args_end(), Idx)) {
1793  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I;
1794  return;
1795  } else if (K == OwnershipAttr::Returns &&
1796  I->getOwnKind() == OwnershipAttr::Returns) {
1797  // A returns attribute conflicts with any other returns attribute using
1798  // a different index.
1799  if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1800  S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1801  << I->args_begin()->getSourceIndex();
1802  if (I->args_size())
1803  S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1804  << Idx.getSourceIndex() << Ex->getSourceRange();
1805  return;
1806  }
1807  }
1808  }
1809  OwnershipArgs.push_back(Idx);
1810  }
1811 
1812  ParamIdx *Start = OwnershipArgs.data();
1813  unsigned Size = OwnershipArgs.size();
1814  llvm::array_pod_sort(Start, Start + Size);
1815  D->addAttr(::new (S.Context)
1816  OwnershipAttr(S.Context, AL, Module, Start, Size));
1817 }
1818 
1819 static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1820  // Check the attribute arguments.
1821  if (AL.getNumArgs() > 1) {
1822  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1823  return;
1824  }
1825 
1826  // gcc rejects
1827  // class c {
1828  // static int a __attribute__((weakref ("v2")));
1829  // static int b() __attribute__((weakref ("f3")));
1830  // };
1831  // and ignores the attributes of
1832  // void f(void) {
1833  // static int a __attribute__((weakref ("v2")));
1834  // }
1835  // we reject them
1836  const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1837  if (!Ctx->isFileContext()) {
1838  S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1839  << cast<NamedDecl>(D);
1840  return;
1841  }
1842 
1843  // The GCC manual says
1844  //
1845  // At present, a declaration to which `weakref' is attached can only
1846  // be `static'.
1847  //
1848  // It also says
1849  //
1850  // Without a TARGET,
1851  // given as an argument to `weakref' or to `alias', `weakref' is
1852  // equivalent to `weak'.
1853  //
1854  // gcc 4.4.1 will accept
1855  // int a7 __attribute__((weakref));
1856  // as
1857  // int a7 __attribute__((weak));
1858  // This looks like a bug in gcc. We reject that for now. We should revisit
1859  // it if this behaviour is actually used.
1860 
1861  // GCC rejects
1862  // static ((alias ("y"), weakref)).
1863  // Should we? How to check that weakref is before or after alias?
1864 
1865  // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1866  // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1867  // StringRef parameter it was given anyway.
1868  StringRef Str;
1869  if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1870  // GCC will accept anything as the argument of weakref. Should we
1871  // check for an existing decl?
1872  D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1873 
1874  D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
1875 }
1876 
1877 static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1878  StringRef Str;
1879  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1880  return;
1881 
1882  // Aliases should be on declarations, not definitions.
1883  const auto *FD = cast<FunctionDecl>(D);
1884  if (FD->isThisDeclarationADefinition()) {
1885  S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1886  return;
1887  }
1888 
1889  D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
1890 }
1891 
1892 static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1893  StringRef Str;
1894  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1895  return;
1896 
1897  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1898  S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
1899  return;
1900  }
1901  if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1902  S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
1903  }
1904 
1905  // Aliases should be on declarations, not definitions.
1906  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1907  if (FD->isThisDeclarationADefinition()) {
1908  S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
1909  return;
1910  }
1911  } else {
1912  const auto *VD = cast<VarDecl>(D);
1913  if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1914  S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
1915  return;
1916  }
1917  }
1918 
1919  // Mark target used to prevent unneeded-internal-declaration warnings.
1920  if (!S.LangOpts.CPlusPlus) {
1921  // FIXME: demangle Str for C++, as the attribute refers to the mangled
1922  // linkage name, not the pre-mangled identifier.
1923  const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
1924  LookupResult LR(S, target, Sema::LookupOrdinaryName);
1926  for (NamedDecl *ND : LR)
1927  ND->markUsed(S.Context);
1928  }
1929 
1930  D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1931 }
1932 
1933 static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1934  StringRef Model;
1935  SourceLocation LiteralLoc;
1936  // Check that it is a string.
1937  if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
1938  return;
1939 
1940  // Check that the value.
1941  if (Model != "global-dynamic" && Model != "local-dynamic"
1942  && Model != "initial-exec" && Model != "local-exec") {
1943  S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1944  return;
1945  }
1946 
1947  if (S.Context.getTargetInfo().getTriple().isOSAIX() &&
1948  Model != "global-dynamic") {
1949  S.Diag(LiteralLoc, diag::err_aix_attr_unsupported_tls_model) << Model;
1950  return;
1951  }
1952 
1953  D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model));
1954 }
1955 
1956 static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1957  QualType ResultType = getFunctionOrMethodResultType(D);
1958  if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1959  D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
1960  return;
1961  }
1962 
1963  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1965 }
1966 
1967 static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1968  FunctionDecl *FD = cast<FunctionDecl>(D);
1969 
1970  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
1971  if (MD->getParent()->isLambda()) {
1972  S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
1973  return;
1974  }
1975  }
1976 
1977  if (!AL.checkAtLeastNumArgs(S, 1))
1978  return;
1979 
1981  for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
1982  if (!AL.isArgIdent(ArgNo)) {
1983  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1984  << AL << AANT_ArgumentIdentifier;
1985  return;
1986  }
1987 
1988  IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
1989  StringRef CPUName = CPUArg->Ident->getName().trim();
1990 
1992  S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
1993  << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
1994  return;
1995  }
1996 
1997  const TargetInfo &Target = S.Context.getTargetInfo();
1998  if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
1999  return Target.CPUSpecificManglingCharacter(CPUName) ==
2000  Target.CPUSpecificManglingCharacter(Cur->getName());
2001  })) {
2002  S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
2003  return;
2004  }
2005  CPUs.push_back(CPUArg->Ident);
2006  }
2007 
2008  FD->setIsMultiVersion(true);
2009  if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
2010  D->addAttr(::new (S.Context)
2011  CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2012  else
2013  D->addAttr(::new (S.Context)
2014  CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2015 }
2016 
2017 static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2018  if (S.LangOpts.CPlusPlus) {
2019  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
2020  << AL << AttributeLangSupport::Cpp;
2021  return;
2022  }
2023 
2024  D->addAttr(::new (S.Context) CommonAttr(S.Context, AL));
2025 }
2026 
2027 static void handleCmseNSEntryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2028  if (S.LangOpts.CPlusPlus && !D->getDeclContext()->isExternCContext()) {
2029  S.Diag(AL.getLoc(), diag::err_attribute_not_clinkage) << AL;
2030  return;
2031  }
2032 
2033  const auto *FD = cast<FunctionDecl>(D);
2034  if (!FD->isExternallyVisible()) {
2035  S.Diag(AL.getLoc(), diag::warn_attribute_cmse_entry_static);
2036  return;
2037  }
2038 
2039  D->addAttr(::new (S.Context) CmseNSEntryAttr(S.Context, AL));
2040 }
2041 
2042 static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2043  if (AL.isDeclspecAttribute()) {
2044  const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2045  const auto &Arch = Triple.getArch();
2046  if (Arch != llvm::Triple::x86 &&
2047  (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2048  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2049  << AL << Triple.getArchName();
2050  return;
2051  }
2052  }
2053 
2054  D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
2055 }
2056 
2057 static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2058  if (hasDeclarator(D)) return;
2059 
2060  if (!isa<ObjCMethodDecl>(D)) {
2061  S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2062  << Attrs << ExpectedFunctionOrMethod;
2063  return;
2064  }
2065 
2066  D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
2067 }
2068 
2069 static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2070  if (!S.getLangOpts().CFProtectionBranch)
2071  S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2072  else
2073  handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2074 }
2075 
2076 bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2077  if (!Attrs.checkExactlyNumArgs(*this, 0)) {
2078  Attrs.setInvalid();
2079  return true;
2080  }
2081 
2082  return false;
2083 }
2084 
2086  // Check whether the attribute is valid on the current target.
2087  if (!AL.existsInTarget(Context.getTargetInfo())) {
2088  Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2089  << AL << AL.getRange();
2090  AL.setInvalid();
2091  return true;
2092  }
2093 
2094  return false;
2095 }
2096 
2097 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2098 
2099  // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2100  // because 'analyzer_noreturn' does not impact the type.
2101  if (!isFunctionOrMethodOrBlock(D)) {
2102  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2103  if (!VD || (!VD->getType()->isBlockPointerType() &&
2104  !VD->getType()->isFunctionPointerType())) {
2106  ? diag::err_attribute_wrong_decl_type
2107  : diag::warn_attribute_wrong_decl_type)
2109  return;
2110  }
2111  }
2112 
2113  D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
2114 }
2115 
2116 // PS3 PPU-specific.
2117 static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2118  /*
2119  Returning a Vector Class in Registers
2120 
2121  According to the PPU ABI specifications, a class with a single member of
2122  vector type is returned in memory when used as the return value of a
2123  function.
2124  This results in inefficient code when implementing vector classes. To return
2125  the value in a single vector register, add the vecreturn attribute to the
2126  class definition. This attribute is also applicable to struct types.
2127 
2128  Example:
2129 
2130  struct Vector
2131  {
2132  __vector float xyzw;
2133  } __attribute__((vecreturn));
2134 
2135  Vector Add(Vector lhs, Vector rhs)
2136  {
2137  Vector result;
2138  result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2139  return result; // This will be returned in a register
2140  }
2141  */
2142  if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2143  S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2144  return;
2145  }
2146 
2147  const auto *R = cast<RecordDecl>(D);
2148  int count = 0;
2149 
2150  if (!isa<CXXRecordDecl>(R)) {
2151  S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2152  return;
2153  }
2154 
2155  if (!cast<CXXRecordDecl>(R)->isPOD()) {
2156  S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2157  return;
2158  }
2159 
2160  for (const auto *I : R->fields()) {
2161  if ((count == 1) || !I->getType()->isVectorType()) {
2162  S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2163  return;
2164  }
2165  count++;
2166  }
2167 
2168  D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
2169 }
2170 
2172  const ParsedAttr &AL) {
2173  if (isa<ParmVarDecl>(D)) {
2174  // [[carries_dependency]] can only be applied to a parameter if it is a
2175  // parameter of a function declaration or lambda.
2177  S.Diag(AL.getLoc(),
2178  diag::err_carries_dependency_param_not_function_decl);
2179  return;
2180  }
2181  }
2182 
2183  D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
2184 }
2185 
2186 static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2187  bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2188 
2189  // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2190  // about using it as an extension.
2191  if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2192  S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2193 
2194  D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
2195 }
2196 
2197 static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2198  uint32_t priority = ConstructorAttr::DefaultPriority;
2199  if (AL.getNumArgs() &&
2200  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2201  return;
2202 
2203  D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
2204 }
2205 
2206 static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2207  uint32_t priority = DestructorAttr::DefaultPriority;
2208  if (AL.getNumArgs() &&
2209  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2210  return;
2211 
2212  D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
2213 }
2214 
2215 template <typename AttrTy>
2216 static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2217  // Handle the case where the attribute has a text message.
2218  StringRef Str;
2219  if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2220  return;
2221 
2222  D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str));
2223 }
2224 
2226  const ParsedAttr &AL) {
2227  if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2228  S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2229  << AL << AL.getRange();
2230  return;
2231  }
2232 
2233  D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL));
2234 }
2235 
2237  IdentifierInfo *Platform,
2238  VersionTuple Introduced,
2239  VersionTuple Deprecated,
2240  VersionTuple Obsoleted) {
2241  StringRef PlatformName
2242  = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2243  if (PlatformName.empty())
2244  PlatformName = Platform->getName();
2245 
2246  // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2247  // of these steps are needed).
2248  if (!Introduced.empty() && !Deprecated.empty() &&
2249  !(Introduced <= Deprecated)) {
2250  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2251  << 1 << PlatformName << Deprecated.getAsString()
2252  << 0 << Introduced.getAsString();
2253  return true;
2254  }
2255 
2256  if (!Introduced.empty() && !Obsoleted.empty() &&
2257  !(Introduced <= Obsoleted)) {
2258  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2259  << 2 << PlatformName << Obsoleted.getAsString()
2260  << 0 << Introduced.getAsString();
2261  return true;
2262  }
2263 
2264  if (!Deprecated.empty() && !Obsoleted.empty() &&
2265  !(Deprecated <= Obsoleted)) {
2266  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2267  << 2 << PlatformName << Obsoleted.getAsString()
2268  << 1 << Deprecated.getAsString();
2269  return true;
2270  }
2271 
2272  return false;
2273 }
2274 
2275 /// Check whether the two versions match.
2276 ///
2277 /// If either version tuple is empty, then they are assumed to match. If
2278 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2279 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2280  bool BeforeIsOkay) {
2281  if (X.empty() || Y.empty())
2282  return true;
2283 
2284  if (X == Y)
2285  return true;
2286 
2287  if (BeforeIsOkay && X < Y)
2288  return true;
2289 
2290  return false;
2291 }
2292 
2294  NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
2295  bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2296  VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2297  bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2298  int Priority) {
2299  VersionTuple MergedIntroduced = Introduced;
2300  VersionTuple MergedDeprecated = Deprecated;
2301  VersionTuple MergedObsoleted = Obsoleted;
2302  bool FoundAny = false;
2303  bool OverrideOrImpl = false;
2304  switch (AMK) {
2305  case AMK_None:
2306  case AMK_Redeclaration:
2307  OverrideOrImpl = false;
2308  break;
2309 
2310  case AMK_Override:
2311  case AMK_ProtocolImplementation:
2312  case AMK_OptionalProtocolImplementation:
2313  OverrideOrImpl = true;
2314  break;
2315  }
2316 
2317  if (D->hasAttrs()) {
2318  AttrVec &Attrs = D->getAttrs();
2319  for (unsigned i = 0, e = Attrs.size(); i != e;) {
2320  const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2321  if (!OldAA) {
2322  ++i;
2323  continue;
2324  }
2325 
2326  IdentifierInfo *OldPlatform = OldAA->getPlatform();
2327  if (OldPlatform != Platform) {
2328  ++i;
2329  continue;
2330  }
2331 
2332  // If there is an existing availability attribute for this platform that
2333  // has a lower priority use the existing one and discard the new
2334  // attribute.
2335  if (OldAA->getPriority() < Priority)
2336  return nullptr;
2337 
2338  // If there is an existing attribute for this platform that has a higher
2339  // priority than the new attribute then erase the old one and continue
2340  // processing the attributes.
2341  if (OldAA->getPriority() > Priority) {
2342  Attrs.erase(Attrs.begin() + i);
2343  --e;
2344  continue;
2345  }
2346 
2347  FoundAny = true;
2348  VersionTuple OldIntroduced = OldAA->getIntroduced();
2349  VersionTuple OldDeprecated = OldAA->getDeprecated();
2350  VersionTuple OldObsoleted = OldAA->getObsoleted();
2351  bool OldIsUnavailable = OldAA->getUnavailable();
2352 
2353  if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2354  !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2355  !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2356  !(OldIsUnavailable == IsUnavailable ||
2357  (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2358  if (OverrideOrImpl) {
2359  int Which = -1;
2360  VersionTuple FirstVersion;
2361  VersionTuple SecondVersion;
2362  if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2363  Which = 0;
2364  FirstVersion = OldIntroduced;
2365  SecondVersion = Introduced;
2366  } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2367  Which = 1;
2368  FirstVersion = Deprecated;
2369  SecondVersion = OldDeprecated;
2370  } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2371  Which = 2;
2372  FirstVersion = Obsoleted;
2373  SecondVersion = OldObsoleted;
2374  }
2375 
2376  if (Which == -1) {
2377  Diag(OldAA->getLocation(),
2378  diag::warn_mismatched_availability_override_unavail)
2379  << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2380  << (AMK == AMK_Override);
2381  } else if (Which != 1 && AMK == AMK_OptionalProtocolImplementation) {
2382  // Allow different 'introduced' / 'obsoleted' availability versions
2383  // on a method that implements an optional protocol requirement. It
2384  // makes less sense to allow this for 'deprecated' as the user can't
2385  // see if the method is 'deprecated' as 'respondsToSelector' will
2386  // still return true when the method is deprecated.
2387  ++i;
2388  continue;
2389  } else {
2390  Diag(OldAA->getLocation(),
2391  diag::warn_mismatched_availability_override)
2392  << Which
2393  << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2394  << FirstVersion.getAsString() << SecondVersion.getAsString()
2395  << (AMK == AMK_Override);
2396  }
2397  if (AMK == AMK_Override)
2398  Diag(CI.getLoc(), diag::note_overridden_method);
2399  else
2400  Diag(CI.getLoc(), diag::note_protocol_method);
2401  } else {
2402  Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2403  Diag(CI.getLoc(), diag::note_previous_attribute);
2404  }
2405 
2406  Attrs.erase(Attrs.begin() + i);
2407  --e;
2408  continue;
2409  }
2410 
2411  VersionTuple MergedIntroduced2 = MergedIntroduced;
2412  VersionTuple MergedDeprecated2 = MergedDeprecated;
2413  VersionTuple MergedObsoleted2 = MergedObsoleted;
2414 
2415  if (MergedIntroduced2.empty())
2416  MergedIntroduced2 = OldIntroduced;
2417  if (MergedDeprecated2.empty())
2418  MergedDeprecated2 = OldDeprecated;
2419  if (MergedObsoleted2.empty())
2420  MergedObsoleted2 = OldObsoleted;
2421 
2422  if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2423  MergedIntroduced2, MergedDeprecated2,
2424  MergedObsoleted2)) {
2425  Attrs.erase(Attrs.begin() + i);
2426  --e;
2427  continue;
2428  }
2429 
2430  MergedIntroduced = MergedIntroduced2;
2431  MergedDeprecated = MergedDeprecated2;
2432  MergedObsoleted = MergedObsoleted2;
2433  ++i;
2434  }
2435  }
2436 
2437  if (FoundAny &&
2438  MergedIntroduced == Introduced &&
2439  MergedDeprecated == Deprecated &&
2440  MergedObsoleted == Obsoleted)
2441  return nullptr;
2442 
2443  // Only create a new attribute if !OverrideOrImpl, but we want to do
2444  // the checking.
2445  if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced,
2446  MergedDeprecated, MergedObsoleted) &&
2447  !OverrideOrImpl) {
2448  auto *Avail = ::new (Context) AvailabilityAttr(
2449  Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2450  Message, IsStrict, Replacement, Priority);
2451  Avail->setImplicit(Implicit);
2452  return Avail;
2453  }
2454  return nullptr;
2455 }
2456 
2457 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2458  if (isa<UsingDecl, UnresolvedUsingTypenameDecl, UnresolvedUsingValueDecl>(
2459  D)) {
2460  S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
2461  << AL;
2462  return;
2463  }
2464 
2465  if (!AL.checkExactlyNumArgs(S, 1))
2466  return;
2467  IdentifierLoc *Platform = AL.getArgAsIdent(0);
2468 
2469  IdentifierInfo *II = Platform->Ident;
2470  if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2471  S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2472  << Platform->Ident;
2473 
2474  auto *ND = dyn_cast<NamedDecl>(D);
2475  if (!ND) // We warned about this already, so just return.
2476  return;
2477 
2481  bool IsUnavailable = AL.getUnavailableLoc().isValid();
2482  bool IsStrict = AL.getStrictLoc().isValid();
2483  StringRef Str;
2484  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2485  Str = SE->getString();
2486  StringRef Replacement;
2487  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2488  Replacement = SE->getString();
2489 
2490  if (II->isStr("swift")) {
2491  if (Introduced.isValid() || Obsoleted.isValid() ||
2492  (!IsUnavailable && !Deprecated.isValid())) {
2493  S.Diag(AL.getLoc(),
2494  diag::warn_availability_swift_unavailable_deprecated_only);
2495  return;
2496  }
2497  }
2498 
2499  int PriorityModifier = AL.isPragmaClangAttribute()
2502  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2503  ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2504  Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2505  Sema::AMK_None, PriorityModifier);
2506  if (NewAttr)
2507  D->addAttr(NewAttr);
2508 
2509  // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2510  // matches before the start of the watchOS platform.
2511  if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2512  IdentifierInfo *NewII = nullptr;
2513  if (II->getName() == "ios")
2514  NewII = &S.Context.Idents.get("watchos");
2515  else if (II->getName() == "ios_app_extension")
2516  NewII = &S.Context.Idents.get("watchos_app_extension");
2517 
2518  if (NewII) {
2519  auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2520  if (Version.empty())
2521  return Version;
2522  auto Major = Version.getMajor();
2523  auto NewMajor = Major >= 9 ? Major - 7 : 0;
2524  if (NewMajor >= 2) {
2525  if (Version.getMinor().hasValue()) {
2526  if (Version.getSubminor().hasValue())
2527  return VersionTuple(NewMajor, Version.getMinor().getValue(),
2528  Version.getSubminor().getValue());
2529  else
2530  return VersionTuple(NewMajor, Version.getMinor().getValue());
2531  }
2532  return VersionTuple(NewMajor);
2533  }
2534 
2535  return VersionTuple(2, 0);
2536  };
2537 
2538  auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2539  auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2540  auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2541 
2542  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2543  ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2544  NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2546  PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2547  if (NewAttr)
2548  D->addAttr(NewAttr);
2549  }
2550  } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2551  // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2552  // matches before the start of the tvOS platform.
2553  IdentifierInfo *NewII = nullptr;
2554  if (II->getName() == "ios")
2555  NewII = &S.Context.Idents.get("tvos");
2556  else if (II->getName() == "ios_app_extension")
2557  NewII = &S.Context.Idents.get("tvos_app_extension");
2558 
2559  if (NewII) {
2560  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2561  ND, AL, NewII, true /*Implicit*/, Introduced.Version,
2562  Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict,
2563  Replacement, Sema::AMK_None,
2564  PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2565  if (NewAttr)
2566  D->addAttr(NewAttr);
2567  }
2568  } else if (S.Context.getTargetInfo().getTriple().getOS() ==
2569  llvm::Triple::IOS &&
2570  S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) {
2571  auto GetSDKInfo = [&]() {
2573  "macOS");
2574  };
2575 
2576  // Transcribe "ios" to "maccatalyst" (and add a new attribute).
2577  IdentifierInfo *NewII = nullptr;
2578  if (II->getName() == "ios")
2579  NewII = &S.Context.Idents.get("maccatalyst");
2580  else if (II->getName() == "ios_app_extension")
2581  NewII = &S.Context.Idents.get("maccatalyst_app_extension");
2582  if (NewII) {
2583  auto MinMacCatalystVersion = [](const VersionTuple &V) {
2584  if (V.empty())
2585  return V;
2586  if (V.getMajor() < 13 ||
2587  (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1))
2588  return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1.
2589  return V;
2590  };
2591  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2592  ND, AL.getRange(), NewII, true /*Implicit*/,
2593  MinMacCatalystVersion(Introduced.Version),
2594  MinMacCatalystVersion(Deprecated.Version),
2595  MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str,
2596  IsStrict, Replacement, Sema::AMK_None,
2597  PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2598  if (NewAttr)
2599  D->addAttr(NewAttr);
2600  } else if (II->getName() == "macos" && GetSDKInfo() &&
2601  (!Introduced.Version.empty() || !Deprecated.Version.empty() ||
2602  !Obsoleted.Version.empty())) {
2603  if (const auto *MacOStoMacCatalystMapping =
2604  GetSDKInfo()->getVersionMapping(
2606  // Infer Mac Catalyst availability from the macOS availability attribute
2607  // if it has versioned availability. Don't infer 'unavailable'. This
2608  // inferred availability has lower priority than the other availability
2609  // attributes that are inferred from 'ios'.
2610  NewII = &S.Context.Idents.get("maccatalyst");
2611  auto RemapMacOSVersion =
2612  [&](const VersionTuple &V) -> Optional<VersionTuple> {
2613  if (V.empty())
2614  return None;
2615  // API_TO_BE_DEPRECATED is 100000.
2616  if (V.getMajor() == 100000)
2617  return VersionTuple(100000);
2618  // The minimum iosmac version is 13.1
2619  return MacOStoMacCatalystMapping->map(V, VersionTuple(13, 1), None);
2620  };
2621  Optional<VersionTuple> NewIntroduced =
2622  RemapMacOSVersion(Introduced.Version),
2623  NewDeprecated =
2624  RemapMacOSVersion(Deprecated.Version),
2625  NewObsoleted =
2626  RemapMacOSVersion(Obsoleted.Version);
2627  if (NewIntroduced || NewDeprecated || NewObsoleted) {
2628  auto VersionOrEmptyVersion =
2629  [](const Optional<VersionTuple> &V) -> VersionTuple {
2630  return V ? *V : VersionTuple();
2631  };
2632  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2633  ND, AL.getRange(), NewII, true /*Implicit*/,
2634  VersionOrEmptyVersion(NewIntroduced),
2635  VersionOrEmptyVersion(NewDeprecated),
2636  VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str,
2637  IsStrict, Replacement, Sema::AMK_None,
2638  PriorityModifier + Sema::AP_InferredFromOtherPlatform +
2640  if (NewAttr)
2641  D->addAttr(NewAttr);
2642  }
2643  }
2644  }
2645  }
2646 }
2647 
2649  const ParsedAttr &AL) {
2650  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 3))
2651  return;
2652 
2653  StringRef Language;
2654  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2655  Language = SE->getString();
2656  StringRef DefinedIn;
2657  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2658  DefinedIn = SE->getString();
2659  bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2660 
2661  D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2662  S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration));
2663 }
2664 
2665 template <class T>
2666 static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
2667  typename T::VisibilityType value) {
2668  T *existingAttr = D->getAttr<T>();
2669  if (existingAttr) {
2670  typename T::VisibilityType existingValue = existingAttr->getVisibility();
2671  if (existingValue == value)
2672  return nullptr;
2673  S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2674  S.Diag(CI.getLoc(), diag::note_previous_attribute);
2675  D->dropAttr<T>();
2676  }
2677  return ::new (S.Context) T(S.Context, CI, value);
2678 }
2679 
2680 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
2681  const AttributeCommonInfo &CI,
2682  VisibilityAttr::VisibilityType Vis) {
2683  return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
2684 }
2685 
2686 TypeVisibilityAttr *
2688  TypeVisibilityAttr::VisibilityType Vis) {
2689  return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
2690 }
2691 
2692 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2693  bool isTypeVisibility) {
2694  // Visibility attributes don't mean anything on a typedef.
2695  if (isa<TypedefNameDecl>(D)) {
2696  S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2697  return;
2698  }
2699 
2700  // 'type_visibility' can only go on a type or namespace.
2701  if (isTypeVisibility &&
2702  !(isa<TagDecl>(D) ||
2703  isa<ObjCInterfaceDecl>(D) ||
2704  isa<NamespaceDecl>(D))) {
2705  S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2706  << AL << ExpectedTypeOrNamespace;
2707  return;
2708  }
2709 
2710  // Check that the argument is a string literal.
2711  StringRef TypeStr;
2712  SourceLocation LiteralLoc;
2713  if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2714  return;
2715 
2716  VisibilityAttr::VisibilityType type;
2717  if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2718  S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2719  << TypeStr;
2720  return;
2721  }
2722 
2723  // Complain about attempts to use protected visibility on targets
2724  // (like Darwin) that don't support it.
2725  if (type == VisibilityAttr::Protected &&
2727  S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2728  type = VisibilityAttr::Default;
2729  }
2730 
2731  Attr *newAttr;
2732  if (isTypeVisibility) {
2733  newAttr = S.mergeTypeVisibilityAttr(
2734  D, AL, (TypeVisibilityAttr::VisibilityType)type);
2735  } else {
2736  newAttr = S.mergeVisibilityAttr(D, AL, type);
2737  }
2738  if (newAttr)
2739  D->addAttr(newAttr);
2740 }
2741 
2742 static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2743  // objc_direct cannot be set on methods declared in the context of a protocol
2744  if (isa<ObjCProtocolDecl>(D->getDeclContext())) {
2745  S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
2746  return;
2747  }
2748 
2750  handleSimpleAttribute<ObjCDirectAttr>(S, D, AL);
2751  } else {
2752  S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2753  }
2754 }
2755 
2757  const ParsedAttr &AL) {
2759  handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
2760  } else {
2761  S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2762  }
2763 }
2764 
2765 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2766  const auto *M = cast<ObjCMethodDecl>(D);
2767  if (!AL.isArgIdent(0)) {
2768  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2769  << AL << 1 << AANT_ArgumentIdentifier;
2770  return;
2771  }
2772 
2773  IdentifierLoc *IL = AL.getArgAsIdent(0);
2774  ObjCMethodFamilyAttr::FamilyKind F;
2775  if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2776  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2777  return;
2778  }
2779 
2780  if (F == ObjCMethodFamilyAttr::OMF_init &&
2781  !M->getReturnType()->isObjCObjectPointerType()) {
2782  S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2783  << M->getReturnType();
2784  // Ignore the attribute.
2785  return;
2786  }
2787 
2788  D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F));
2789 }
2790 
2791 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2792  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2793  QualType T = TD->getUnderlyingType();
2794  if (!T->isCARCBridgableType()) {
2795  S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2796  return;
2797  }
2798  }
2799  else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2800  QualType T = PD->getType();
2801  if (!T->isCARCBridgableType()) {
2802  S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2803  return;
2804  }
2805  }
2806  else {
2807  // It is okay to include this attribute on properties, e.g.:
2808  //
2809  // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2810  //
2811  // In this case it follows tradition and suppresses an error in the above
2812  // case.
2813  S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2814  }
2815  D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL));
2816 }
2817 
2818 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
2819  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2820  QualType T = TD->getUnderlyingType();
2821  if (!T->isObjCObjectPointerType()) {
2822  S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2823  return;
2824  }
2825  } else {
2826  S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2827  return;
2828  }
2829  D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL));
2830 }
2831 
2832 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2833  if (!AL.isArgIdent(0)) {
2834  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2835  << AL << 1 << AANT_ArgumentIdentifier;
2836  return;
2837  }
2838 
2839  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
2840  BlocksAttr::BlockType type;
2841  if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2842  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
2843  return;
2844  }
2845 
2846  D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type));
2847 }
2848 
2849 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2850  unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2851  if (AL.getNumArgs() > 0) {
2852  Expr *E = AL.getArgAsExpr(0);
2854  if (E->isTypeDependent() || E->isValueDependent() ||
2855  !(Idx = E->getIntegerConstantExpr(S.Context))) {
2856  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2857  << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2858  return;
2859  }
2860 
2861  if (Idx->isSigned() && Idx->isNegative()) {
2862  S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2863  << E->getSourceRange();
2864  return;
2865  }
2866 
2867  sentinel = Idx->getZExtValue();
2868  }
2869 
2870  unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2871  if (AL.getNumArgs() > 1) {
2872  Expr *E = AL.getArgAsExpr(1);
2874  if (E->isTypeDependent() || E->isValueDependent() ||
2875  !(Idx = E->getIntegerConstantExpr(S.Context))) {
2876  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2877  << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2878  return;
2879  }
2880  nullPos = Idx->getZExtValue();
2881 
2882  if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) {
2883  // FIXME: This error message could be improved, it would be nice
2884  // to say what the bounds actually are.
2885  S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2886  << E->getSourceRange();
2887  return;
2888  }
2889  }
2890 
2891  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2892  const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2893  if (isa<FunctionNoProtoType>(FT)) {
2894  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2895  return;
2896  }
2897 
2898  if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2899  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2900  return;
2901  }
2902  } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2903  if (!MD->isVariadic()) {
2904  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2905  return;
2906  }
2907  } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2908  if (!BD->isVariadic()) {
2909  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2910  return;
2911  }
2912  } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2913  QualType Ty = V->getType();
2914  if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2915  const FunctionType *FT = Ty->isFunctionPointerType()
2916  ? D->getFunctionType()
2917  : Ty->castAs<BlockPointerType>()
2918  ->getPointeeType()
2919  ->castAs<FunctionType>();
2920  if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2921  int m = Ty->isFunctionPointerType() ? 0 : 1;
2922  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2923  return;
2924  }
2925  } else {
2926  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2928  return;
2929  }
2930  } else {
2931  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2933  return;
2934  }
2935  D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
2936 }
2937 
2938 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2939  if (D->getFunctionType() &&
2941  !isa<CXXConstructorDecl>(D)) {
2942  S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2943  return;
2944  }
2945  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2946  if (MD->getReturnType()->isVoidType()) {
2947  S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2948  return;
2949  }
2950 
2951  StringRef Str;
2952  if (AL.isStandardAttributeSyntax() && !AL.getScopeName()) {
2953  // The standard attribute cannot be applied to variable declarations such
2954  // as a function pointer.
2955  if (isa<VarDecl>(D))
2956  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
2957  << AL << "functions, classes, or enumerations";
2958 
2959  // If this is spelled as the standard C++17 attribute, but not in C++17,
2960  // warn about using it as an extension. If there are attribute arguments,
2961  // then claim it's a C++2a extension instead.
2962  // FIXME: If WG14 does not seem likely to adopt the same feature, add an
2963  // extension warning for C2x mode.
2964  const LangOptions &LO = S.getLangOpts();
2965  if (AL.getNumArgs() == 1) {
2966  if (LO.CPlusPlus && !LO.CPlusPlus20)
2967  S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL;
2968 
2969  // Since this this is spelled [[nodiscard]], get the optional string
2970  // literal. If in C++ mode, but not in C++2a mode, diagnose as an
2971  // extension.
2972  // FIXME: C2x should support this feature as well, even as an extension.
2973  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
2974  return;
2975  } else if (LO.CPlusPlus && !LO.CPlusPlus17)
2976  S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2977  }
2978 
2979  D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
2980 }
2981 
2982 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2983  // weak_import only applies to variable & function declarations.
2984  bool isDef = false;
2985  if (!D->canBeWeakImported(isDef)) {
2986  if (isDef)
2987  S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2988  << "weak_import";
2989  else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2990  (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2991  (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2992  // Nothing to warn about here.
2993  } else
2994  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2995  << AL << ExpectedVariableOrFunction;
2996 
2997  return;
2998  }
2999 
3000  D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
3001 }
3002 
3003 // Handles reqd_work_group_size and work_group_size_hint.
3004 template <typename WorkGroupAttr>
3005 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3006  uint32_t WGSize[3];
3007  for (unsigned i = 0; i < 3; ++i) {
3008  const Expr *E = AL.getArgAsExpr(i);
3009  if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
3010  /*StrictlyUnsigned=*/true))
3011  return;
3012  if (WGSize[i] == 0) {
3013  S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3014  << AL << E->getSourceRange();
3015  return;
3016  }
3017  }
3018 
3019  WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
3020  if (Existing && !(Existing->getXDim() == WGSize[0] &&
3021  Existing->getYDim() == WGSize[1] &&
3022  Existing->getZDim() == WGSize[2]))
3023  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3024 
3025  D->addAttr(::new (S.Context)
3026  WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
3027 }
3028 
3029 // Handles intel_reqd_sub_group_size.
3030 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3031  uint32_t SGSize;
3032  const Expr *E = AL.getArgAsExpr(0);
3033  if (!checkUInt32Argument(S, AL, E, SGSize))
3034  return;
3035  if (SGSize == 0) {
3036  S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3037  << AL << E->getSourceRange();
3038  return;
3039  }
3040 
3041  OpenCLIntelReqdSubGroupSizeAttr *Existing =
3042  D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
3043  if (Existing && Existing->getSubGroupSize() != SGSize)
3044  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3045 
3046  D->addAttr(::new (S.Context)
3047  OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize));
3048 }
3049 
3050 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
3051  if (!AL.hasParsedType()) {
3052  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3053  return;
3054  }
3055 
3056  TypeSourceInfo *ParmTSI = nullptr;
3057  QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
3058  assert(ParmTSI && "no type source info for attribute argument");
3059 
3060  if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
3061  (ParmType->isBooleanType() ||
3062  !ParmType->isIntegralType(S.getASTContext()))) {
3063  S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
3064  return;
3065  }
3066 
3067  if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
3068  if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
3069  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3070  return;
3071  }
3072  }
3073 
3074  D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
3075 }
3076 
3078  StringRef Name) {
3079  // Explicit or partial specializations do not inherit
3080  // the section attribute from the primary template.
3081  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3082  if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
3084  return nullptr;
3085  }
3086  if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
3087  if (ExistingAttr->getName() == Name)
3088  return nullptr;
3089  Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3090  << 1 /*section*/;
3091  Diag(CI.getLoc(), diag::note_previous_attribute);
3092  return nullptr;
3093  }
3094  return ::new (Context) SectionAttr(Context, CI, Name);
3095 }
3096 
3097 /// Used to implement to perform semantic checking on
3098 /// attribute((section("foo"))) specifiers.
3099 ///
3100 /// In this case, "foo" is passed in to be checked. If the section
3101 /// specifier is invalid, return an Error that indicates the problem.
3102 ///
3103 /// This is a simple quality of implementation feature to catch errors
3104 /// and give good diagnostics in cases when the assembler or code generator
3105 /// would otherwise reject the section specifier.
3106 llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) {
3107  if (!Context.getTargetInfo().getTriple().isOSDarwin())
3108  return llvm::Error::success();
3109 
3110  // Let MCSectionMachO validate this.
3111  StringRef Segment, Section;
3112  unsigned TAA, StubSize;
3113  bool HasTAA;
3114  return llvm::MCSectionMachO::ParseSectionSpecifier(SecName, Segment, Section,
3115  TAA, HasTAA, StubSize);
3116 }
3117 
3118 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
3119  if (llvm::Error E = isValidSectionSpecifier(SecName)) {
3120  Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3121  << toString(std::move(E)) << 1 /*'section'*/;
3122  return false;
3123  }
3124  return true;
3125 }
3126 
3127 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3128  // Make sure that there is a string literal as the sections's single
3129  // argument.
3130  StringRef Str;
3131  SourceLocation LiteralLoc;
3132  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3133  return;
3134 
3135  if (!S.checkSectionName(LiteralLoc, Str))
3136  return;
3137 
3138  SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
3139  if (NewAttr) {
3140  D->addAttr(NewAttr);
3142  ObjCPropertyDecl>(D))
3143  S.UnifySection(NewAttr->getName(),
3145  cast<NamedDecl>(D));
3146  }
3147 }
3148 
3149 // This is used for `__declspec(code_seg("segname"))` on a decl.
3150 // `#pragma code_seg("segname")` uses checkSectionName() instead.
3151 static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
3152  StringRef CodeSegName) {
3153  if (llvm::Error E = S.isValidSectionSpecifier(CodeSegName)) {
3154  S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3155  << toString(std::move(E)) << 0 /*'code-seg'*/;
3156  return false;
3157  }
3158 
3159  return true;
3160 }
3161 
3163  StringRef Name) {
3164  // Explicit or partial specializations do not inherit
3165  // the code_seg attribute from the primary template.
3166  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3168  return nullptr;
3169  }
3170  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3171  if (ExistingAttr->getName() == Name)
3172  return nullptr;
3173  Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3174  << 0 /*codeseg*/;
3175  Diag(CI.getLoc(), diag::note_previous_attribute);
3176  return nullptr;
3177  }
3178  return ::new (Context) CodeSegAttr(Context, CI, Name);
3179 }
3180 
3181 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3182  StringRef Str;
3183  SourceLocation LiteralLoc;
3184  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3185  return;
3186  if (!checkCodeSegName(S, LiteralLoc, Str))
3187  return;
3188  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3189  if (!ExistingAttr->isImplicit()) {
3190  S.Diag(AL.getLoc(),
3191  ExistingAttr->getName() == Str
3192  ? diag::warn_duplicate_codeseg_attribute
3193  : diag::err_conflicting_codeseg_attribute);
3194  return;
3195  }
3196  D->dropAttr<CodeSegAttr>();
3197  }
3198  if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
3199  D->addAttr(CSA);
3200 }
3201 
3202 // Check for things we'd like to warn about. Multiversioning issues are
3203 // handled later in the process, once we know how many exist.
3204 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3205  enum FirstParam { Unsupported, Duplicate, Unknown };
3206  enum SecondParam { None, Architecture, Tune };
3207  if (AttrStr.find("fpmath=") != StringRef::npos)
3208  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3209  << Unsupported << None << "fpmath=";
3210 
3211  // Diagnose use of tune if target doesn't support it.
3212  if (!Context.getTargetInfo().supportsTargetAttributeTune() &&
3213  AttrStr.find("tune=") != StringRef::npos)
3214  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3215  << Unsupported << None << "tune=";
3216 
3217  ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3218 
3219  if (!ParsedAttrs.Architecture.empty() &&
3220  !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3221  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3222  << Unknown << Architecture << ParsedAttrs.Architecture;
3223 
3224  if (!ParsedAttrs.Tune.empty() &&
3225  !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune))
3226  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3227  << Unknown << Tune << ParsedAttrs.Tune;
3228 
3229  if (ParsedAttrs.DuplicateArchitecture)
3230  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3231  << Duplicate << None << "arch=";
3232  if (ParsedAttrs.DuplicateTune)
3233  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3234  << Duplicate << None << "tune=";
3235 
3236  for (const auto &Feature : ParsedAttrs.Features) {
3237  auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3238  if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3239  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3240  << Unsupported << None << CurFeature;
3241  }
3242 
3244  StringRef Error;
3245  if (!ParsedAttrs.BranchProtection.empty() &&
3247  ParsedAttrs.BranchProtection, BPI, Error)) {
3248  if (Error.empty())
3249  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3250  << Unsupported << None << "branch-protection";
3251  else
3252  return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
3253  << Error;
3254  }
3255 
3256  return false;
3257 }
3258 
3259 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3260  StringRef Str;
3261  SourceLocation LiteralLoc;
3262  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3263  S.checkTargetAttr(LiteralLoc, Str))
3264  return;
3265 
3266  TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3267  D->addAttr(NewAttr);
3268 }
3269 
3270 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3271  Expr *E = AL.getArgAsExpr(0);
3272  uint32_t VecWidth;
3273  if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3274  AL.setInvalid();
3275  return;
3276  }
3277 
3278  MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3279  if (Existing && Existing->getVectorWidth() != VecWidth) {
3280  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3281  return;
3282  }
3283 
3284  D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3285 }
3286 
3287 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3288  Expr *E = AL.getArgAsExpr(0);
3289  SourceLocation Loc = E->getExprLoc();
3290  FunctionDecl *FD = nullptr;
3292 
3293  // gcc only allows for simple identifiers. Since we support more than gcc, we
3294  // will warn the user.
3295  if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3296  if (DRE->hasQualifier())
3297  S.Diag(Loc, diag::warn_cleanup_ext);
3298  FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3299  NI = DRE->getNameInfo();
3300  if (!FD) {
3301  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3302  << NI.getName();
3303  return;
3304  }
3305  } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3306  if (ULE->hasExplicitTemplateArgs())
3307  S.Diag(Loc, diag::warn_cleanup_ext);
3309  NI = ULE->getNameInfo();
3310  if (!FD) {
3311  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3312  << NI.getName();
3313  if (ULE->getType() == S.Context.OverloadTy)
3315  return;
3316  }
3317  } else {
3318  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3319  return;
3320  }
3321 
3322  if (FD->getNumParams() != 1) {
3323  S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3324  << NI.getName();
3325  return;
3326  }
3327 
3328  // We're currently more strict than GCC about what function types we accept.
3329  // If this ever proves to be a problem it should be easy to fix.
3330  QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3331  QualType ParamTy = FD->getParamDecl(0)->getType();
3333  ParamTy, Ty) != Sema::Compatible) {
3334  S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3335  << NI.getName() << ParamTy << Ty;
3336  return;
3337  }
3338 
3339  D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
3340 }
3341 
3343  const ParsedAttr &AL) {
3344  if (!AL.isArgIdent(0)) {
3345  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3346  << AL << 0 << AANT_ArgumentIdentifier;
3347  return;
3348  }
3349 
3350  EnumExtensibilityAttr::Kind ExtensibilityKind;
3351  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3352  if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3353  ExtensibilityKind)) {
3354  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3355  return;
3356  }
3357 
3358  D->addAttr(::new (S.Context)
3359  EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3360 }
3361 
3362 /// Handle __attribute__((format_arg((idx)))) attribute based on
3363 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3364 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3365  Expr *IdxExpr = AL.getArgAsExpr(0);
3366  ParamIdx Idx;
3367  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3368  return;
3369 
3370  // Make sure the format string is really a string.
3372 
3373  bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3374  if (NotNSStringTy &&
3375  !isCFStringType(Ty, S.Context) &&
3376  (!Ty->isPointerType() ||
3377  !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3378  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3379  << "a string type" << IdxExpr->getSourceRange()
3381  return;
3382  }
3384  if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true) &&
3385  !isCFStringType(Ty, S.Context) &&
3386  (!Ty->isPointerType() ||
3387  !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3388  S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3389  << (NotNSStringTy ? "string type" : "NSString")
3390  << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3391  return;
3392  }
3393 
3394  D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
3395 }
3396 
3404 };
3405 
3406 /// getFormatAttrKind - Map from format attribute names to supported format
3407 /// types.
3408 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3409  return llvm::StringSwitch<FormatAttrKind>(Format)
3410  // Check for formats that get handled specially.
3411  .Case("NSString", NSStringFormat)
3412  .Case("CFString", CFStringFormat)
3413  .Case("strftime", StrftimeFormat)
3414 
3415  // Otherwise, check for supported formats.
3416  .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3417  .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3418  .Case("kprintf", SupportedFormat) // OpenBSD.
3419  .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3420  .Case("os_trace", SupportedFormat)
3421  .Case("os_log", SupportedFormat)
3422 
3423  .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3424  .Default(InvalidFormat);
3425 }
3426 
3427 /// Handle __attribute__((init_priority(priority))) attributes based on
3428 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3429 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3430  if (!S.getLangOpts().CPlusPlus) {
3431  S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3432  return;
3433  }
3434 
3435  if (S.getCurFunctionOrMethodDecl()) {
3436  S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3437  AL.setInvalid();
3438  return;
3439  }
3440  QualType T = cast<VarDecl>(D)->getType();
3441  if (S.Context.getAsArrayType(T))
3442  T = S.Context.getBaseElementType(T);
3443  if (!T->getAs<RecordType>()) {
3444  S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3445  AL.setInvalid();
3446  return;
3447  }
3448 
3449  Expr *E = AL.getArgAsExpr(0);
3450  uint32_t prioritynum;
3451  if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3452  AL.setInvalid();
3453  return;
3454  }
3455 
3456  // Only perform the priority check if the attribute is outside of a system
3457  // header. Values <= 100 are reserved for the implementation, and libc++
3458  // benefits from being able to specify values in that range.
3459  if ((prioritynum < 101 || prioritynum > 65535) &&
3461  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3462  << E->getSourceRange() << AL << 101 << 65535;
3463  AL.setInvalid();
3464  return;
3465  }
3466  D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3467 }
3468 
3470  StringRef NewUserDiagnostic) {
3471  if (const auto *EA = D->getAttr<ErrorAttr>()) {
3472  std::string NewAttr = CI.getNormalizedFullName();
3473  assert((NewAttr == "error" || NewAttr == "warning") &&
3474  "unexpected normalized full name");
3475  bool Match = (EA->isError() && NewAttr == "error") ||
3476  (EA->isWarning() && NewAttr == "warning");
3477  if (!Match) {
3478  Diag(EA->getLocation(), diag::err_attributes_are_not_compatible)
3479  << CI << EA;
3480  Diag(CI.getLoc(), diag::note_conflicting_attribute);
3481  return nullptr;
3482  }
3483  if (EA->getUserDiagnostic() != NewUserDiagnostic) {
3484  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << EA;
3485  Diag(EA->getLoc(), diag::note_previous_attribute);
3486  }
3487  D->dropAttr<ErrorAttr>();
3488  }
3489  return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic);
3490 }
3491 
3493  IdentifierInfo *Format, int FormatIdx,
3494  int FirstArg) {
3495  // Check whether we already have an equivalent format attribute.
3496  for (auto *F : D->specific_attrs<FormatAttr>()) {
3497  if (F->getType() == Format &&
3498  F->getFormatIdx() == FormatIdx &&
3499  F->getFirstArg() == FirstArg) {
3500  // If we don't have a valid location for this attribute, adopt the
3501  // location.
3502  if (F->getLocation().isInvalid())
3503  F->setRange(CI.getRange());
3504  return nullptr;
3505  }
3506  }
3507 
3508  return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3509 }
3510 
3511 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3512 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3513 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3514  if (!AL.isArgIdent(0)) {
3515  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3516  << AL << 1 << AANT_ArgumentIdentifier;
3517  return;
3518  }
3519 
3520  // In C++ the implicit 'this' function parameter also counts, and they are
3521  // counted from one.
3522  bool HasImplicitThisParam = isInstanceMethod(D);
3523  unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3524 
3525  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3526  StringRef Format = II->getName();
3527 
3528  if (normalizeName(Format)) {
3529  // If we've modified the string name, we need a new identifier for it.
3530  II = &S.Context.Idents.get(Format);
3531  }
3532 
3533  // Check for supported formats.
3535 
3536  if (Kind == IgnoredFormat)
3537  return;
3538 
3539  if (Kind == InvalidFormat) {
3540  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3541  << AL << II->getName();
3542  return;
3543  }
3544 
3545  // checks for the 2nd argument
3546  Expr *IdxExpr = AL.getArgAsExpr(1);
3547  uint32_t Idx;
3548  if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3549  return;
3550 
3551  if (Idx < 1 || Idx > NumArgs) {
3552  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3553  << AL << 2 << IdxExpr->getSourceRange();
3554  return;
3555  }
3556 
3557  // FIXME: Do we need to bounds check?
3558  unsigned ArgIdx = Idx - 1;
3559 
3560  if (HasImplicitThisParam) {
3561  if (ArgIdx == 0) {
3562  S.Diag(AL.getLoc(),
3563  diag::err_format_attribute_implicit_this_format_string)
3564  << IdxExpr->getSourceRange();
3565  return;
3566  }
3567  ArgIdx--;
3568  }
3569 
3570  // make sure the format string is really a string
3571  QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3572 
3573  if (Kind == CFStringFormat) {
3574  if (!isCFStringType(Ty, S.Context)) {
3575  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3576  << "a CFString" << IdxExpr->getSourceRange()
3577  << getFunctionOrMethodParamRange(D, ArgIdx);
3578  return;
3579  }
3580  } else if (Kind == NSStringFormat) {
3581  // FIXME: do we need to check if the type is NSString*? What are the
3582  // semantics?
3583  if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true)) {
3584  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3585  << "an NSString" << IdxExpr->getSourceRange()
3586  << getFunctionOrMethodParamRange(D, ArgIdx);
3587  return;
3588  }
3589  } else if (!Ty->isPointerType() ||
3590  !Ty->castAs<PointerType>()->getPointeeType()->isCharType()) {
3591  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3592  << "a string type" << IdxExpr->getSourceRange()
3593  << getFunctionOrMethodParamRange(D, ArgIdx);
3594  return;
3595  }
3596 
3597  // check the 3rd argument
3598  Expr *FirstArgExpr = AL.getArgAsExpr(2);
3599  uint32_t FirstArg;
3600  if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3601  return;
3602 
3603  // check if the function is variadic if the 3rd argument non-zero
3604  if (FirstArg != 0) {
3605  if (isFunctionOrMethodVariadic(D)) {
3606  ++NumArgs; // +1 for ...
3607  } else {
3608  S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3609  return;
3610  }
3611  }
3612 
3613  // strftime requires FirstArg to be 0 because it doesn't read from any
3614  // variable the input is just the current time + the format string.
3615  if (Kind == StrftimeFormat) {
3616  if (FirstArg != 0) {
3617  S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3618  << FirstArgExpr->getSourceRange();
3619  return;
3620  }
3621  // if 0 it disables parameter checking (to use with e.g. va_list)
3622  } else if (FirstArg != 0 && FirstArg != NumArgs) {
3623  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3624  << AL << 3 << FirstArgExpr->getSourceRange();
3625  return;
3626  }
3627 
3628  FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
3629  if (NewAttr)
3630  D->addAttr(NewAttr);
3631 }
3632 
3633 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
3634 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3635  // The index that identifies the callback callee is mandatory.
3636  if (AL.getNumArgs() == 0) {
3637  S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
3638  << AL.getRange();
3639  return;
3640  }
3641 
3642  bool HasImplicitThisParam = isInstanceMethod(D);
3643  int32_t NumArgs = getFunctionOrMethodNumParams(D);
3644 
3645  FunctionDecl *FD = D->getAsFunction();
3646  assert(FD && "Expected a function declaration!");
3647 
3648  llvm::StringMap<int> NameIdxMapping;
3649  NameIdxMapping["__"] = -1;
3650 
3651  NameIdxMapping["this"] = 0;
3652 
3653  int Idx = 1;
3654  for (const ParmVarDecl *PVD : FD->parameters())
3655  NameIdxMapping[PVD->getName()] = Idx++;
3656 
3657  auto UnknownName = NameIdxMapping.end();
3658 
3659  SmallVector<int, 8> EncodingIndices;
3660  for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
3661  SourceRange SR;
3662  int32_t ArgIdx;
3663 
3664  if (AL.isArgIdent(I)) {
3665  IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3666  auto It = NameIdxMapping.find(IdLoc->Ident->getName());
3667  if (It == UnknownName) {
3668  S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
3669  << IdLoc->Ident << IdLoc->Loc;
3670  return;
3671  }
3672 
3673  SR = SourceRange(IdLoc->Loc);
3674  ArgIdx = It->second;
3675  } else if (AL.isArgExpr(I)) {
3676  Expr *IdxExpr = AL.getArgAsExpr(I);
3677 
3678  // If the expression is not parseable as an int32_t we have a problem.
3679  if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
3680  false)) {
3681  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3682  << AL << (I + 1) << IdxExpr->getSourceRange();
3683  return;
3684  }
3685 
3686  // Check oob, excluding the special values, 0 and -1.
3687  if (ArgIdx < -1 || ArgIdx > NumArgs) {
3688  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3689  << AL << (I + 1) << IdxExpr->getSourceRange();
3690  return;
3691  }
3692 
3693  SR = IdxExpr->getSourceRange();
3694  } else {
3695  llvm_unreachable("Unexpected ParsedAttr argument type!");
3696  }
3697 
3698  if (ArgIdx == 0 && !HasImplicitThisParam) {
3699  S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
3700  << (I + 1) << SR;
3701  return;
3702  }
3703 
3704  // Adjust for the case we do not have an implicit "this" parameter. In this
3705  // case we decrease all positive values by 1 to get LLVM argument indices.
3706  if (!HasImplicitThisParam && ArgIdx > 0)
3707  ArgIdx -= 1;
3708 
3709  EncodingIndices.push_back(ArgIdx);
3710  }
3711 
3712  int CalleeIdx = EncodingIndices.front();
3713  // Check if the callee index is proper, thus not "this" and not "unknown".
3714  // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
3715  // is false and positive if "HasImplicitThisParam" is true.
3716  if (CalleeIdx < (int)HasImplicitThisParam) {
3717  S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
3718  << AL.getRange();
3719  return;
3720  }
3721 
3722  // Get the callee type, note the index adjustment as the AST doesn't contain
3723  // the this type (which the callee cannot reference anyway!).
3724  const Type *CalleeType =
3725  getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
3726  .getTypePtr();
3727  if (!CalleeType || !CalleeType->isFunctionPointerType()) {
3728  S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3729  << AL.getRange();
3730  return;
3731  }
3732 
3733  const Type *CalleeFnType =
3735 
3736  // TODO: Check the type of the callee arguments.
3737 
3738  const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
3739  if (!CalleeFnProtoType) {
3740  S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3741  << AL.getRange();
3742  return;
3743  }
3744 
3745  if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
3746  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3747  << AL << (unsigned)(EncodingIndices.size() - 1);
3748  return;
3749  }
3750 
3751  if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
3752  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3753  << AL << (unsigned)(EncodingIndices.size() - 1);
3754  return;
3755  }
3756 
3757  if (CalleeFnProtoType->isVariadic()) {
3758  S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
3759  return;
3760  }
3761 
3762  // Do not allow multiple callback attributes.
3763  if (D->hasAttr<CallbackAttr>()) {
3764  S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
3765  return;
3766  }
3767 
3768  D->addAttr(::new (S.Context) CallbackAttr(
3769  S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
3770 }
3771 
3772 static bool isFunctionLike(const Type &T) {
3773  // Check for explicit function types.
3774  // 'called_once' is only supported in Objective-C and it has
3775  // function pointers and block pointers.
3776  return T.isFunctionPointerType() || T.isBlockPointerType();
3777 }
3778 
3779 /// Handle 'called_once' attribute.
3780 static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3781  // 'called_once' only applies to parameters representing functions.
3782  QualType T = cast<ParmVarDecl>(D)->getType();
3783 
3784  if (!isFunctionLike(*T)) {
3785  S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type);
3786  return;
3787  }
3788 
3789  D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL));
3790 }
3791 
3792 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3793  // Try to find the underlying union declaration.
3794  RecordDecl *RD = nullptr;
3795  const auto *TD = dyn_cast<TypedefNameDecl>(D);
3796  if (TD && TD->getUnderlyingType()->isUnionType())
3797  RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3798  else
3799  RD = dyn_cast<RecordDecl>(D);
3800 
3801  if (!RD || !RD->isUnion()) {
3802  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
3803  << ExpectedUnion;
3804  return;
3805  }
3806 
3807  if (!RD->isCompleteDefinition()) {
3808  if (!RD->isBeingDefined())
3809  S.Diag(AL.getLoc(),
3810  diag::warn_transparent_union_attribute_not_definition);
3811  return;
3812  }
3813 
3815  FieldEnd = RD->field_end();
3816  if (Field == FieldEnd) {
3817  S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3818  return;
3819  }
3820 
3821  FieldDecl *FirstField = *Field;
3822  QualType FirstType = FirstField->getType();
3823  if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3824  S.Diag(FirstField->getLocation(),
3825  diag::warn_transparent_union_attribute_floating)
3826  << FirstType->isVectorType() << FirstType;
3827  return;
3828  }
3829 
3830  if (FirstType->isIncompleteType())
3831  return;
3832  uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3833  uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3834  for (; Field != FieldEnd; ++Field) {
3835  QualType FieldType = Field->getType();
3836  if (FieldType->isIncompleteType())
3837  return;
3838  // FIXME: this isn't fully correct; we also need to test whether the
3839  // members of the union would all have the same calling convention as the
3840  // first member of the union. Checking just the size and alignment isn't
3841  // sufficient (consider structs passed on the stack instead of in registers
3842  // as an example).
3843  if (S.Context.getTypeSize(FieldType) != FirstSize ||
3844  S.Context.getTypeAlign(FieldType) > FirstAlign) {
3845  // Warn if we drop the attribute.
3846  bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3847  unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType)
3848  : S.Context.getTypeAlign(FieldType);
3849  S.Diag(Field->getLocation(),
3850  diag::warn_transparent_union_attribute_field_size_align)
3851  << isSize << *Field << FieldBits;
3852  unsigned FirstBits = isSize ? FirstSize : FirstAlign;
3853  S.Diag(FirstField->getLocation(),
3854  diag::note_transparent_union_first_field_size_align)
3855  << isSize << FirstBits;
3856  return;
3857  }
3858  }
3859 
3860  RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
3861 }
3862 
3864  StringRef Str, MutableArrayRef<Expr *> Args) {
3865  auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI);
3867  for (unsigned Idx = 0; Idx < Attr->args_size(); Idx++) {
3868  Expr *&E = Attr->args_begin()[Idx];
3869  assert(E && "error are handled before");
3870  if (E->isValueDependent() || E->isTypeDependent())
3871  continue;
3872 
3873  if (E->getType()->isArrayType())
3874  E = ImpCastExprToType(E, Context.getPointerType(E->getType()),
3875  clang::CK_ArrayToPointerDecay)
3876  .get();
3877  if (E->getType()->isFunctionType())
3878  E = ImplicitCastExpr::Create(Context,
3879  Context.getPointerType(E->getType()),
3880  clang::CK_FunctionToPointerDecay, E, nullptr,
3882  if (E->isLValue())
3884  clang::CK_LValueToRValue, E, nullptr,
3886 
3887  Expr::EvalResult Eval;
3888  Notes.clear();
3889  Eval.Diag = &Notes;
3890 
3891  bool Result =
3892  E->EvaluateAsConstantExpr(Eval, Context);
3893 
3894  /// Result means the expression can be folded to a constant.
3895  /// Note.empty() means the expression is a valid constant expression in the
3896  /// current language mode.
3897  if (!Result || !Notes.empty()) {
3898  Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type)
3899  << CI << (Idx + 1) << AANT_ArgumentConstantExpr;
3900  for (auto &Note : Notes)
3901  Diag(Note.first, Note.second);
3902  return;
3903  }
3904  assert(Eval.Val.hasValue());
3905  E = ConstantExpr::Create(Context, E, Eval.Val);
3906  }
3907  D->addAttr(Attr);
3908 }
3909 
3910 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3911  // Make sure that there is a string literal as the annotation's first
3912  // argument.
3913  StringRef Str;
3914  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3915  return;
3916 
3918  Args.reserve(AL.getNumArgs() - 1);
3919  for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
3920  assert(!AL.isArgIdent(Idx));
3921  Args.push_back(AL.getArgAsExpr(Idx));
3922  }
3923 
3924  S.AddAnnotationAttr(D, AL, Str, Args);
3925 }
3926 
3927 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3928  S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
3929 }
3930 
3932  AlignValueAttr TmpAttr(Context, CI, E);
3933  SourceLocation AttrLoc = CI.getLoc();
3934 
3935  QualType T;
3936  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3937  T = TD->getUnderlyingType();
3938  else if (const auto *VD = dyn_cast<ValueDecl>(D))
3939  T = VD->getType();
3940  else
3941  llvm_unreachable("Unknown decl type for align_value");
3942 
3943  if (!T->isDependentType() && !T->isAnyPointerType() &&
3944  !T->isReferenceType() && !T->isMemberPointerType()) {
3945  Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3946  << &TmpAttr << T << D->getSourceRange();
3947  return;
3948  }
3949 
3950  if (!E->isValueDependent()) {
3951  llvm::APSInt Alignment;
3952  ExprResult ICE = VerifyIntegerConstantExpression(
3953  E, &Alignment, diag::err_align_value_attribute_argument_not_int);
3954  if (ICE.isInvalid())
3955  return;
3956 
3957  if (!Alignment.isPowerOf2()) {
3958  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3959  << E->getSourceRange();
3960  return;
3961  }
3962 
3963  D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
3964  return;
3965  }
3966 
3967  // Save dependent expressions in the AST to be instantiated.
3968  D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
3969 }
3970 
3971 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3972  // check the attribute arguments.
3973  if (AL.getNumArgs() > 1) {
3974  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3975  return;
3976  }
3977 
3978  if (AL.getNumArgs() == 0) {
3979  D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
3980  return;
3981  }
3982 
3983  Expr *E = AL.getArgAsExpr(0);
3985  S.Diag(AL.getEllipsisLoc(),
3986  diag::err_pack_expansion_without_parameter_packs);
3987  return;
3988  }
3989 
3991  return;
3992 
3993  S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
3994 }
3995 
3997  bool IsPackExpansion) {
3998  AlignedAttr TmpAttr(Context, CI, true, E);
3999  SourceLocation AttrLoc = CI.getLoc();
4000 
4001  // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4002  if (TmpAttr.isAlignas()) {
4003  // C++11 [dcl.align]p1:
4004  // An alignment-specifier may be applied to a variable or to a class
4005  // data member, but it shall not be applied to a bit-field, a function
4006  // parameter, the formal parameter of a catch clause, or a variable
4007  // declared with the register storage class specifier. An
4008  // alignment-specifier may also be applied to the declaration of a class
4009  // or enumeration type.
4010  // C11 6.7.5/2:
4011  // An alignment attribute shall not be specified in a declaration of
4012  // a typedef, or a bit-field, or a function, or a parameter, or an
4013  // object declared with the register storage-class specifier.
4014  int DiagKind = -1;
4015  if (isa<ParmVarDecl>(D)) {
4016  DiagKind = 0;
4017  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
4018  if (VD->getStorageClass() == SC_Register)
4019  DiagKind = 1;
4020  if (VD->isExceptionVariable())
4021  DiagKind = 2;
4022  } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
4023  if (FD->isBitField())
4024  DiagKind = 3;
4025  } else if (!isa<TagDecl>(D)) {
4026  Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
4027  << (TmpAttr.isC11() ? ExpectedVariableOrField
4029  return;
4030  }
4031  if (DiagKind != -1) {
4032  Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
4033  << &TmpAttr << DiagKind;
4034  return;
4035  }
4036  }
4037 
4038  if (E->isValueDependent()) {
4039  // We can't support a dependent alignment on a non-dependent type,
4040  // because we have no way to model that a type is "alignment-dependent"
4041  // but not dependent in any other way.
4042  if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
4043  if (!TND->getUnderlyingType()->isDependentType()) {
4044  Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4045  << E->getSourceRange();
4046  return;
4047  }
4048  }
4049 
4050  // Save dependent expressions in the AST to be instantiated.
4051  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
4052  AA->setPackExpansion(IsPackExpansion);
4053  D->addAttr(AA);
4054  return;
4055  }
4056 
4057  // FIXME: Cache the number on the AL object?
4058  llvm::APSInt Alignment;
4059  ExprResult ICE = VerifyIntegerConstantExpression(
4060  E, &Alignment, diag::err_aligned_attribute_argument_not_int);
4061  if (ICE.isInvalid())
4062  return;
4063 
4064  uint64_t AlignVal = Alignment.getZExtValue();
4065  // 16 byte ByVal alignment not due to a vector member is not honoured by XL
4066  // on AIX. Emit a warning here that users are generating binary incompatible
4067  // code to be safe.
4068  if (AlignVal >= 16 && isa<FieldDecl>(D) &&
4069  Context.getTargetInfo().getTriple().isOSAIX())
4070  Diag(AttrLoc, diag::warn_not_xl_compatible) << E->getSourceRange();
4071 
4072  // C++11 [dcl.align]p2:
4073  // -- if the constant expression evaluates to zero, the alignment
4074  // specifier shall have no effect
4075  // C11 6.7.5p6:
4076  // An alignment specification of zero has no effect.
4077  if (!(TmpAttr.isAlignas() && !Alignment)) {
4078  if (!llvm::isPowerOf2_64(AlignVal)) {
4079  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4080  << E->getSourceRange();
4081  return;
4082  }
4083  }
4084 
4085  unsigned MaximumAlignment = Sema::MaximumAlignment;
4086  if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
4087  MaximumAlignment = std::min(MaximumAlignment, 8192u);
4088  if (AlignVal > MaximumAlignment) {
4089  Diag(AttrLoc, diag::err_attribute_aligned_too_great)
4090  << MaximumAlignment << E->getSourceRange();
4091  return;
4092  }
4093 
4094  const auto *VD = dyn_cast<VarDecl>(D);
4095  if (VD && Context.getTargetInfo().isTLSSupported()) {
4096  unsigned MaxTLSAlign =
4097  Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
4098  .getQuantity();
4099  if (MaxTLSAlign && AlignVal > MaxTLSAlign &&
4100  VD->getTLSKind() != VarDecl::TLS_None) {
4101  Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
4102  << (unsigned)AlignVal << VD << MaxTLSAlign;
4103  return;
4104  }
4105  }
4106 
4107  // On AIX, an aligned attribute can not decrease the alignment when applied
4108  // to a variable declaration with vector type.
4109  if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4110  const Type *Ty = VD->getType().getTypePtr();
4111  if (Ty->isVectorType() && AlignVal < 16) {
4112  Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4113  << VD->getType() << 16;
4114  return;
4115  }
4116  }
4117 
4118  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
4119  AA->setPackExpansion(IsPackExpansion);
4120  D->addAttr(AA);
4121 }
4122 
4124  TypeSourceInfo *TS, bool IsPackExpansion) {
4125  // FIXME: Cache the number on the AL object if non-dependent?
4126  // FIXME: Perform checking of type validity
4127  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4128  AA->setPackExpansion(IsPackExpansion);
4129  D->addAttr(AA);
4130 }
4131 
4133  assert(D->hasAttrs() && "no attributes on decl");
4134 
4135  QualType UnderlyingTy, DiagTy;
4136  if (const auto *VD = dyn_cast<ValueDecl>(D)) {
4137  UnderlyingTy = DiagTy = VD->getType();
4138  } else {
4139  UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
4140  if (const auto *ED = dyn_cast<EnumDecl>(D))
4141  UnderlyingTy = ED->getIntegerType();
4142  }
4143  if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
4144  return;
4145 
4146  // C++11 [dcl.align]p5, C11 6.7.5/4:
4147  // The combined effect of all alignment attributes in a declaration shall
4148  // not specify an alignment that is less strict than the alignment that
4149  // would otherwise be required for the entity being declared.
4150  AlignedAttr *AlignasAttr = nullptr;
4151  AlignedAttr *LastAlignedAttr = nullptr;
4152  unsigned Align = 0;
4153  for (auto *I : D->specific_attrs<AlignedAttr>()) {
4154  if (I->isAlignmentDependent())
4155  return;
4156  if (I->isAlignas())
4157  AlignasAttr = I;
4158  Align = std::max(Align, I->getAlignment(Context));
4159  LastAlignedAttr = I;
4160  }
4161 
4162  if (Align && DiagTy->isSizelessType()) {
4163  Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
4164  << LastAlignedAttr << DiagTy;
4165  } else if (AlignasAttr && Align) {
4166  CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
4167  CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
4168  if (NaturalAlign > RequestedAlign)
4169  Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
4170  << DiagTy << (unsigned)NaturalAlign.getQuantity();
4171  }
4172 }
4173 
4175  CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4176  MSInheritanceModel ExplicitModel) {
4177  assert(RD->hasDefinition() && "RD has no definition!");
4178 
4179  // We may not have seen base specifiers or any virtual methods yet. We will
4180  // have to wait until the record is defined to catch any mismatches.
4181  if (!RD->getDefinition()->isCompleteDefinition())
4182  return false;
4183 
4184  // The unspecified model never matches what a definition could need.
4185  if (ExplicitModel == MSInheritanceModel::Unspecified)
4186  return false;
4187 
4188  if (BestCase) {
4189  if (RD->calculateInheritanceModel() == ExplicitModel)
4190  return false;
4191  } else {
4192  if (RD->calculateInheritanceModel() <= ExplicitModel)
4193  return false;
4194  }
4195 
4196  Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
4197  << 0 /*definition*/;
4198  Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
4199  return true;
4200 }
4201 
4202 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
4203 /// attribute.
4204 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
4205  bool &IntegerMode, bool &ComplexMode,
4206  bool &ExplicitIEEE) {
4207  IntegerMode = true;
4208  ComplexMode = false;
4209  switch (Str.size()) {
4210  case 2:
4211  switch (Str[0]) {
4212  case 'Q':
4213  DestWidth = 8;
4214  break;
4215  case 'H':
4216  DestWidth = 16;
4217  break;
4218  case 'S':
4219  DestWidth = 32;
4220  break;
4221  case 'D':
4222  DestWidth = 64;
4223  break;
4224  case 'X':
4225  DestWidth = 96;
4226  break;
4227  case 'K': // KFmode - IEEE quad precision (__float128)
4228  ExplicitIEEE = true;
4229  DestWidth = Str[1] == 'I' ? 0 : 128;
4230  break;
4231  case 'T':
4232  ExplicitIEEE = false;
4233  DestWidth = 128;
4234  break;
4235  }
4236  if (Str[1] == 'F') {
4237  IntegerMode = false;
4238  } else if (Str[1] == 'C') {
4239  IntegerMode = false;
4240  ComplexMode = true;
4241  } else if (Str[1] != 'I') {
4242  DestWidth = 0;
4243  }
4244  break;
4245  case 4:
4246  // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4247  // pointer on PIC16 and other embedded platforms.
4248  if (Str == "word")
4249  DestWidth = S.Context.getTargetInfo().getRegisterWidth();
4250  else if (Str == "byte")
4251  DestWidth = S.Context.getTargetInfo().getCharWidth();
4252  break;
4253  case 7:
4254  if (Str == "pointer")
4255  DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
4256  break;
4257  case 11:
4258  if (Str == "unwind_word")
4259  DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4260  break;
4261  }
4262 }
4263 
4264 /// handleModeAttr - This attribute modifies the width of a decl with primitive
4265 /// type.
4266 ///
4267 /// Despite what would be logical, the mode attribute is a decl attribute, not a
4268 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4269 /// HImode, not an intermediate pointer.
4270 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4271  // This attribute isn't documented, but glibc uses it. It changes
4272  // the width of an int or unsigned int to the specified size.
4273  if (!AL.isArgIdent(0)) {
4274  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4275  << AL << AANT_ArgumentIdentifier;
4276  return;
4277  }
4278 
4279  IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
4280 
4281  S.AddModeAttr(D, AL, Name);
4282 }
4283 
4285  IdentifierInfo *Name, bool InInstantiation) {
4286  StringRef Str = Name->getName();
4287  normalizeName(Str);
4288  SourceLocation AttrLoc = CI.getLoc();
4289 
4290  unsigned DestWidth = 0;
4291  bool IntegerMode = true;
4292  bool ComplexMode = false;
4293  bool ExplicitIEEE = false;
4294  llvm::APInt VectorSize(64, 0);
4295  if (Str.size() >= 4 && Str[0] == 'V') {
4296  // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4297  size_t StrSize = Str.size();
4298  size_t VectorStringLength = 0;
4299  while ((VectorStringLength + 1) < StrSize &&
4300  isdigit(Str[VectorStringLength + 1]))
4301  ++VectorStringLength;
4302  if (VectorStringLength &&
4303  !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4304  VectorSize.isPowerOf2()) {
4305  parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4306  IntegerMode, ComplexMode, ExplicitIEEE);
4307  // Avoid duplicate warning from template instantiation.
4308  if (!InInstantiation)
4309  Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4310  } else {
4311  VectorSize = 0;
4312  }
4313  }
4314 
4315  if (!VectorSize)
4316  parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode,
4317  ExplicitIEEE);
4318 
4319  // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4320  // and friends, at least with glibc.
4321  // FIXME: Make sure floating-point mappings are accurate
4322  // FIXME: Support XF and TF types
4323  if (!DestWidth) {
4324  Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4325  return;
4326  }
4327 
4328  QualType OldTy;
4329  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4330  OldTy = TD->getUnderlyingType();
4331  else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4332  // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4333  // Try to get type from enum declaration, default to int.
4334  OldTy = ED->getIntegerType();
4335  if (OldTy.isNull())
4336  OldTy = Context.IntTy;
4337  } else
4338  OldTy = cast<ValueDecl>(D)->getType();
4339 
4340  if (OldTy->isDependentType()) {
4341  D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4342  return;
4343  }
4344 
4345  // Base type can also be a vector type (see PR17453).
4346  // Distinguish between base type and base element type.
4347  QualType OldElemTy = OldTy;
4348  if (const auto *VT = OldTy->getAs<VectorType>())
4349  OldElemTy = VT->getElementType();
4350 
4351  // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4352  // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4353  // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4354  if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
4355  VectorSize.getBoolValue()) {
4356  Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
4357  return;
4358  }
4359  bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
4360  !OldElemTy->isExtIntType()) ||
4361  OldElemTy->getAs<EnumType>();
4362 
4363  if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4364  !IntegralOrAnyEnumType)
4365  Diag(AttrLoc, diag::err_mode_not_primitive);
4366  else if (IntegerMode) {
4367  if (!IntegralOrAnyEnumType)
4368  Diag(AttrLoc, diag::err_mode_wrong_type);
4369  } else if (ComplexMode) {
4370  if (!OldElemTy->isComplexType())
4371  Diag(AttrLoc, diag::err_mode_wrong_type);
4372  } else {
4373  if (!OldElemTy->isFloatingType())
4374  Diag(AttrLoc, diag::err_mode_wrong_type);
4375  }
4376 
4377  QualType NewElemTy;
4378 
4379  if (IntegerMode)
4380  NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4381  OldElemTy->isSignedIntegerType());
4382  else
4383  NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitIEEE);
4384 
4385  if (NewElemTy.isNull()) {
4386  Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4387  return;
4388  }
4389 
4390  if (ComplexMode) {
4391  NewElemTy = Context.getComplexType(NewElemTy);
4392  }
4393 
4394  QualType NewTy = NewElemTy;
4395  if (VectorSize.getBoolValue()) {
4396  NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4398  } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4399  // Complex machine mode does not support base vector types.
4400  if (ComplexMode) {
4401  Diag(AttrLoc, diag::err_complex_mode_vector_type);
4402  return;
4403  }
4404  unsigned NumElements = Context.getTypeSize(OldElemTy) *
4405  OldVT->getNumElements() /
4406  Context.getTypeSize(NewElemTy);
4407  NewTy =
4408  Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4409  }
4410 
4411  if (NewTy.isNull()) {
4412  Diag(AttrLoc, diag::err_mode_wrong_type);
4413  return;
4414  }
4415 
4416  // Install the new type.
4417  if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4418  TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4419  else if (auto *ED = dyn_cast<EnumDecl>(D))
4420  ED->setIntegerType(NewTy);
4421  else
4422  cast<ValueDecl>(D)->setType(NewTy);
4423 
4424  D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4425 }
4426 
4427 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4428  D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4429 }
4430 
4431 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
4432  const AttributeCommonInfo &CI,
4433  const IdentifierInfo *Ident) {
4434  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4435  Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4436  Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4437  return nullptr;
4438  }
4439 
4440  if (D->hasAttr<AlwaysInlineAttr>())
4441  return nullptr;
4442 
4443  return ::new (Context) AlwaysInlineAttr(Context, CI);
4444 }
4445 
4446 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4447  const ParsedAttr &AL) {
4448  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4449  // Attribute applies to Var but not any subclass of it (like ParmVar,
4450  // ImplicitParm or VarTemplateSpecialization).
4451  if (VD->getKind() != Decl::Var) {
4452  Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4453  << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4455  return nullptr;
4456  }
4457  // Attribute does not apply to non-static local variables.
4458  if (VD->hasLocalStorage()) {
4459  Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4460  return nullptr;
4461  }
4462  }
4463 
4464  return ::new (Context) InternalLinkageAttr(Context, AL);
4465 }
4466 InternalLinkageAttr *
4467 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4468  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4469  // Attribute applies to Var but not any subclass of it (like ParmVar,
4470  // ImplicitParm or VarTemplateSpecialization).
4471  if (VD->getKind() != Decl::Var) {
4472  Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4473  << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4475  return nullptr;
4476  }
4477  // Attribute does not apply to non-static local variables.
4478  if (VD->hasLocalStorage()) {
4479  Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4480  return nullptr;
4481  }
4482  }
4483 
4484  return ::new (Context) InternalLinkageAttr(Context, AL);
4485 }
4486 
4487 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
4488  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4489  Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4490  Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4491  return nullptr;
4492  }
4493 
4494  if (D->hasAttr<MinSizeAttr>())
4495  return nullptr;
4496 
4497  return ::new (Context) MinSizeAttr(Context, CI);
4498 }
4499 
4500 SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
4501  StringRef Name) {
4502  if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) {
4503  if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
4504  Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
4505  << PrevSNA << &SNA;
4506  Diag(SNA.getLoc(), diag::note_conflicting_attribute);
4507  }
4508 
4509  D->dropAttr<SwiftNameAttr>();
4510  }
4511  return ::new (Context) SwiftNameAttr(Context, SNA, Name);
4512 }
4513 
4514 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
4515  const AttributeCommonInfo &CI) {
4516  if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4517  Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4518  Diag(CI.getLoc(), diag::note_conflicting_attribute);
4519  D->dropAttr<AlwaysInlineAttr>();
4520  }
4521  if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4522  Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4523  Diag(CI.getLoc(), diag::note_conflicting_attribute);
4524  D->dropAttr<MinSizeAttr>();
4525  }
4526 
4527  if (D->hasAttr<OptimizeNoneAttr>())
4528  return nullptr;
4529 
4530  return ::new (Context) OptimizeNoneAttr(Context, CI);
4531 }
4532 
4533 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4534  if (AlwaysInlineAttr *Inline =
4535  S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
4536  D->addAttr(Inline);
4537 }
4538 
4539 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4540  if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
4541  D->addAttr(MinSize);
4542 }
4543 
4544 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4545  if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
4546  D->addAttr(Optnone);
4547 }
4548 
4549 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4550  const auto *VD = cast<VarDecl>(D);
4551  if (VD->hasLocalStorage()) {
4552  S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4553  return;
4554  }
4555  // constexpr variable may already get an implicit constant attr, which should
4556  // be replaced by the explicit constant attr.
4557  if (auto *A = D->getAttr<CUDAConstantAttr>()) {
4558  if (!A->isImplicit())
4559  return;
4560  D->dropAttr<CUDAConstantAttr>();
4561  }
4562  D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
4563 }
4564 
4565 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4566  const auto *VD = cast<VarDecl>(D);
4567  // extern __shared__ is only allowed on arrays with no length (e.g.
4568  // "int x[]").
4569  if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4570  !isa<IncompleteArrayType>(VD->getType())) {
4571  S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4572  return;
4573  }
4574  if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4575  S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4576  << S.CurrentCUDATarget())
4577  return;
4578  D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
4579 }
4580 
4581 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4582  const auto *FD = cast<FunctionDecl>(D);
4583  if (!FD->getReturnType()->isVoidType() &&
4584  !FD->getReturnType()->getAs<AutoType>() &&
4586  SourceRange RTRange = FD->getReturnTypeSourceRange();
4587  S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4588  << FD->getType()
4589  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4590  : FixItHint());
4591  return;
4592  }
4593  if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4594  if (Method->isInstance()) {
4595  S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4596  << Method;
4597  return;
4598  }
4599  S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4600  }
4601  // Only warn for "inline" when compiling for host, to cut down on noise.
4602  if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4603  S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4604 
4605  D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
4606  // In host compilation the kernel is emitted as a stub function, which is
4607  // a helper function for launching the kernel. The instructions in the helper
4608  // function has nothing to do with the source code of the kernel. Do not emit
4609  // debug info for the stub function to avoid confusing the debugger.
4610  if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice)
4611  D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
4612 }
4613 
4614 static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4615  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4616  if (VD->hasLocalStorage()) {
4617  S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4618  return;
4619  }
4620  }
4621 
4622  if (auto *A = D->getAttr<CUDADeviceAttr>()) {
4623  if (!A->isImplicit())
4624  return;
4625  D->dropAttr<CUDADeviceAttr>();
4626  }
4627  D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL));
4628 }
4629 
4630 static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4631  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4632  if (VD->hasLocalStorage()) {
4633  S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4634  return;
4635  }
4636  }
4637  if (!D->hasAttr<HIPManagedAttr>())
4638  D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL));
4639  if (!D->hasAttr<CUDADeviceAttr>())
4640  D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context));
4641 }
4642 
4643 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4644  const auto *Fn = cast<FunctionDecl>(D);
4645  if (!Fn->isInlineSpecified()) {
4646  S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4647  return;
4648  }
4649 
4650  if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
4651  S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
4652 
4653  D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
4654 }
4655 
4656 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4657  if (hasDeclarator(D)) return;
4658 
4659  // Diagnostic is emitted elsewhere: here we store the (valid) AL
4660  // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4661  CallingConv CC;
4662  if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4663  return;
4664 
4665  if (!isa<ObjCMethodDecl>(D)) {
4666  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4667  << AL << ExpectedFunctionOrMethod;
4668  return;
4669  }
4670 
4671  switch (AL.getKind()) {
4672  case ParsedAttr::AT_FastCall:
4673  D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
4674  return;
4675  case ParsedAttr::AT_StdCall:
4676  D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
4677  return;
4678  case ParsedAttr::AT_ThisCall:
4679  D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
4680  return;
4681  case ParsedAttr::AT_CDecl:
4682  D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
4683  return;
4684  case ParsedAttr::AT_Pascal:
4685  D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
4686  return;
4687  case ParsedAttr::AT_SwiftCall:
4688  D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
4689  return;
4690  case ParsedAttr::AT_SwiftAsyncCall:
4691  D->addAttr(::new (S.Context) SwiftAsyncCallAttr(S.Context, AL));
4692  return;
4693  case ParsedAttr::AT_VectorCall:
4694  D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
4695  return;
4696  case ParsedAttr::AT_MSABI:
4697  D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
4698  return;
4699  case ParsedAttr::AT_SysVABI:
4700  D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
4701  return;
4702  case ParsedAttr::AT_RegCall:
4703  D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
4704  return;
4705  case ParsedAttr::AT_Pcs: {
4706  PcsAttr::PCSType PCS;
4707  switch (CC) {
4708  case CC_AAPCS:
4709  PCS = PcsAttr::AAPCS;
4710  break;
4711  case CC_AAPCS_VFP:
4712  PCS = PcsAttr::AAPCS_VFP;
4713  break;
4714  default:
4715  llvm_unreachable("unexpected calling convention in pcs attribute");
4716  }
4717 
4718  D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
4719  return;
4720  }
4721  case ParsedAttr::AT_AArch64VectorPcs:
4722  D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
4723  return;
4724  case ParsedAttr::AT_IntelOclBicc:
4725  D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
4726  return;
4727  case ParsedAttr::AT_PreserveMost:
4728  D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
4729  return;
4730  case ParsedAttr::AT_PreserveAll:
4731  D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
4732  return;
4733  default:
4734  llvm_unreachable("unexpected attribute kind");
4735  }
4736 }
4737 
4738 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4739  if (!AL.checkAtLeastNumArgs(S, 1))
4740  return;
4741 
4742  std::vector<StringRef> DiagnosticIdentifiers;
4743  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4744  StringRef RuleName;
4745 
4746  if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4747  return;
4748 
4749  // FIXME: Warn if the rule name is unknown. This is tricky because only
4750  // clang-tidy knows about available rules.
4751  DiagnosticIdentifiers.push_back(RuleName);
4752  }
4753  D->addAttr(::new (S.Context)
4754  SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
4755  DiagnosticIdentifiers.size()));
4756 }
4757 
4758 static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4759  TypeSourceInfo *DerefTypeLoc = nullptr;
4760  QualType ParmType;
4761  if (AL.hasParsedType()) {
4762  ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc);
4763 
4764  unsigned SelectIdx = ~0U;
4765  if (ParmType->isReferenceType())
4766  SelectIdx = 0;
4767  else if (ParmType->isArrayType())
4768  SelectIdx = 1;
4769 
4770  if (SelectIdx != ~0U) {
4771  S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
4772  << SelectIdx << AL;
4773  return;
4774  }
4775  }
4776 
4777  // To check if earlier decl attributes do not conflict the newly parsed ones
4778  // we always add (and check) the attribute to the canonical decl. We need
4779  // to repeat the check for attribute mutual exclusion because we're attaching
4780  // all of the attributes to the canonical declaration rather than the current
4781  // declaration.
4782  D = D->getCanonicalDecl();
4783  if (AL.getKind() == ParsedAttr::AT_Owner) {
4784  if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
4785  return;
4786  if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
4787  const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
4788  ? OAttr->getDerefType().getTypePtr()
4789  : nullptr;
4790  if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4791  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4792  << AL << OAttr;
4793  S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
4794  }
4795  return;
4796  }
4797  for (Decl *Redecl : D->redecls()) {
4798  Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
4799  }
4800  } else {
4801  if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
4802  return;
4803  if (const auto *PAttr = D->getAttr<PointerAttr>()) {
4804  const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
4805  ? PAttr->getDerefType().getTypePtr()
4806  : nullptr;
4807  if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4808  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4809  << AL << PAttr;
4810  S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
4811  }
4812  return;
4813  }
4814  for (Decl *Redecl : D->redecls()) {
4815  Redecl->addAttr(::new (S.Context)
4816  PointerAttr(S.Context, AL, DerefTypeLoc));
4817  }
4818  }
4819 }
4820 
4822  const FunctionDecl *FD) {
4823  if (Attrs.isInvalid())
4824  return true;
4825 
4826  if (Attrs.hasProcessingCache()) {
4827  CC = (CallingConv) Attrs.getProcessingCache();
4828  return false;
4829  }
4830 
4831  unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4832  if (!Attrs.checkExactlyNumArgs(*this, ReqArgs)) {
4833  Attrs.setInvalid();
4834  return true;
4835  }
4836 
4837  // TODO: diagnose uses of these conventions on the wrong target.
4838  switch (Attrs.getKind()) {
4839  case ParsedAttr::AT_CDecl:
4840  CC = CC_C;
4841  break;
4842  case ParsedAttr::AT_FastCall:
4843  CC = CC_X86FastCall;
4844  break;
4845  case ParsedAttr::AT_StdCall:
4846  CC = CC_X86StdCall;
4847  break;
4848  case ParsedAttr::AT_ThisCall:
4849  CC = CC_X86ThisCall;
4850  break;
4851  case ParsedAttr::AT_Pascal:
4852  CC = CC_X86Pascal;
4853  break;
4854  case ParsedAttr::AT_SwiftCall:
4855  CC = CC_Swift;
4856  break;
4857  case ParsedAttr::AT_SwiftAsyncCall:
4858  CC = CC_SwiftAsync;
4859  break;
4860  case ParsedAttr::AT_VectorCall:
4861  CC = CC_X86VectorCall;
4862  break;
4863  case ParsedAttr::AT_AArch64VectorPcs:
4864  CC = CC_AArch64VectorCall;
4865  break;
4866  case ParsedAttr::AT_RegCall:
4867  CC = CC_X86RegCall;
4868  break;
4869  case ParsedAttr::AT_MSABI:
4870  CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4871  CC_Win64;
4872  break;
4873  case ParsedAttr::AT_SysVABI:
4874  CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4875  CC_C;
4876  break;
4877  case ParsedAttr::AT_Pcs: {
4878  StringRef StrRef;
4879  if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4880  Attrs.setInvalid();
4881  return true;
4882  }
4883  if (StrRef == "aapcs") {
4884  CC = CC_AAPCS;
4885  break;
4886  } else if (StrRef == "aapcs-vfp") {
4887  CC = CC_AAPCS_VFP;
4888  break;
4889  }
4890 
4891  Attrs.setInvalid();
4892  Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4893  return true;
4894  }
4895  case ParsedAttr::AT_IntelOclBicc:
4896  CC = CC_IntelOclBicc;
4897  break;
4898  case ParsedAttr::AT_PreserveMost:
4899  CC = CC_PreserveMost;
4900  break;
4901  case ParsedAttr::AT_PreserveAll:
4902  CC = CC_PreserveAll;
4903  break;
4904  default: llvm_unreachable("unexpected attribute kind");
4905  }
4906 
4908  const TargetInfo &TI = Context.getTargetInfo();
4909  // CUDA functions may have host and/or device attributes which indicate
4910  // their targeted execution environment, therefore the calling convention
4911  // of functions in CUDA should be checked against the target deduced based
4912  // on their host/device attributes.
4913  if (LangOpts.CUDA) {
4914  auto *Aux = Context.getAuxTargetInfo();
4915  auto CudaTarget = IdentifyCUDATarget(FD);
4916  bool CheckHost = false, CheckDevice = false;
4917  switch (CudaTarget) {
4918  case CFT_HostDevice:
4919  CheckHost = true;
4920  CheckDevice = true;
4921  break;
4922  case CFT_Host:
4923  CheckHost = true;
4924  break;
4925  case CFT_Device:
4926  case CFT_Global:
4927  CheckDevice = true;
4928  break;
4929  case CFT_InvalidTarget:
4930  llvm_unreachable("unexpected cuda target");
4931  }
4932  auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
4933  auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
4934  if (CheckHost && HostTI)
4935  A = HostTI->checkCallingConvention(CC);
4936  if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
4937  A = DeviceTI->checkCallingConvention(CC);
4938  } else {
4939  A = TI.checkCallingConvention(CC);
4940  }
4941 
4942  switch (A) {
4943  case TargetInfo::CCCR_OK:
4944  break;
4945 
4947  // Treat an ignored convention as if it was an explicit C calling convention
4948  // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
4949  // that command line flags that change the default convention to
4950  // __vectorcall don't affect declarations marked __stdcall.
4951  CC = CC_C;
4952  break;
4953 
4955  Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
4956  << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4957  break;
4958 
4959  case TargetInfo::CCCR_Warning: {
4960  Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
4961  << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4962 
4963  // This convention is not valid for the target. Use the default function or
4964  // method calling convention.
4965  bool IsCXXMethod = false, IsVariadic = false;
4966  if (FD) {
4967  IsCXXMethod = FD->isCXXInstanceMember();
4968  IsVariadic = FD->isVariadic();
4969  }
4970  CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4971  break;
4972  }
4973  }
4974 
4975  Attrs.setProcessingCache((unsigned) CC);
4976  return false;
4977 }
4978 
4979 /// Pointer-like types in the default address space.
4981  if (!Ty->hasPointerRepresentation())
4982  return Ty->isDependentType();
4984 }
4985 
4986 /// Pointers and references in the default address space.
4988  if (const auto *PtrType = Ty->getAs<PointerType>()) {
4989  Ty = PtrType->getPointeeType();
4990  } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4991  Ty = RefType->getPointeeType();
4992  } else {
4993  return Ty->isDependentType();
4994  }
4995  return Ty.getAddressSpace() == LangAS::Default;
4996 }
4997 
4998 /// Pointers and references to pointers in the default address space.
5000  if (const auto *PtrType = Ty->getAs<PointerType>()) {
5001  Ty = PtrType->getPointeeType();
5002  } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
5003  Ty = RefType->getPointeeType();
5004  } else {
5005  return Ty->isDependentType();
5006  }
5007  if (!Ty.getQualifiers().empty())
5008  return false;
5009  return isValidSwiftContextType(Ty);
5010 }
5011 
5013  ParameterABI abi) {
5014 
5015  QualType type = cast<ParmVarDecl>(D)->getType();
5016 
5017  if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
5018  if (existingAttr->getABI() != abi) {
5019  Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
5020  << getParameterABISpelling(abi) << existingAttr;
5021  Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
5022  return;
5023  }
5024  }
5025 
5026  switch (abi) {
5028  llvm_unreachable("explicit attribute for ordinary parameter ABI?");
5029 
5031  if (!isValidSwiftContextType(type)) {
5032  Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5033  << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
5034  }
5035  D->addAttr(::new (Context) SwiftContextAttr(Context, CI));
5036  return;
5037 
5039  if (!isValidSwiftContextType(type)) {
5040  Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5041  << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
5042  }
5043  D->addAttr(::new (Context) SwiftAsyncContextAttr(Context, CI));
5044  return;
5045 
5048  Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5049  << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type;
5050  }
5051  D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI));
5052  return;
5053 
5056  Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5057  << getParameterABISpelling(abi) << /*pointer*/ 0 << type;
5058  }
5059  D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI));
5060  return;
5061  }
5062  llvm_unreachable("bad parameter ABI attribute");
5063 }
5064 
5065 /// Checks a regparm attribute, returning true if it is ill-formed and
5066 /// otherwise setting numParams to the appropriate value.
5067 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
5068  if (AL.isInvalid())
5069  return true;
5070 
5071  if (!AL.checkExactlyNumArgs(*this, 1)) {
5072  AL.setInvalid();
5073  return true;
5074  }
5075 
5076  uint32_t NP;
5077  Expr *NumParamsExpr = AL.getArgAsExpr(0);
5078  if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
5079  AL.setInvalid();
5080  return true;
5081  }
5082 
5083  if (Context.getTargetInfo().getRegParmMax() == 0) {
5084  Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
5085  << NumParamsExpr->getSourceRange();
5086  AL.setInvalid();
5087  return true;
5088  }
5089 
5090  numParams = NP;
5091  if (numParams > Context.getTargetInfo().getRegParmMax()) {
5092  Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
5093  << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
5094  AL.setInvalid();
5095  return true;
5096  }
5097 
5098  return false;
5099 }
5100 
5101 // Checks whether an argument of launch_bounds attribute is
5102 // acceptable, performs implicit conversion to Rvalue, and returns
5103 // non-nullptr Expr result on success. Otherwise, it returns nullptr
5104 // and may output an error.
5106  const CUDALaunchBoundsAttr &AL,
5107  const unsigned Idx) {
5109  return nullptr;
5110 
5111  // Accept template arguments for now as they depend on something else.
5112  // We'll get to check them when they eventually get instantiated.
5113  if (E->isValueDependent())
5114  return E;
5115 
5117  if (!(I = E->getIntegerConstantExpr(S.Context))) {
5118  S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
5119  << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
5120  return nullptr;
5121  }
5122  // Make sure we can fit it in 32 bits.
5123  if (!I->isIntN(32)) {
5124  S.Diag(E->getExprLoc(), diag::err_ice_too_large)
5125  << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
5126  return nullptr;
5127  }
5128  if (*I < 0)
5129  S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
5130  << &AL << Idx << E->getSourceRange();
5131 
5132  // We may need to perform implicit conversion of the argument.
5134  S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
5135  ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
5136  assert(!ValArg.isInvalid() &&
5137  "Unexpected PerformCopyInitialization() failure.");
5138 
5139  return ValArg.getAs<Expr>();
5140 }
5141 
5143  Expr *MaxThreads, Expr *MinBlocks) {
5144  CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks);
5145  MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
5146  if (MaxThreads == nullptr)
5147  return;
5148 
5149  if (MinBlocks) {
5150  MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
5151  if (MinBlocks == nullptr)
5152  return;
5153  }
5154 
5155  D->addAttr(::new (Context)
5156  CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks));
5157 }
5158 
5159 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5160  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
5161  return;
5162 
5163  S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0),
5164  AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr);
5165 }
5166 
5168  const ParsedAttr &AL) {
5169  if (!AL.isArgIdent(0)) {
5170  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5171  << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
5172  return;
5173  }
5174 
5175  ParamIdx ArgumentIdx;
5176  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
5177  ArgumentIdx))
5178  return;
5179 
5180  ParamIdx TypeTagIdx;
5181  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
5182  TypeTagIdx))
5183  return;
5184 
5185  bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag";
5186  if (IsPointer) {
5187  // Ensure that buffer has a pointer type.
5188  unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
5189  if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
5190  !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
5191  S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
5192  }
5193 
5194  D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
5195  S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx,
5196  IsPointer));
5197 }
5198 
5200  const ParsedAttr &AL) {
5201  if (!AL.isArgIdent(0)) {
5202  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5203  << AL << 1 << AANT_ArgumentIdentifier;
5204  return;
5205  }
5206 
5207  if (!AL.checkExactlyNumArgs(S, 1))
5208  return;
5209 
5210  if (!isa<VarDecl>(D)) {
5211  S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
5212  << AL << ExpectedVariable;
5213  return;
5214  }
5215 
5216  IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
5217  TypeSourceInfo *MatchingCTypeLoc = nullptr;
5218  S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
5219  assert(MatchingCTypeLoc && "no type source info for attribute argument");
5220 
5221  D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(
5222  S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(),
5223  AL.getMustBeNull()));
5224 }
5225 
5226 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5227  ParamIdx ArgCount;
5228 
5229  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
5230  ArgCount,
5231  true /* CanIndexImplicitThis */))
5232  return;
5233 
5234  // ArgCount isn't a parameter index [0;n), it's a count [1;n]
5235  D->addAttr(::new (S.Context)
5236  XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
5237 }
5238 
5240  const ParsedAttr &AL) {
5241  uint32_t Count = 0, Offset = 0;
5242  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Count, 0, true))
5243  return;
5244  if (AL.getNumArgs() == 2) {
5245  Expr *Arg = AL.getArgAsExpr(1);
5246  if (!checkUInt32Argument(S, AL, Arg, Offset, 1, true))
5247  return;
5248  if (Count < Offset) {
5249  S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range)
5250  << &AL << 0 << Count << Arg->getBeginLoc();
5251  return;
5252  }
5253  }
5254  D->addAttr(::new (S.Context)
5255  PatchableFunctionEntryAttr(S.Context, AL, Count, Offset));
5256 }
5257 
5258 namespace {
5259 struct IntrinToName {
5260  uint32_t Id;
5261  int32_t FullName;
5262  int32_t ShortName;
5263 };
5264 } // unnamed namespace
5265 
5266 static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName,
5268  const char *IntrinNames) {
5269  if (AliasName.startswith("__arm_"))
5270  AliasName = AliasName.substr(6);
5271  const IntrinToName *It = std::lower_bound(
5272  Map.begin(), Map.end(), BuiltinID,
5273  [](const IntrinToName &L, unsigned Id) { return L.Id < Id; });
5274  if (It == Map.end() || It->Id != BuiltinID)
5275  return false;
5276  StringRef FullName(&IntrinNames[It->FullName]);
5277  if (AliasName == FullName)
5278  return true;
5279  if (It->ShortName == -1)
5280  return false;
5281  StringRef ShortName(&IntrinNames[It->ShortName]);
5282  return AliasName == ShortName;
5283 }
5284 
5285 static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) {
5286 #include "clang/Basic/arm_mve_builtin_aliases.inc"
5287  // The included file defines:
5288  // - ArrayRef<IntrinToName> Map
5289  // - const char IntrinNames[]
5290  return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5291 }
5292 
5293 static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) {
5294 #include "clang/Basic/arm_cde_builtin_aliases.inc"
5295  return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5296 }
5297 
5298 static bool ArmSveAliasValid(ASTContext &Context, unsigned BuiltinID,
5299  StringRef AliasName) {
5300  if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
5301  BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(BuiltinID);
5302  return BuiltinID >= AArch64::FirstSVEBuiltin &&
5303  BuiltinID <= AArch64::LastSVEBuiltin;
5304 }
5305 
5306 static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {