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