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