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