clang  7.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 
1848  D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
1850 }
1851 
1852 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1853  StringRef Str;
1854  if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1855  return;
1856 
1857  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1858  S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1859  return;
1860  }
1861  if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1862  S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1863  }
1864 
1865  // Aliases should be on declarations, not definitions.
1866  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1867  if (FD->isThisDeclarationADefinition()) {
1868  S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0;
1869  return;
1870  }
1871  } else {
1872  const auto *VD = cast<VarDecl>(D);
1873  if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1874  S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0;
1875  return;
1876  }
1877  }
1878 
1879  // FIXME: check if target symbol exists in current file
1880 
1881  D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1883 }
1884 
1885 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1886  if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
1887  return;
1888 
1889  D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1891 }
1892 
1893 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1894  if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
1895  return;
1896 
1897  D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1899 }
1900 
1901 static void handleTLSModelAttr(Sema &S, Decl *D,
1902  const AttributeList &Attr) {
1903  StringRef Model;
1904  SourceLocation LiteralLoc;
1905  // Check that it is a string.
1906  if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1907  return;
1908 
1909  // Check that the value.
1910  if (Model != "global-dynamic" && Model != "local-dynamic"
1911  && Model != "initial-exec" && Model != "local-exec") {
1912  S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1913  return;
1914  }
1915 
1916  D->addAttr(::new (S.Context)
1917  TLSModelAttr(Attr.getRange(), S.Context, Model,
1919 }
1920 
1921 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1922  QualType ResultType = getFunctionOrMethodResultType(D);
1923  if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1924  D->addAttr(::new (S.Context) RestrictAttr(
1925  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1926  return;
1927  }
1928 
1929  S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1931 }
1932 
1933 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1934  if (S.LangOpts.CPlusPlus) {
1935  S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1936  << Attr.getName() << AttributeLangSupport::Cpp;
1937  return;
1938  }
1939 
1940  if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1942  D->addAttr(CA);
1943 }
1944 
1945 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1946  if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1947  Attr.getName()))
1948  return;
1949 
1950  if (Attr.isDeclspecAttribute()) {
1951  const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
1952  const auto &Arch = Triple.getArch();
1953  if (Arch != llvm::Triple::x86 &&
1954  (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
1955  S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_on_arch)
1956  << Attr.getName() << Triple.getArchName();
1957  return;
1958  }
1959  }
1960 
1961  D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1963 }
1964 
1965 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &Attrs) {
1966  if (hasDeclarator(D)) return;
1967 
1968  if (S.CheckNoReturnAttr(Attrs))
1969  return;
1970 
1971  if (!isa<ObjCMethodDecl>(D)) {
1972  S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
1973  << Attrs.getName() << ExpectedFunctionOrMethod;
1974  return;
1975  }
1976 
1977  D->addAttr(::new (S.Context) NoReturnAttr(
1978  Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
1979 }
1980 
1982  const AttributeList &Attr) {
1983  if (S.CheckNoCallerSavedRegsAttr(Attr))
1984  return;
1985 
1986  D->addAttr(::new (S.Context) AnyX86NoCallerSavedRegistersAttr(
1987  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1988 }
1989 
1991  if (!checkAttributeNumArgs(*this, Attrs, 0)) {
1992  Attrs.setInvalid();
1993  return true;
1994  }
1995 
1996  return false;
1997 }
1998 
2000  // Check whether the attribute is valid on the current target.
2001  if (!Attr.existsInTarget(Context.getTargetInfo())) {
2002  Diag(Attr.getLoc(), diag::warn_unknown_attribute_ignored) << Attr.getName();
2003  Attr.setInvalid();
2004  return true;
2005  }
2006 
2007  if (!checkAttributeNumArgs(*this, Attr, 0)) {
2008  Attr.setInvalid();
2009  return true;
2010  }
2011 
2012  return false;
2013 }
2014 
2016  const AttributeList &Attr) {
2017 
2018  // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2019  // because 'analyzer_noreturn' does not impact the type.
2020  if (!isFunctionOrMethodOrBlock(D)) {
2021  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2022  if (!VD || (!VD->getType()->isBlockPointerType() &&
2023  !VD->getType()->isFunctionPointerType())) {
2024  S.Diag(Attr.getLoc(),
2025  Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
2026  : diag::warn_attribute_wrong_decl_type)
2028  return;
2029  }
2030  }
2031 
2032  D->addAttr(::new (S.Context)
2033  AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
2035 }
2036 
2037 // PS3 PPU-specific.
2038 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2039 /*
2040  Returning a Vector Class in Registers
2041 
2042  According to the PPU ABI specifications, a class with a single member of
2043  vector type is returned in memory when used as the return value of a function.
2044  This results in inefficient code when implementing vector classes. To return
2045  the value in a single vector register, add the vecreturn attribute to the
2046  class definition. This attribute is also applicable to struct types.
2047 
2048  Example:
2049 
2050  struct Vector
2051  {
2052  __vector float xyzw;
2053  } __attribute__((vecreturn));
2054 
2055  Vector Add(Vector lhs, Vector rhs)
2056  {
2057  Vector result;
2058  result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2059  return result; // This will be returned in a register
2060  }
2061 */
2062  if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2063  S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
2064  return;
2065  }
2066 
2067  RecordDecl *record = cast<RecordDecl>(D);
2068  int count = 0;
2069 
2070  if (!isa<CXXRecordDecl>(record)) {
2071  S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2072  return;
2073  }
2074 
2075  if (!cast<CXXRecordDecl>(record)->isPOD()) {
2076  S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2077  return;
2078  }
2079 
2080  for (const auto *I : record->fields()) {
2081  if ((count == 1) || !I->getType()->isVectorType()) {
2082  S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2083  return;
2084  }
2085  count++;
2086  }
2087 
2088  D->addAttr(::new (S.Context)
2089  VecReturnAttr(Attr.getRange(), S.Context,
2091 }
2092 
2094  const AttributeList &Attr) {
2095  if (isa<ParmVarDecl>(D)) {
2096  // [[carries_dependency]] can only be applied to a parameter if it is a
2097  // parameter of a function declaration or lambda.
2099  S.Diag(Attr.getLoc(),
2100  diag::err_carries_dependency_param_not_function_decl);
2101  return;
2102  }
2103  }
2104 
2105  D->addAttr(::new (S.Context) CarriesDependencyAttr(
2106  Attr.getRange(), S.Context,
2108 }
2109 
2110 static void handleNotTailCalledAttr(Sema &S, Decl *D,
2111  const AttributeList &Attr) {
2112  if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
2113  Attr.getName()))
2114  return;
2115 
2116  D->addAttr(::new (S.Context) NotTailCalledAttr(
2117  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2118 }
2119 
2121  const AttributeList &Attr) {
2122  if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
2123  Attr.getName()))
2124  return;
2125 
2126  D->addAttr(::new (S.Context) DisableTailCallsAttr(
2127  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2128 }
2129 
2130 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2131  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2132  if (VD->hasLocalStorage()) {
2133  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2134  return;
2135  }
2136  } else if (!isFunctionOrMethod(D)) {
2137  S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2138  << Attr.getName() << ExpectedVariableOrFunction;
2139  return;
2140  }
2141 
2142  D->addAttr(::new (S.Context)
2143  UsedAttr(Attr.getRange(), S.Context,
2145 }
2146 
2147 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2148  bool IsCXX17Attr = Attr.isCXX11Attribute() && !Attr.getScopeName();
2149 
2150  if (IsCXX17Attr && isa<VarDecl>(D)) {
2151  // The C++17 spelling of this attribute cannot be applied to a static data
2152  // member per [dcl.attr.unused]p2.
2153  if (cast<VarDecl>(D)->isStaticDataMember()) {
2154  S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2155  << Attr.getName() << ExpectedForMaybeUnused;
2156  return;
2157  }
2158  }
2159 
2160  // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2161  // about using it as an extension.
2162  if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2163  S.Diag(Attr.getLoc(), diag::ext_cxx17_attr) << Attr.getName();
2164 
2165  D->addAttr(::new (S.Context) UnusedAttr(
2166  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2167 }
2168 
2169 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2170  uint32_t priority = ConstructorAttr::DefaultPriority;
2171  if (Attr.getNumArgs() &&
2172  !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2173  return;
2174 
2175  D->addAttr(::new (S.Context)
2176  ConstructorAttr(Attr.getRange(), S.Context, priority,
2178 }
2179 
2180 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2181  uint32_t priority = DestructorAttr::DefaultPriority;
2182  if (Attr.getNumArgs() &&
2183  !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2184  return;
2185 
2186  D->addAttr(::new (S.Context)
2187  DestructorAttr(Attr.getRange(), S.Context, priority,
2189 }
2190 
2191 template <typename AttrTy>
2192 static void handleAttrWithMessage(Sema &S, Decl *D,
2193  const AttributeList &Attr) {
2194  // Handle the case where the attribute has a text message.
2195  StringRef Str;
2196  if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2197  return;
2198 
2199  D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
2201 }
2202 
2204  const AttributeList &Attr) {
2205  if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2206  S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2207  << Attr.getName() << Attr.getRange();
2208  return;
2209  }
2210 
2211  D->addAttr(::new (S.Context)
2212  ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
2214 }
2215 
2217  IdentifierInfo *Platform,
2218  VersionTuple Introduced,
2219  VersionTuple Deprecated,
2220  VersionTuple Obsoleted) {
2221  StringRef PlatformName
2222  = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2223  if (PlatformName.empty())
2224  PlatformName = Platform->getName();
2225 
2226  // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2227  // of these steps are needed).
2228  if (!Introduced.empty() && !Deprecated.empty() &&
2229  !(Introduced <= Deprecated)) {
2230  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2231  << 1 << PlatformName << Deprecated.getAsString()
2232  << 0 << Introduced.getAsString();
2233  return true;
2234  }
2235 
2236  if (!Introduced.empty() && !Obsoleted.empty() &&
2237  !(Introduced <= Obsoleted)) {
2238  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2239  << 2 << PlatformName << Obsoleted.getAsString()
2240  << 0 << Introduced.getAsString();
2241  return true;
2242  }
2243 
2244  if (!Deprecated.empty() && !Obsoleted.empty() &&
2245  !(Deprecated <= Obsoleted)) {
2246  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2247  << 2 << PlatformName << Obsoleted.getAsString()
2248  << 1 << Deprecated.getAsString();
2249  return true;
2250  }
2251 
2252  return false;
2253 }
2254 
2255 /// \brief Check whether the two versions match.
2256 ///
2257 /// If either version tuple is empty, then they are assumed to match. If
2258 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2259 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2260  bool BeforeIsOkay) {
2261  if (X.empty() || Y.empty())
2262  return true;
2263 
2264  if (X == Y)
2265  return true;
2266 
2267  if (BeforeIsOkay && X < Y)
2268  return true;
2269 
2270  return false;
2271 }
2272 
2274  IdentifierInfo *Platform,
2275  bool Implicit,
2276  VersionTuple Introduced,
2277  VersionTuple Deprecated,
2278  VersionTuple Obsoleted,
2279  bool IsUnavailable,
2280  StringRef Message,
2281  bool IsStrict,
2282  StringRef Replacement,
2284  unsigned AttrSpellingListIndex) {
2285  VersionTuple MergedIntroduced = Introduced;
2286  VersionTuple MergedDeprecated = Deprecated;
2287  VersionTuple MergedObsoleted = Obsoleted;
2288  bool FoundAny = false;
2289  bool OverrideOrImpl = false;
2290  switch (AMK) {
2291  case AMK_None:
2292  case AMK_Redeclaration:
2293  OverrideOrImpl = false;
2294  break;
2295 
2296  case AMK_Override:
2297  case AMK_ProtocolImplementation:
2298  OverrideOrImpl = true;
2299  break;
2300  }
2301 
2302  if (D->hasAttrs()) {
2303  AttrVec &Attrs = D->getAttrs();
2304  for (unsigned i = 0, e = Attrs.size(); i != e;) {
2305  const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2306  if (!OldAA) {
2307  ++i;
2308  continue;
2309  }
2310 
2311  IdentifierInfo *OldPlatform = OldAA->getPlatform();
2312  if (OldPlatform != Platform) {
2313  ++i;
2314  continue;
2315  }
2316 
2317  // If there is an existing availability attribute for this platform that
2318  // is explicit and the new one is implicit use the explicit one and
2319  // discard the new implicit attribute.
2320  if (!OldAA->isImplicit() && Implicit) {
2321  return nullptr;
2322  }
2323 
2324  // If there is an existing attribute for this platform that is implicit
2325  // and the new attribute is explicit then erase the old one and
2326  // continue processing the attributes.
2327  if (!Implicit && OldAA->isImplicit()) {
2328  Attrs.erase(Attrs.begin() + i);
2329  --e;
2330  continue;
2331  }
2332 
2333  FoundAny = true;
2334  VersionTuple OldIntroduced = OldAA->getIntroduced();
2335  VersionTuple OldDeprecated = OldAA->getDeprecated();
2336  VersionTuple OldObsoleted = OldAA->getObsoleted();
2337  bool OldIsUnavailable = OldAA->getUnavailable();
2338 
2339  if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2340  !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2341  !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2342  !(OldIsUnavailable == IsUnavailable ||
2343  (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2344  if (OverrideOrImpl) {
2345  int Which = -1;
2346  VersionTuple FirstVersion;
2347  VersionTuple SecondVersion;
2348  if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2349  Which = 0;
2350  FirstVersion = OldIntroduced;
2351  SecondVersion = Introduced;
2352  } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2353  Which = 1;
2354  FirstVersion = Deprecated;
2355  SecondVersion = OldDeprecated;
2356  } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2357  Which = 2;
2358  FirstVersion = Obsoleted;
2359  SecondVersion = OldObsoleted;
2360  }
2361 
2362  if (Which == -1) {
2363  Diag(OldAA->getLocation(),
2364  diag::warn_mismatched_availability_override_unavail)
2365  << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2366  << (AMK == AMK_Override);
2367  } else {
2368  Diag(OldAA->getLocation(),
2369  diag::warn_mismatched_availability_override)
2370  << Which
2371  << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2372  << FirstVersion.getAsString() << SecondVersion.getAsString()
2373  << (AMK == AMK_Override);
2374  }
2375  if (AMK == AMK_Override)
2376  Diag(Range.getBegin(), diag::note_overridden_method);
2377  else
2378  Diag(Range.getBegin(), diag::note_protocol_method);
2379  } else {
2380  Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2381  Diag(Range.getBegin(), diag::note_previous_attribute);
2382  }
2383 
2384  Attrs.erase(Attrs.begin() + i);
2385  --e;
2386  continue;
2387  }
2388 
2389  VersionTuple MergedIntroduced2 = MergedIntroduced;
2390  VersionTuple MergedDeprecated2 = MergedDeprecated;
2391  VersionTuple MergedObsoleted2 = MergedObsoleted;
2392 
2393  if (MergedIntroduced2.empty())
2394  MergedIntroduced2 = OldIntroduced;
2395  if (MergedDeprecated2.empty())
2396  MergedDeprecated2 = OldDeprecated;
2397  if (MergedObsoleted2.empty())
2398  MergedObsoleted2 = OldObsoleted;
2399 
2400  if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2401  MergedIntroduced2, MergedDeprecated2,
2402  MergedObsoleted2)) {
2403  Attrs.erase(Attrs.begin() + i);
2404  --e;
2405  continue;
2406  }
2407 
2408  MergedIntroduced = MergedIntroduced2;
2409  MergedDeprecated = MergedDeprecated2;
2410  MergedObsoleted = MergedObsoleted2;
2411  ++i;
2412  }
2413  }
2414 
2415  if (FoundAny &&
2416  MergedIntroduced == Introduced &&
2417  MergedDeprecated == Deprecated &&
2418  MergedObsoleted == Obsoleted)
2419  return nullptr;
2420 
2421  // Only create a new attribute if !OverrideOrImpl, but we want to do
2422  // the checking.
2423  if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2424  MergedDeprecated, MergedObsoleted) &&
2425  !OverrideOrImpl) {
2426  auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
2427  Introduced, Deprecated,
2428  Obsoleted, IsUnavailable, Message,
2429  IsStrict, Replacement,
2430  AttrSpellingListIndex);
2431  Avail->setImplicit(Implicit);
2432  return Avail;
2433  }
2434  return nullptr;
2435 }
2436 
2437 static void handleAvailabilityAttr(Sema &S, Decl *D,
2438  const AttributeList &Attr) {
2439  if (!checkAttributeNumArgs(S, Attr, 1))
2440  return;
2441  IdentifierLoc *Platform = Attr.getArgAsIdent(0);
2442  unsigned Index = Attr.getAttributeSpellingListIndex();
2443 
2444  IdentifierInfo *II = Platform->Ident;
2445  if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2446  S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2447  << Platform->Ident;
2448 
2449  NamedDecl *ND = dyn_cast<NamedDecl>(D);
2450  if (!ND) // We warned about this already, so just return.
2451  return;
2452 
2453  AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2454  AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2455  AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2456  bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2457  bool IsStrict = Attr.getStrictLoc().isValid();
2458  StringRef Str;
2459  if (const StringLiteral *SE =
2460  dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
2461  Str = SE->getString();
2462  StringRef Replacement;
2463  if (const StringLiteral *SE =
2464  dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2465  Replacement = SE->getString();
2466 
2467  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
2468  false/*Implicit*/,
2469  Introduced.Version,
2470  Deprecated.Version,
2471  Obsoleted.Version,
2472  IsUnavailable, Str,
2473  IsStrict, Replacement,
2475  Index);
2476  if (NewAttr)
2477  D->addAttr(NewAttr);
2478 
2479  // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2480  // matches before the start of the watchOS platform.
2481  if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2482  IdentifierInfo *NewII = nullptr;
2483  if (II->getName() == "ios")
2484  NewII = &S.Context.Idents.get("watchos");
2485  else if (II->getName() == "ios_app_extension")
2486  NewII = &S.Context.Idents.get("watchos_app_extension");
2487 
2488  if (NewII) {
2489  auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2490  if (Version.empty())
2491  return Version;
2492  auto Major = Version.getMajor();
2493  auto NewMajor = Major >= 9 ? Major - 7 : 0;
2494  if (NewMajor >= 2) {
2495  if (Version.getMinor().hasValue()) {
2496  if (Version.getSubminor().hasValue())
2497  return VersionTuple(NewMajor, Version.getMinor().getValue(),
2498  Version.getSubminor().getValue());
2499  else
2500  return VersionTuple(NewMajor, Version.getMinor().getValue());
2501  }
2502  }
2503 
2504  return VersionTuple(2, 0);
2505  };
2506 
2507  auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2508  auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2509  auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2510 
2511  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2512  Attr.getRange(),
2513  NewII,
2514  true/*Implicit*/,
2515  NewIntroduced,
2516  NewDeprecated,
2517  NewObsoleted,
2518  IsUnavailable, Str,
2519  IsStrict,
2520  Replacement,
2522  Index);
2523  if (NewAttr)
2524  D->addAttr(NewAttr);
2525  }
2526  } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2527  // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2528  // matches before the start of the tvOS platform.
2529  IdentifierInfo *NewII = nullptr;
2530  if (II->getName() == "ios")
2531  NewII = &S.Context.Idents.get("tvos");
2532  else if (II->getName() == "ios_app_extension")
2533  NewII = &S.Context.Idents.get("tvos_app_extension");
2534 
2535  if (NewII) {
2536  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2537  Attr.getRange(),
2538  NewII,
2539  true/*Implicit*/,
2540  Introduced.Version,
2541  Deprecated.Version,
2542  Obsoleted.Version,
2543  IsUnavailable, Str,
2544  IsStrict,
2545  Replacement,
2547  Index);
2548  if (NewAttr)
2549  D->addAttr(NewAttr);
2550  }
2551  }
2552 }
2553 
2555  const AttributeList &Attr) {
2556  if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
2557  return;
2558  assert(checkAttributeAtMostNumArgs(S, Attr, 3) &&
2559  "Invalid number of arguments in an external_source_symbol attribute");
2560 
2561  StringRef Language;
2562  if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(0)))
2563  Language = SE->getString();
2564  StringRef DefinedIn;
2565  if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(1)))
2566  DefinedIn = SE->getString();
2567  bool IsGeneratedDeclaration = Attr.getArgAsIdent(2) != nullptr;
2568 
2569  D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2570  Attr.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2572 }
2573 
2574 template <class T>
2576  typename T::VisibilityType value,
2577  unsigned attrSpellingListIndex) {
2578  T *existingAttr = D->getAttr<T>();
2579  if (existingAttr) {
2580  typename T::VisibilityType existingValue = existingAttr->getVisibility();
2581  if (existingValue == value)
2582  return nullptr;
2583  S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2584  S.Diag(range.getBegin(), diag::note_previous_attribute);
2585  D->dropAttr<T>();
2586  }
2587  return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2588 }
2589 
2590 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2591  VisibilityAttr::VisibilityType Vis,
2592  unsigned AttrSpellingListIndex) {
2593  return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2594  AttrSpellingListIndex);
2595 }
2596 
2597 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2598  TypeVisibilityAttr::VisibilityType Vis,
2599  unsigned AttrSpellingListIndex) {
2600  return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2601  AttrSpellingListIndex);
2602 }
2603 
2604 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2605  bool isTypeVisibility) {
2606  // Visibility attributes don't mean anything on a typedef.
2607  if (isa<TypedefNameDecl>(D)) {
2608  S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2609  << Attr.getName();
2610  return;
2611  }
2612 
2613  // 'type_visibility' can only go on a type or namespace.
2614  if (isTypeVisibility &&
2615  !(isa<TagDecl>(D) ||
2616  isa<ObjCInterfaceDecl>(D) ||
2617  isa<NamespaceDecl>(D))) {
2618  S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2619  << Attr.getName() << ExpectedTypeOrNamespace;
2620  return;
2621  }
2622 
2623  // Check that the argument is a string literal.
2624  StringRef TypeStr;
2625  SourceLocation LiteralLoc;
2626  if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2627  return;
2628 
2629  VisibilityAttr::VisibilityType type;
2630  if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2631  S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2632  << Attr.getName() << TypeStr;
2633  return;
2634  }
2635 
2636  // Complain about attempts to use protected visibility on targets
2637  // (like Darwin) that don't support it.
2638  if (type == VisibilityAttr::Protected &&
2640  S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2641  type = VisibilityAttr::Default;
2642  }
2643 
2644  unsigned Index = Attr.getAttributeSpellingListIndex();
2645  clang::Attr *newAttr;
2646  if (isTypeVisibility) {
2647  newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2648  (TypeVisibilityAttr::VisibilityType) type,
2649  Index);
2650  } else {
2651  newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2652  }
2653  if (newAttr)
2654  D->addAttr(newAttr);
2655 }
2656 
2658  const AttributeList &Attr) {
2659  ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2660  if (!Attr.isArgIdent(0)) {
2661  S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2662  << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2663  return;
2664  }
2665 
2666  IdentifierLoc *IL = Attr.getArgAsIdent(0);
2667  ObjCMethodFamilyAttr::FamilyKind F;
2668  if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2669  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2670  << IL->Ident;
2671  return;
2672  }
2673 
2674  if (F == ObjCMethodFamilyAttr::OMF_init &&
2675  !method->getReturnType()->isObjCObjectPointerType()) {
2676  S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2677  << method->getReturnType();
2678  // Ignore the attribute.
2679  return;
2680  }
2681 
2682  method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2683  S.Context, F,
2685 }
2686 
2687 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2688  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2689  QualType T = TD->getUnderlyingType();
2690  if (!T->isCARCBridgableType()) {
2691  S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2692  return;
2693  }
2694  }
2695  else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2696  QualType T = PD->getType();
2697  if (!T->isCARCBridgableType()) {
2698  S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2699  return;
2700  }
2701  }
2702  else {
2703  // It is okay to include this attribute on properties, e.g.:
2704  //
2705  // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2706  //
2707  // In this case it follows tradition and suppresses an error in the above
2708  // case.
2709  S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2710  }
2711  D->addAttr(::new (S.Context)
2712  ObjCNSObjectAttr(Attr.getRange(), S.Context,
2714 }
2715 
2717  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2718  QualType T = TD->getUnderlyingType();
2719  if (!T->isObjCObjectPointerType()) {
2720  S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2721  return;
2722  }
2723  } else {
2724  S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2725  return;
2726  }
2727  D->addAttr(::new (S.Context)
2728  ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2730 }
2731 
2732 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2733  if (!Attr.isArgIdent(0)) {
2734  S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2735  << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2736  return;
2737  }
2738 
2739  IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2740  BlocksAttr::BlockType type;
2741  if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2742  S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2743  << Attr.getName() << II;
2744  return;
2745  }
2746 
2747  D->addAttr(::new (S.Context)
2748  BlocksAttr(Attr.getRange(), S.Context, type,
2750 }
2751 
2752 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2753  unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2754  if (Attr.getNumArgs() > 0) {
2755  Expr *E = Attr.getArgAsExpr(0);
2756  llvm::APSInt Idx(32);
2757  if (E->isTypeDependent() || E->isValueDependent() ||
2758  !E->isIntegerConstantExpr(Idx, S.Context)) {
2759  S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2760  << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2761  << E->getSourceRange();
2762  return;
2763  }
2764 
2765  if (Idx.isSigned() && Idx.isNegative()) {
2766  S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2767  << E->getSourceRange();
2768  return;
2769  }
2770 
2771  sentinel = Idx.getZExtValue();
2772  }
2773 
2774  unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2775  if (Attr.getNumArgs() > 1) {
2776  Expr *E = Attr.getArgAsExpr(1);
2777  llvm::APSInt Idx(32);
2778  if (E->isTypeDependent() || E->isValueDependent() ||
2779  !E->isIntegerConstantExpr(Idx, S.Context)) {
2780  S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2781  << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2782  << E->getSourceRange();
2783  return;
2784  }
2785  nullPos = Idx.getZExtValue();
2786 
2787  if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2788  // FIXME: This error message could be improved, it would be nice
2789  // to say what the bounds actually are.
2790  S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2791  << E->getSourceRange();
2792  return;
2793  }
2794  }
2795 
2796  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2797  const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2798  if (isa<FunctionNoProtoType>(FT)) {
2799  S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2800  return;
2801  }
2802 
2803  if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2804  S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2805  return;
2806  }
2807  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2808  if (!MD->isVariadic()) {
2809  S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2810  return;
2811  }
2812  } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2813  if (!BD->isVariadic()) {
2814  S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2815  return;
2816  }
2817  } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2818  QualType Ty = V->getType();
2819  if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2820  const FunctionType *FT = Ty->isFunctionPointerType()
2821  ? D->getFunctionType()
2822  : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2823  if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2824  int m = Ty->isFunctionPointerType() ? 0 : 1;
2825  S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2826  return;
2827  }
2828  } else {
2829  S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2831  return;
2832  }
2833  } else {
2834  S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2836  return;
2837  }
2838  D->addAttr(::new (S.Context)
2839  SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2841 }
2842 
2843 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2844  if (D->getFunctionType() &&
2846  S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2847  << Attr.getName() << 0;
2848  return;
2849  }
2850  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2851  if (MD->getReturnType()->isVoidType()) {
2852  S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2853  << Attr.getName() << 1;
2854  return;
2855  }
2856 
2857  // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2858  // about using it as an extension.
2859  if (!S.getLangOpts().CPlusPlus17 && Attr.isCXX11Attribute() &&
2860  !Attr.getScopeName())
2861  S.Diag(Attr.getLoc(), diag::ext_cxx17_attr) << Attr.getName();
2862 
2863  D->addAttr(::new (S.Context)
2864  WarnUnusedResultAttr(Attr.getRange(), S.Context,
2866 }
2867 
2868 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2869  // weak_import only applies to variable & function declarations.
2870  bool isDef = false;
2871  if (!D->canBeWeakImported(isDef)) {
2872  if (isDef)
2873  S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2874  << "weak_import";
2875  else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2876  (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2877  (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2878  // Nothing to warn about here.
2879  } else
2880  S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2881  << Attr.getName() << ExpectedVariableOrFunction;
2882 
2883  return;
2884  }
2885 
2886  D->addAttr(::new (S.Context)
2887  WeakImportAttr(Attr.getRange(), S.Context,
2889 }
2890 
2891 // Handles reqd_work_group_size and work_group_size_hint.
2892 template <typename WorkGroupAttr>
2893 static void handleWorkGroupSize(Sema &S, Decl *D,
2894  const AttributeList &Attr) {
2895  uint32_t WGSize[3];
2896  for (unsigned i = 0; i < 3; ++i) {
2897  const Expr *E = Attr.getArgAsExpr(i);
2898  if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2899  return;
2900  if (WGSize[i] == 0) {
2901  S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2902  << Attr.getName() << E->getSourceRange();
2903  return;
2904  }
2905  }
2906 
2907  WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2908  if (Existing && !(Existing->getXDim() == WGSize[0] &&
2909  Existing->getYDim() == WGSize[1] &&
2910  Existing->getZDim() == WGSize[2]))
2911  S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2912 
2913  D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2914  WGSize[0], WGSize[1], WGSize[2],
2916 }
2917 
2918 // Handles intel_reqd_sub_group_size.
2919 static void handleSubGroupSize(Sema &S, Decl *D, const AttributeList &Attr) {
2920  uint32_t SGSize;
2921  const Expr *E = Attr.getArgAsExpr(0);
2922  if (!checkUInt32Argument(S, Attr, E, SGSize))
2923  return;
2924  if (SGSize == 0) {
2925  S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2926  << Attr.getName() << E->getSourceRange();
2927  return;
2928  }
2929 
2930  OpenCLIntelReqdSubGroupSizeAttr *Existing =
2931  D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2932  if (Existing && Existing->getSubGroupSize() != SGSize)
2933  S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2934 
2935  D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr(
2936  Attr.getRange(), S.Context, SGSize,
2938 }
2939 
2940 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2941  if (!Attr.hasParsedType()) {
2942  S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2943  << Attr.getName() << 1;
2944  return;
2945  }
2946 
2947  TypeSourceInfo *ParmTSI = nullptr;
2948  QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2949  assert(ParmTSI && "no type source info for attribute argument");
2950 
2951  if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2952  (ParmType->isBooleanType() ||
2953  !ParmType->isIntegralType(S.getASTContext()))) {
2954  S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2955  << ParmType;
2956  return;
2957  }
2958 
2959  if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2960  if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2961  S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2962  return;
2963  }
2964  }
2965 
2966  D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2967  ParmTSI,
2969 }
2970 
2971 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2972  StringRef Name,
2973  unsigned AttrSpellingListIndex) {
2974  if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2975  if (ExistingAttr->getName() == Name)
2976  return nullptr;
2977  Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2978  Diag(Range.getBegin(), diag::note_previous_attribute);
2979  return nullptr;
2980  }
2981  return ::new (Context) SectionAttr(Range, Context, Name,
2982  AttrSpellingListIndex);
2983 }
2984 
2985 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2986  std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2987  if (!Error.empty()) {
2988  Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2989  return false;
2990  }
2991  return true;
2992 }
2993 
2994 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2995  // Make sure that there is a string literal as the sections's single
2996  // argument.
2997  StringRef Str;
2998  SourceLocation LiteralLoc;
2999  if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
3000  return;
3001 
3002  if (!S.checkSectionName(LiteralLoc, Str))
3003  return;
3004 
3005  // If the target wants to validate the section specifier, make it happen.
3006  std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
3007  if (!Error.empty()) {
3008  S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3009  << Error;
3010  return;
3011  }
3012 
3013  unsigned Index = Attr.getAttributeSpellingListIndex();
3014  SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
3015  if (NewAttr)
3016  D->addAttr(NewAttr);
3017 }
3018 
3019 // Check for things we'd like to warn about. Multiversioning issues are
3020 // handled later in the process, once we know how many exist.
3021 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3022  enum FirstParam { Unsupported, Duplicate };
3023  enum SecondParam { None, Architecture };
3024  for (auto Str : {"tune=", "fpmath="})
3025  if (AttrStr.find(Str) != StringRef::npos)
3026  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3027  << Unsupported << None << Str;
3028 
3029  TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3030 
3031  if (!ParsedAttrs.Architecture.empty() &&
3032  !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3033  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3034  << Unsupported << Architecture << ParsedAttrs.Architecture;
3035 
3036  if (ParsedAttrs.DuplicateArchitecture)
3037  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3038  << Duplicate << None << "arch=";
3039 
3040  for (const auto &Feature : ParsedAttrs.Features) {
3041  auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3042  if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3043  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3044  << Unsupported << None << CurFeature;
3045  }
3046 
3047  return true;
3048 }
3049 
3050 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3051  StringRef Str;
3052  SourceLocation LiteralLoc;
3053  if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc) ||
3054  !S.checkTargetAttr(LiteralLoc, Str))
3055  return;
3056  unsigned Index = Attr.getAttributeSpellingListIndex();
3057  TargetAttr *NewAttr =
3058  ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
3059  D->addAttr(NewAttr);
3060 }
3061 
3062 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3063  Expr *E = Attr.getArgAsExpr(0);
3064  SourceLocation Loc = E->getExprLoc();
3065  FunctionDecl *FD = nullptr;
3067 
3068  // gcc only allows for simple identifiers. Since we support more than gcc, we
3069  // will warn the user.
3070  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3071  if (DRE->hasQualifier())
3072  S.Diag(Loc, diag::warn_cleanup_ext);
3073  FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3074  NI = DRE->getNameInfo();
3075  if (!FD) {
3076  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3077  << NI.getName();
3078  return;
3079  }
3080  } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3081  if (ULE->hasExplicitTemplateArgs())
3082  S.Diag(Loc, diag::warn_cleanup_ext);
3084  NI = ULE->getNameInfo();
3085  if (!FD) {
3086  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3087  << NI.getName();
3088  if (ULE->getType() == S.Context.OverloadTy)
3090  return;
3091  }
3092  } else {
3093  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3094  return;
3095  }
3096 
3097  if (FD->getNumParams() != 1) {
3098  S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3099  << NI.getName();
3100  return;
3101  }
3102 
3103  // We're currently more strict than GCC about what function types we accept.
3104  // If this ever proves to be a problem it should be easy to fix.
3105  QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3106  QualType ParamTy = FD->getParamDecl(0)->getType();
3108  ParamTy, Ty) != Sema::Compatible) {
3109  S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3110  << NI.getName() << ParamTy << Ty;
3111  return;
3112  }
3113 
3114  D->addAttr(::new (S.Context)
3115  CleanupAttr(Attr.getRange(), S.Context, FD,
3117 }
3118 
3120  const AttributeList &Attr) {
3121  if (!Attr.isArgIdent(0)) {
3122  S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3123  << Attr.getName() << 0 << AANT_ArgumentIdentifier;
3124  return;
3125  }
3126 
3127  EnumExtensibilityAttr::Kind ExtensibilityKind;
3128  IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3129  if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3130  ExtensibilityKind)) {
3131  S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3132  << Attr.getName() << II;
3133  return;
3134  }
3135 
3136  D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3137  Attr.getRange(), S.Context, ExtensibilityKind,
3139 }
3140 
3141 /// Handle __attribute__((format_arg((idx)))) attribute based on
3142 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3143 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3144  Expr *IdxExpr = Attr.getArgAsExpr(0);
3145  uint64_t Idx;
3146  if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
3147  return;
3148 
3149  // Make sure the format string is really a string.
3151 
3152  bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3153  if (NotNSStringTy &&
3154  !isCFStringType(Ty, S.Context) &&
3155  (!Ty->isPointerType() ||
3156  !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3157  S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3158  << "a string type" << IdxExpr->getSourceRange()
3160  return;
3161  }
3163  if (!isNSStringType(Ty, S.Context) &&
3164  !isCFStringType(Ty, S.Context) &&
3165  (!Ty->isPointerType() ||
3166  !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3167  S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
3168  << (NotNSStringTy ? "string type" : "NSString")
3169  << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3170  return;
3171  }
3172 
3173  // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
3174  // because that has corrected for the implicit this parameter, and is zero-
3175  // based. The attribute expects what the user wrote explicitly.
3176  llvm::APSInt Val;
3177  IdxExpr->EvaluateAsInt(Val, S.Context);
3178 
3179  D->addAttr(::new (S.Context)
3180  FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
3182 }
3183 
3191 };
3192 
3193 /// getFormatAttrKind - Map from format attribute names to supported format
3194 /// types.
3195 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3196  return llvm::StringSwitch<FormatAttrKind>(Format)
3197  // Check for formats that get handled specially.
3198  .Case("NSString", NSStringFormat)
3199  .Case("CFString", CFStringFormat)
3200  .Case("strftime", StrftimeFormat)
3201 
3202  // Otherwise, check for supported formats.
3203  .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3204  .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3205  .Case("kprintf", SupportedFormat) // OpenBSD.
3206  .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3207  .Case("os_trace", SupportedFormat)
3208  .Case("os_log", SupportedFormat)
3209 
3210  .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3211  .Default(InvalidFormat);
3212 }
3213 
3214 /// Handle __attribute__((init_priority(priority))) attributes based on
3215 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3216 static void handleInitPriorityAttr(Sema &S, Decl *D,
3217  const AttributeList &Attr) {
3218  if (!S.getLangOpts().CPlusPlus) {
3219  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3220  return;
3221  }
3222 
3223  if (S.getCurFunctionOrMethodDecl()) {
3224  S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3225  Attr.setInvalid();
3226  return;
3227  }
3228  QualType T = cast<VarDecl>(D)->getType();
3229  if (S.Context.getAsArrayType(T))
3230  T = S.Context.getBaseElementType(T);
3231  if (!T->getAs<RecordType>()) {
3232  S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3233  Attr.setInvalid();
3234  return;
3235  }
3236 
3237  Expr *E = Attr.getArgAsExpr(0);
3238  uint32_t prioritynum;
3239  if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
3240  Attr.setInvalid();
3241  return;
3242  }
3243 
3244  if (prioritynum < 101 || prioritynum > 65535) {
3245  S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
3246  << E->getSourceRange() << Attr.getName() << 101 << 65535;
3247  Attr.setInvalid();
3248  return;
3249  }
3250  D->addAttr(::new (S.Context)
3251  InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3253 }
3254 
3256  IdentifierInfo *Format, int FormatIdx,
3257  int FirstArg,
3258  unsigned AttrSpellingListIndex) {
3259  // Check whether we already have an equivalent format attribute.
3260  for (auto *F : D->specific_attrs<FormatAttr>()) {
3261  if (F->getType() == Format &&
3262  F->getFormatIdx() == FormatIdx &&
3263  F->getFirstArg() == FirstArg) {
3264  // If we don't have a valid location for this attribute, adopt the
3265  // location.
3266  if (F->getLocation().isInvalid())
3267  F->setRange(Range);
3268  return nullptr;
3269  }
3270  }
3271 
3272  return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3273  FirstArg, AttrSpellingListIndex);
3274 }
3275 
3276 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3277 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3278 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3279  if (!Attr.isArgIdent(0)) {
3280  S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3281  << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3282  return;
3283  }
3284 
3285  // In C++ the implicit 'this' function parameter also counts, and they are
3286  // counted from one.
3287  bool HasImplicitThisParam = isInstanceMethod(D);
3288  unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3289 
3290  IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3291  StringRef Format = II->getName();
3292 
3293  if (normalizeName(Format)) {
3294  // If we've modified the string name, we need a new identifier for it.
3295  II = &S.Context.Idents.get(Format);
3296  }
3297 
3298  // Check for supported formats.
3300 
3301  if (Kind == IgnoredFormat)
3302  return;
3303 
3304  if (Kind == InvalidFormat) {
3305  S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3306  << Attr.getName() << II->getName();
3307  return;
3308  }
3309 
3310  // checks for the 2nd argument
3311  Expr *IdxExpr = Attr.getArgAsExpr(1);
3312  uint32_t Idx;
3313  if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
3314  return;
3315 
3316  if (Idx < 1 || Idx > NumArgs) {
3317  S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3318  << Attr.getName() << 2 << IdxExpr->getSourceRange();
3319  return;
3320  }
3321 
3322  // FIXME: Do we need to bounds check?
3323  unsigned ArgIdx = Idx - 1;
3324 
3325  if (HasImplicitThisParam) {
3326  if (ArgIdx == 0) {
3327  S.Diag(Attr.getLoc(),
3328  diag::err_format_attribute_implicit_this_format_string)
3329  << IdxExpr->getSourceRange();
3330  return;
3331  }
3332  ArgIdx--;
3333  }
3334 
3335  // make sure the format string is really a string
3336  QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3337 
3338  if (Kind == CFStringFormat) {
3339  if (!isCFStringType(Ty, S.Context)) {
3340  S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3341  << "a CFString" << IdxExpr->getSourceRange()
3342  << getFunctionOrMethodParamRange(D, ArgIdx);
3343  return;
3344  }
3345  } else if (Kind == NSStringFormat) {
3346  // FIXME: do we need to check if the type is NSString*? What are the
3347  // semantics?
3348  if (!isNSStringType(Ty, S.Context)) {
3349  S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3350  << "an NSString" << IdxExpr->getSourceRange()
3351  << getFunctionOrMethodParamRange(D, ArgIdx);
3352  return;
3353  }
3354  } else if (!Ty->isPointerType() ||
3355  !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3356  S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3357  << "a string type" << IdxExpr->getSourceRange()
3358  << getFunctionOrMethodParamRange(D, ArgIdx);
3359  return;
3360  }
3361 
3362  // check the 3rd argument
3363  Expr *FirstArgExpr = Attr.getArgAsExpr(2);
3364  uint32_t FirstArg;
3365  if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
3366  return;
3367 
3368  // check if the function is variadic if the 3rd argument non-zero
3369  if (FirstArg != 0) {
3370  if (isFunctionOrMethodVariadic(D)) {
3371  ++NumArgs; // +1 for ...
3372  } else {
3373  S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3374  return;
3375  }
3376  }
3377 
3378  // strftime requires FirstArg to be 0 because it doesn't read from any
3379  // variable the input is just the current time + the format string.
3380  if (Kind == StrftimeFormat) {
3381  if (FirstArg != 0) {
3382  S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3383  << FirstArgExpr->getSourceRange();
3384  return;
3385  }
3386  // if 0 it disables parameter checking (to use with e.g. va_list)
3387  } else if (FirstArg != 0 && FirstArg != NumArgs) {
3388  S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3389  << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
3390  return;
3391  }
3392 
3393  FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
3394  Idx, FirstArg,
3396  if (NewAttr)
3397  D->addAttr(NewAttr);
3398 }
3399 
3401  const AttributeList &Attr) {
3402  // Try to find the underlying union declaration.
3403  RecordDecl *RD = nullptr;
3404  TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3405  if (TD && TD->getUnderlyingType()->isUnionType())
3406  RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3407  else
3408  RD = dyn_cast<RecordDecl>(D);
3409 
3410  if (!RD || !RD->isUnion()) {
3411  S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3412  << Attr.getName() << ExpectedUnion;
3413  return;
3414  }
3415 
3416  if (!RD->isCompleteDefinition()) {
3417  if (!RD->isBeingDefined())
3418  S.Diag(Attr.getLoc(),
3419  diag::warn_transparent_union_attribute_not_definition);
3420  return;
3421  }
3422 
3424  FieldEnd = RD->field_end();
3425  if (Field == FieldEnd) {
3426  S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3427  return;
3428  }
3429 
3430  FieldDecl *FirstField = *Field;
3431  QualType FirstType = FirstField->getType();
3432  if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3433  S.Diag(FirstField->getLocation(),
3434  diag::warn_transparent_union_attribute_floating)
3435  << FirstType->isVectorType() << FirstType;
3436  return;
3437  }
3438 
3439  if (FirstType->isIncompleteType())
3440  return;
3441  uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3442  uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3443  for (; Field != FieldEnd; ++Field) {
3444  QualType FieldType = Field->getType();
3445  if (FieldType->isIncompleteType())
3446  return;
3447  // FIXME: this isn't fully correct; we also need to test whether the
3448  // members of the union would all have the same calling convention as the
3449  // first member of the union. Checking just the size and alignment isn't
3450  // sufficient (consider structs passed on the stack instead of in registers
3451  // as an example).
3452  if (S.Context.getTypeSize(FieldType) != FirstSize ||
3453  S.Context.getTypeAlign(FieldType) > FirstAlign) {
3454  // Warn if we drop the attribute.
3455  bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3456  unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3457  : S.Context.getTypeAlign(FieldType);
3458  S.Diag(Field->getLocation(),
3459  diag::warn_transparent_union_attribute_field_size_align)
3460  << isSize << Field->getDeclName() << FieldBits;
3461  unsigned FirstBits = isSize? FirstSize : FirstAlign;
3462  S.Diag(FirstField->getLocation(),
3463  diag::note_transparent_union_first_field_size_align)
3464  << isSize << FirstBits;
3465  return;
3466  }
3467  }
3468 
3469  RD->addAttr(::new (S.Context)
3470  TransparentUnionAttr(Attr.getRange(), S.Context,
3472 }
3473 
3474 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3475  // Make sure that there is a string literal as the annotation's single
3476  // argument.
3477  StringRef Str;
3478  if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
3479  return;
3480 
3481  // Don't duplicate annotations that are already set.
3482  for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3483  if (I->getAnnotation() == Str)
3484  return;
3485  }
3486 
3487  D->addAttr(::new (S.Context)
3488  AnnotateAttr(Attr.getRange(), S.Context, Str,
3490 }
3491 
3492 static void handleAlignValueAttr(Sema &S, Decl *D,
3493  const AttributeList &Attr) {
3494  S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3496 }
3497 
3499  unsigned SpellingListIndex) {
3500  AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3501  SourceLocation AttrLoc = AttrRange.getBegin();
3502 
3503  QualType T;
3504  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3505  T = TD->getUnderlyingType();
3506  else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3507  T = VD->getType();
3508  else
3509  llvm_unreachable("Unknown decl type for align_value");
3510 
3511  if (!T->isDependentType() && !T->isAnyPointerType() &&
3512  !T->isReferenceType() && !T->isMemberPointerType()) {
3513  Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3514  << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3515  return;
3516  }
3517 
3518  if (!E->isValueDependent()) {
3519  llvm::APSInt Alignment;
3520  ExprResult ICE
3521  = VerifyIntegerConstantExpression(E, &Alignment,
3522  diag::err_align_value_attribute_argument_not_int,
3523  /*AllowFold*/ false);
3524  if (ICE.isInvalid())
3525  return;
3526 
3527  if (!Alignment.isPowerOf2()) {
3528  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3529  << E->getSourceRange();
3530  return;
3531  }
3532 
3533  D->addAttr(::new (Context)
3534  AlignValueAttr(AttrRange, Context, ICE.get(),
3535  SpellingListIndex));
3536  return;
3537  }
3538 
3539  // Save dependent expressions in the AST to be instantiated.
3540  D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3541 }
3542 
3543 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3544  // check the attribute arguments.
3545  if (Attr.getNumArgs() > 1) {
3546  S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3547  << Attr.getName() << 1;
3548  return;
3549  }
3550 
3551  if (Attr.getNumArgs() == 0) {
3552  D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3553  true, nullptr, Attr.getAttributeSpellingListIndex()));
3554  return;
3555  }
3556 
3557  Expr *E = Attr.getArgAsExpr(0);
3558  if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3559  S.Diag(Attr.getEllipsisLoc(),
3560  diag::err_pack_expansion_without_parameter_packs);
3561  return;
3562  }
3563 
3565  return;
3566 
3567  if (E->isValueDependent()) {
3568  if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3569  if (!TND->getUnderlyingType()->isDependentType()) {
3570  S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3571  << E->getSourceRange();
3572  return;
3573  }
3574  }
3575  }
3576 
3577  S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3578  Attr.isPackExpansion());
3579 }
3580 
3582  unsigned SpellingListIndex, bool IsPackExpansion) {
3583  AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3584  SourceLocation AttrLoc = AttrRange.getBegin();
3585 
3586  // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3587  if (TmpAttr.isAlignas()) {
3588  // C++11 [dcl.align]p1:
3589  // An alignment-specifier may be applied to a variable or to a class
3590  // data member, but it shall not be applied to a bit-field, a function
3591  // parameter, the formal parameter of a catch clause, or a variable
3592  // declared with the register storage class specifier. An
3593  // alignment-specifier may also be applied to the declaration of a class
3594  // or enumeration type.
3595  // C11 6.7.5/2:
3596  // An alignment attribute shall not be specified in a declaration of
3597  // a typedef, or a bit-field, or a function, or a parameter, or an
3598  // object declared with the register storage-class specifier.
3599  int DiagKind = -1;
3600  if (isa<ParmVarDecl>(D)) {
3601  DiagKind = 0;
3602  } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3603  if (VD->getStorageClass() == SC_Register)
3604  DiagKind = 1;
3605  if (VD->isExceptionVariable())
3606  DiagKind = 2;
3607  } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3608  if (FD->isBitField())
3609  DiagKind = 3;
3610  } else if (!isa<TagDecl>(D)) {
3611  Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3612  << (TmpAttr.isC11() ? ExpectedVariableOrField
3614  return;
3615  }
3616  if (DiagKind != -1) {
3617  Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3618  << &TmpAttr << DiagKind;
3619  return;
3620  }
3621  }
3622 
3623  if (E->isTypeDependent() || E->isValueDependent()) {
3624  // Save dependent expressions in the AST to be instantiated.
3625  AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3626  AA->setPackExpansion(IsPackExpansion);
3627  D->addAttr(AA);
3628  return;
3629  }
3630 
3631  // FIXME: Cache the number on the Attr object?
3632  llvm::APSInt Alignment;
3633  ExprResult ICE
3634  = VerifyIntegerConstantExpression(E, &Alignment,
3635  diag::err_aligned_attribute_argument_not_int,
3636  /*AllowFold*/ false);
3637  if (ICE.isInvalid())
3638  return;
3639 
3640  uint64_t AlignVal = Alignment.getZExtValue();
3641 
3642  // C++11 [dcl.align]p2:
3643  // -- if the constant expression evaluates to zero, the alignment
3644  // specifier shall have no effect
3645  // C11 6.7.5p6:
3646  // An alignment specification of zero has no effect.
3647  if (!(TmpAttr.isAlignas() && !Alignment)) {
3648  if (!llvm::isPowerOf2_64(AlignVal)) {
3649  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3650  << E->getSourceRange();
3651  return;
3652  }
3653  }
3654 
3655  // Alignment calculations can wrap around if it's greater than 2**28.
3656  unsigned MaxValidAlignment =
3657  Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3658  : 268435456;
3659  if (AlignVal > MaxValidAlignment) {
3660  Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3661  << E->getSourceRange();
3662  return;
3663  }
3664 
3665  if (Context.getTargetInfo().isTLSSupported()) {
3666  unsigned MaxTLSAlign =
3667  Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3668  .getQuantity();
3669  auto *VD = dyn_cast<VarDecl>(D);
3670  if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3671  VD->getTLSKind() != VarDecl::TLS_None) {
3672  Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3673  << (unsigned)AlignVal << VD << MaxTLSAlign;
3674  return;
3675  }
3676  }
3677 
3678  AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3679  ICE.get(), SpellingListIndex);
3680  AA->setPackExpansion(IsPackExpansion);
3681  D->addAttr(AA);
3682 }
3683 
3685  unsigned SpellingListIndex, bool IsPackExpansion) {
3686  // FIXME: Cache the number on the Attr object if non-dependent?
3687  // FIXME: Perform checking of type validity
3688  AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3689  SpellingListIndex);
3690  AA->setPackExpansion(IsPackExpansion);
3691  D->addAttr(AA);
3692 }
3693 
3695  assert(D->hasAttrs() && "no attributes on decl");
3696 
3697  QualType UnderlyingTy, DiagTy;
3698  if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3699  UnderlyingTy = DiagTy = VD->getType();
3700  } else {
3701  UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3702  if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3703  UnderlyingTy = ED->getIntegerType();
3704  }
3705  if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3706  return;
3707 
3708  // C++11 [dcl.align]p5, C11 6.7.5/4:
3709  // The combined effect of all alignment attributes in a declaration shall
3710  // not specify an alignment that is less strict than the alignment that
3711  // would otherwise be required for the entity being declared.
3712  AlignedAttr *AlignasAttr = nullptr;
3713  unsigned Align = 0;
3714  for (auto *I : D->specific_attrs<AlignedAttr>()) {
3715  if (I->isAlignmentDependent())
3716  return;
3717  if (I->isAlignas())
3718  AlignasAttr = I;
3719  Align = std::max(Align, I->getAlignment(Context));
3720  }
3721 
3722  if (AlignasAttr && Align) {
3723  CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3724  CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3725  if (NaturalAlign > RequestedAlign)
3726  Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3727  << DiagTy << (unsigned)NaturalAlign.getQuantity();
3728  }
3729 }
3730 
3732  CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3733  MSInheritanceAttr::Spelling SemanticSpelling) {
3734  assert(RD->hasDefinition() && "RD has no definition!");
3735 
3736  // We may not have seen base specifiers or any virtual methods yet. We will
3737  // have to wait until the record is defined to catch any mismatches.
3738  if (!RD->getDefinition()->isCompleteDefinition())
3739  return false;
3740 
3741  // The unspecified model never matches what a definition could need.
3742  if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3743  return false;
3744 
3745  if (BestCase) {
3746  if (RD->calculateInheritanceModel() == SemanticSpelling)
3747  return false;
3748  } else {
3749  if (RD->calculateInheritanceModel() <= SemanticSpelling)
3750  return false;
3751  }
3752 
3753  Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3754  << 0 /*definition*/;
3755  Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3756  << RD->getNameAsString();
3757  return true;
3758 }
3759 
3760 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3761 /// attribute.
3762 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3763  bool &IntegerMode, bool &ComplexMode) {
3764  IntegerMode = true;
3765  ComplexMode = false;
3766  switch (Str.size()) {
3767  case 2:
3768  switch (Str[0]) {
3769  case 'Q':
3770  DestWidth = 8;
3771  break;
3772  case 'H':
3773  DestWidth = 16;
3774  break;
3775  case 'S':
3776  DestWidth = 32;
3777  break;
3778  case 'D':
3779  DestWidth = 64;
3780  break;
3781  case 'X':
3782  DestWidth = 96;
3783  break;
3784  case 'T':
3785  DestWidth = 128;
3786  break;
3787  }
3788  if (Str[1] == 'F') {
3789  IntegerMode = false;
3790  } else if (Str[1] == 'C') {
3791  IntegerMode = false;
3792  ComplexMode = true;
3793  } else if (Str[1] != 'I') {
3794  DestWidth = 0;
3795  }
3796  break;
3797  case 4:
3798  // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3799  // pointer on PIC16 and other embedded platforms.
3800  if (Str == "word")
3801  DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3802  else if (Str == "byte")
3803  DestWidth = S.Context.getTargetInfo().getCharWidth();
3804  break;
3805  case 7:
3806  if (Str == "pointer")
3807  DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3808  break;
3809  case 11:
3810  if (Str == "unwind_word")
3811  DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3812  break;
3813  }
3814 }
3815 
3816 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3817 /// type.
3818 ///
3819 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3820 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3821 /// HImode, not an intermediate pointer.
3822 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3823  // This attribute isn't documented, but glibc uses it. It changes
3824  // the width of an int or unsigned int to the specified size.
3825  if (!Attr.isArgIdent(0)) {
3826  S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3828  return;
3829  }
3830 
3831  IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3832 
3833  S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3834 }
3835 
3837  unsigned SpellingListIndex, bool InInstantiation) {
3838  StringRef Str = Name->getName();
3839  normalizeName(Str);
3840  SourceLocation AttrLoc = AttrRange.getBegin();
3841 
3842  unsigned DestWidth = 0;
3843  bool IntegerMode = true;
3844  bool ComplexMode = false;
3845  llvm::APInt VectorSize(64, 0);
3846  if (Str.size() >= 4 && Str[0] == 'V') {
3847  // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3848  size_t StrSize = Str.size();
3849  size_t VectorStringLength = 0;
3850  while ((VectorStringLength + 1) < StrSize &&
3851  isdigit(Str[VectorStringLength + 1]))
3852  ++VectorStringLength;
3853  if (VectorStringLength &&
3854  !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3855  VectorSize.isPowerOf2()) {
3856  parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3857  IntegerMode, ComplexMode);
3858  // Avoid duplicate warning from template instantiation.
3859  if (!InInstantiation)
3860  Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3861  } else {
3862  VectorSize = 0;
3863  }
3864  }
3865 
3866  if (!VectorSize)
3867  parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3868 
3869  // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3870  // and friends, at least with glibc.
3871  // FIXME: Make sure floating-point mappings are accurate
3872  // FIXME: Support XF and TF types
3873  if (!DestWidth) {
3874  Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3875  return;
3876  }
3877 
3878  QualType OldTy;
3879  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3880  OldTy = TD->getUnderlyingType();
3881  else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3882  // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3883  // Try to get type from enum declaration, default to int.
3884  OldTy = ED->getIntegerType();
3885  if (OldTy.isNull())
3886  OldTy = Context.IntTy;
3887  } else
3888  OldTy = cast<ValueDecl>(D)->getType();
3889 
3890  if (OldTy->isDependentType()) {
3891  D->addAttr(::new (Context)
3892  ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3893  return;
3894  }
3895 
3896  // Base type can also be a vector type (see PR17453).
3897  // Distinguish between base type and base element type.
3898  QualType OldElemTy = OldTy;
3899  if (const VectorType *VT = OldTy->getAs<VectorType>())
3900  OldElemTy = VT->getElementType();
3901 
3902  // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3903  // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3904  // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3905  if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3906  VectorSize.getBoolValue()) {
3907  Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3908  return;
3909  }
3910  bool IntegralOrAnyEnumType =
3911  OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3912 
3913  if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3914  !IntegralOrAnyEnumType)
3915  Diag(AttrLoc, diag::err_mode_not_primitive);
3916  else if (IntegerMode) {
3917  if (!IntegralOrAnyEnumType)
3918  Diag(AttrLoc, diag::err_mode_wrong_type);
3919  } else if (ComplexMode) {
3920  if (!OldElemTy->isComplexType())
3921  Diag(AttrLoc, diag::err_mode_wrong_type);
3922  } else {
3923  if (!OldElemTy->isFloatingType())
3924  Diag(AttrLoc, diag::err_mode_wrong_type);
3925  }
3926 
3927  QualType NewElemTy;
3928 
3929  if (IntegerMode)
3930  NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3931  OldElemTy->isSignedIntegerType());
3932  else
3933  NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
3934 
3935  if (NewElemTy.isNull()) {
3936  Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3937  return;
3938  }
3939 
3940  if (ComplexMode) {
3941  NewElemTy = Context.getComplexType(NewElemTy);
3942  }
3943 
3944  QualType NewTy = NewElemTy;
3945  if (VectorSize.getBoolValue()) {
3946  NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3948  } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
3949  // Complex machine mode does not support base vector types.
3950  if (ComplexMode) {
3951  Diag(AttrLoc, diag::err_complex_mode_vector_type);
3952  return;
3953  }
3954  unsigned NumElements = Context.getTypeSize(OldElemTy) *
3955  OldVT->getNumElements() /
3956  Context.getTypeSize(NewElemTy);
3957  NewTy =
3958  Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3959  }
3960 
3961  if (NewTy.isNull()) {
3962  Diag(AttrLoc, diag::err_mode_wrong_type);
3963  return;
3964  }
3965 
3966  // Install the new type.
3967  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3968  TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3969  else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3970  ED->setIntegerType(NewTy);
3971  else
3972  cast<ValueDecl>(D)->setType(NewTy);
3973 
3974  D->addAttr(::new (Context)
3975  ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3976 }
3977 
3978 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3979  D->addAttr(::new (S.Context)
3980  NoDebugAttr(Attr.getRange(), S.Context,
3982 }
3983 
3984 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3985  IdentifierInfo *Ident,
3986  unsigned AttrSpellingListIndex) {
3987  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3988  Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3989  Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3990  return nullptr;
3991  }
3992 
3993  if (D->hasAttr<AlwaysInlineAttr>())
3994  return nullptr;
3995 
3996  return ::new (Context) AlwaysInlineAttr(Range, Context,
3997  AttrSpellingListIndex);
3998 }
3999 
4001  IdentifierInfo *Ident,
4002  unsigned AttrSpellingListIndex) {
4003  if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
4004  return nullptr;
4005 
4006  return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
4007 }
4008 
4009 InternalLinkageAttr *
4011  IdentifierInfo *Ident,
4012  unsigned AttrSpellingListIndex) {
4013  if (auto VD = dyn_cast<VarDecl>(D)) {
4014  // Attribute applies to Var but not any subclass of it (like ParmVar,
4015  // ImplicitParm or VarTemplateSpecialization).
4016  if (VD->getKind() != Decl::Var) {
4017  Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
4018  << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4020  return nullptr;
4021  }
4022  // Attribute does not apply to non-static local variables.
4023  if (VD->hasLocalStorage()) {
4024  Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4025  return nullptr;
4026  }
4027  }
4028 
4029  if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
4030  return nullptr;
4031 
4032  return ::new (Context)
4033  InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
4034 }
4035 
4036 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
4037  unsigned AttrSpellingListIndex) {
4038  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4039  Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
4040  Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4041  return nullptr;
4042  }
4043 
4044  if (D->hasAttr<MinSizeAttr>())
4045  return nullptr;
4046 
4047  return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
4048 }
4049 
4050 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
4051  unsigned AttrSpellingListIndex) {
4052  if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4053  Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4054  Diag(Range.getBegin(), diag::note_conflicting_attribute);
4055  D->dropAttr<AlwaysInlineAttr>();
4056  }
4057  if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4058  Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4059  Diag(Range.getBegin(), diag::note_conflicting_attribute);
4060  D->dropAttr<MinSizeAttr>();
4061  }
4062 
4063  if (D->hasAttr<OptimizeNoneAttr>())
4064  return nullptr;
4065 
4066  return ::new (Context) OptimizeNoneAttr(Range, Context,
4067  AttrSpellingListIndex);
4068 }
4069 
4070 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
4071  const AttributeList &Attr) {
4072  if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
4073  Attr.getName()))
4074  return;
4075 
4076  if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
4077  D, Attr.getRange(), Attr.getName(),
4079  D->addAttr(Inline);
4080 }
4081 
4082 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4083  if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4084  D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4085  D->addAttr(MinSize);
4086 }
4087 
4088 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
4089  const AttributeList &Attr) {
4090  if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4091  D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4092  D->addAttr(Optnone);
4093 }
4094 
4095 static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4096  if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(),
4097  Attr.getName()))
4098  return;
4099  auto *VD = cast<VarDecl>(D);
4100  if (!VD->hasGlobalStorage()) {
4101  S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant);
4102  return;
4103  }
4104  D->addAttr(::new (S.Context) CUDAConstantAttr(
4105  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4106 }
4107 
4108 static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4109  if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
4110  Attr.getName()))
4111  return;
4112  auto *VD = cast<VarDecl>(D);
4113  // extern __shared__ is only allowed on arrays with no length (e.g.
4114  // "int x[]").
4115  if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) {
4116  S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
4117  return;
4118  }
4119  if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4120  S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared)
4121  << S.CurrentCUDATarget())
4122  return;
4123  D->addAttr(::new (S.Context) CUDASharedAttr(
4124  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4125 }
4126 
4127 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4128  if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
4129  Attr.getName()) ||
4130  checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
4131  Attr.getName())) {
4132  return;
4133  }
4134  FunctionDecl *FD = cast<FunctionDecl>(D);
4135  if (!FD->getReturnType()->isVoidType()) {
4136  SourceRange RTRange = FD->getReturnTypeSourceRange();
4137  S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4138  << FD->getType()
4139  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4140  : FixItHint());
4141  return;
4142  }
4143  if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4144  if (Method->isInstance()) {
4145  S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
4146  << Method;
4147  return;
4148  }
4149  S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
4150  }
4151  // Only warn for "inline" when compiling for host, to cut down on noise.
4152  if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4153  S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
4154 
4155  D->addAttr(::new (S.Context)
4156  CUDAGlobalAttr(Attr.getRange(), S.Context,
4158 }
4159 
4160 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4161  FunctionDecl *Fn = cast<FunctionDecl>(D);
4162  if (!Fn->isInlineSpecified()) {
4163  S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4164  return;
4165  }
4166 
4167  D->addAttr(::new (S.Context)
4168  GNUInlineAttr(Attr.getRange(), S.Context,
4170 }
4171 
4172 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4173  if (hasDeclarator(D)) return;
4174 
4175  // Diagnostic is emitted elsewhere: here we store the (valid) Attr
4176  // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4177  CallingConv CC;
4178  if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
4179  return;
4180 
4181  if (!isa<ObjCMethodDecl>(D)) {
4182  S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4183  << Attr.getName() << ExpectedFunctionOrMethod;
4184  return;
4185  }
4186 
4187  switch (Attr.getKind()) {
4188  case AttributeList::AT_FastCall:
4189  D->addAttr(::new (S.Context)
4190  FastCallAttr(Attr.getRange(), S.Context,
4192  return;
4193  case AttributeList::AT_StdCall:
4194  D->addAttr(::new (S.Context)
4195  StdCallAttr(Attr.getRange(), S.Context,
4197  return;
4198  case AttributeList::AT_ThisCall:
4199  D->addAttr(::new (S.Context)
4200  ThisCallAttr(Attr.getRange(), S.Context,
4202  return;
4203  case AttributeList::AT_CDecl:
4204  D->addAttr(::new (S.Context)
4205  CDeclAttr(Attr.getRange(), S.Context,
4207  return;
4208  case AttributeList::AT_Pascal:
4209  D->addAttr(::new (S.Context)
4210  PascalAttr(Attr.getRange(), S.Context,
4212  return;
4213  case AttributeList::AT_SwiftCall:
4214  D->addAttr(::new (S.Context)
4215  SwiftCallAttr(Attr.getRange(), S.Context,
4217  return;
4218  case AttributeList::AT_VectorCall:
4219  D->addAttr(::new (S.Context)
4220  VectorCallAttr(Attr.getRange(), S.Context,
4222  return;
4223  case AttributeList::AT_MSABI:
4224  D->addAttr(::new (S.Context)
4225  MSABIAttr(Attr.getRange(), S.Context,
4227  return;
4228  case AttributeList::AT_SysVABI:
4229  D->addAttr(::new (S.Context)
4230  SysVABIAttr(Attr.getRange(), S.Context,
4232  return;
4233  case AttributeList::AT_RegCall:
4234  D->addAttr(::new (S.Context) RegCallAttr(
4235  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4236  return;
4237  case AttributeList::AT_Pcs: {
4238  PcsAttr::PCSType PCS;
4239  switch (CC) {
4240  case CC_AAPCS:
4241  PCS = PcsAttr::AAPCS;
4242  break;
4243  case CC_AAPCS_VFP:
4244  PCS = PcsAttr::AAPCS_VFP;
4245  break;
4246  default:
4247  llvm_unreachable("unexpected calling convention in pcs attribute");
4248  }
4249 
4250  D->addAttr(::new (S.Context)
4251  PcsAttr(Attr.getRange(), S.Context, PCS,
4253  return;
4254  }
4255  case AttributeList::AT_IntelOclBicc:
4256  D->addAttr(::new (S.Context)
4257  IntelOclBiccAttr(Attr.getRange(), S.Context,
4259  return;
4260  case AttributeList::AT_PreserveMost:
4261  D->addAttr(::new (S.Context) PreserveMostAttr(
4262  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4263  return;
4264  case AttributeList::AT_PreserveAll:
4265  D->addAttr(::new (S.Context) PreserveAllAttr(
4266  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4267  return;
4268  default:
4269  llvm_unreachable("unexpected attribute kind");
4270  }
4271 }
4272 
4273 static void handleSuppressAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4274  if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4275  return;
4276 
4277  std::vector<StringRef> DiagnosticIdentifiers;
4278  for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4279  StringRef RuleName;
4280 
4281  if (!S.checkStringLiteralArgumentAttr(Attr, I, RuleName, nullptr))
4282  return;
4283 
4284  // FIXME: Warn if the rule name is unknown. This is tricky because only
4285  // clang-tidy knows about available rules.
4286  DiagnosticIdentifiers.push_back(RuleName);
4287  }
4288  D->addAttr(::new (S.Context) SuppressAttr(
4289  Attr.getRange(), S.Context, DiagnosticIdentifiers.data(),
4290  DiagnosticIdentifiers.size(), Attr.getAttributeSpellingListIndex()));
4291 }
4292 
4294  const FunctionDecl *FD) {
4295  if (Attrs.isInvalid())
4296  return true;
4297 
4298  if (Attrs.hasProcessingCache()) {
4299  CC = (CallingConv) Attrs.getProcessingCache();
4300  return false;
4301  }
4302 
4303  unsigned ReqArgs = Attrs.getKind() == AttributeList::AT_Pcs ? 1 : 0;
4304  if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4305  Attrs.setInvalid();
4306  return true;
4307  }
4308 
4309  // TODO: diagnose uses of these conventions on the wrong target.
4310  switch (Attrs.getKind()) {
4311  case AttributeList::AT_CDecl: CC = CC_C; break;
4312  case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
4313  case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
4314  case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
4315  case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
4316  case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
4317  case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
4318  case AttributeList::AT_RegCall: CC = CC_X86RegCall; break;
4319  case AttributeList::AT_MSABI:
4320  CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4321  CC_Win64;
4322  break;
4323  case AttributeList::AT_SysVABI:
4324  CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4325  CC_C;
4326  break;
4327  case AttributeList::AT_Pcs: {
4328  StringRef StrRef;
4329  if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4330  Attrs.setInvalid();
4331  return true;
4332  }
4333  if (StrRef == "aapcs") {
4334  CC = CC_AAPCS;
4335  break;
4336  } else if (StrRef == "aapcs-vfp") {
4337  CC = CC_AAPCS_VFP;
4338  break;
4339  }
4340 
4341  Attrs.setInvalid();
4342  Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4343  return true;
4344  }
4345  case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
4346  case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
4347  case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
4348  default: llvm_unreachable("unexpected attribute kind");
4349  }
4350 
4351  const TargetInfo &TI = Context.getTargetInfo();
4353  if (A != TargetInfo::CCCR_OK) {
4354  if (A == TargetInfo::CCCR_Warning)
4355  Diag(Attrs.getLoc(), diag::warn_cconv_ignored) << Attrs.getName();
4356 
4357  // This convention is not valid for the target. Use the default function or
4358  // method calling convention.
4359  bool IsCXXMethod = false, IsVariadic = false;
4360  if (FD) {
4361  IsCXXMethod = FD->isCXXInstanceMember();
4362  IsVariadic = FD->isVariadic();
4363  }
4364  CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4365  }
4366 
4367  Attrs.setProcessingCache((unsigned) CC);
4368  return false;
4369 }
4370 
4371 /// Pointer-like types in the default address space.
4373  if (!type->hasPointerRepresentation())
4374  return type->isDependentType();
4375  return type->getPointeeType().getAddressSpace() == LangAS::Default;
4376 }
4377 
4378 /// Pointers and references in the default address space.
4380  if (auto ptrType = type->getAs<PointerType>()) {
4381  type = ptrType->getPointeeType();
4382  } else if (auto refType = type->getAs<ReferenceType>()) {
4383  type = refType->getPointeeType();
4384  } else {
4385  return type->isDependentType();
4386  }
4387  return type.getAddressSpace() == LangAS::Default;
4388 }
4389 
4390 /// Pointers and references to pointers in the default address space.
4392  if (auto ptrType = type->getAs<PointerType>()) {
4393  type = ptrType->getPointeeType();
4394  } else if (auto refType = type->getAs<ReferenceType>()) {
4395  type = refType->getPointeeType();
4396  } else {
4397  return type->isDependentType();
4398  }
4399  if (!type.getQualifiers().empty())
4400  return false;
4401  return isValidSwiftContextType(type);
4402 }
4403 
4404 static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &Attrs,
4405  ParameterABI Abi) {
4406  S.AddParameterABIAttr(Attrs.getRange(), D, Abi,
4408 }
4409 
4411  unsigned spellingIndex) {
4412 
4413  QualType type = cast<ParmVarDecl>(D)->getType();
4414 
4415  if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4416  if (existingAttr->getABI() != abi) {
4417  Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4418  << getParameterABISpelling(abi) << existingAttr;
4419  Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4420  return;
4421  }
4422  }
4423 
4424  switch (abi) {
4426  llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4427 
4429  if (!isValidSwiftContextType(type)) {
4430  Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4431  << getParameterABISpelling(abi)
4432  << /*pointer to pointer */ 0 << type;
4433  }
4434  D->addAttr(::new (Context)
4435  SwiftContextAttr(range, Context, spellingIndex));
4436  return;
4437 
4439  if (!isValidSwiftErrorResultType(type)) {
4440  Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4441  << getParameterABISpelling(abi)
4442  << /*pointer to pointer */ 1 << type;
4443  }
4444  D->addAttr(::new (Context)
4445  SwiftErrorResultAttr(range, Context, spellingIndex));
4446  return;
4447 
4449  if (!isValidSwiftIndirectResultType(type)) {
4450  Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4451  << getParameterABISpelling(abi)
4452  << /*pointer*/ 0 << type;
4453  }
4454  D->addAttr(::new (Context)
4455  SwiftIndirectResultAttr(range, Context, spellingIndex));
4456  return;
4457  }
4458  llvm_unreachable("bad parameter ABI attribute");
4459 }
4460 
4461 /// Checks a regparm attribute, returning true if it is ill-formed and
4462 /// otherwise setting numParams to the appropriate value.
4463 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4464  if (Attr.isInvalid())
4465  return true;
4466 
4467  if (!checkAttributeNumArgs(*this, Attr, 1)) {
4468  Attr.setInvalid();
4469  return true;
4470  }
4471 
4472  uint32_t NP;
4473  Expr *NumParamsExpr = Attr.getArgAsExpr(0);
4474  if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
4475  Attr.setInvalid();
4476  return true;
4477  }
4478 
4479  if (Context.getTargetInfo().getRegParmMax() == 0) {
4480  Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
4481  << NumParamsExpr->getSourceRange();
4482  Attr.setInvalid();
4483  return true;
4484  }
4485 
4486  numParams = NP;
4487  if (numParams > Context.getTargetInfo().getRegParmMax()) {
4488  Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
4489  << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4490  Attr.setInvalid();
4491  return true;
4492  }
4493 
4494  return false;
4495 }
4496 
4497 // Checks whether an argument of launch_bounds attribute is
4498 // acceptable, performs implicit conversion to Rvalue, and returns
4499 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4500 // and may output an error.
4502  const CUDALaunchBoundsAttr &Attr,
4503  const unsigned Idx) {
4505  return nullptr;
4506 
4507  // Accept template arguments for now as they depend on something else.
4508  // We'll get to check them when they eventually get instantiated.
4509  if (E->isValueDependent())
4510  return E;
4511 
4512  llvm::APSInt I(64);
4513  if (!E->isIntegerConstantExpr(I, S.Context)) {
4514  S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4515  << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4516  return nullptr;
4517  }
4518  // Make sure we can fit it in 32 bits.
4519  if (!I.isIntN(32)) {
4520  S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4521  << 32 << /* Unsigned */ 1;
4522  return nullptr;
4523  }
4524  if (I < 0)
4525  S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4526  << &Attr << Idx << E->getSourceRange();
4527 
4528  // We may need to perform implicit conversion of the argument.
4530  S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4531  ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4532  assert(!ValArg.isInvalid() &&
4533  "Unexpected PerformCopyInitialization() failure.");
4534 
4535  return ValArg.getAs<Expr>();
4536 }
4537 
4538 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4539  Expr *MinBlocks, unsigned SpellingListIndex) {
4540  CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4541  SpellingListIndex);
4542  MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4543  if (MaxThreads == nullptr)
4544  return;
4545 
4546  if (MinBlocks) {
4547  MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4548  if (MinBlocks == nullptr)
4549  return;
4550  }
4551 
4552  D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4553  AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4554 }
4555 
4556 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4557  const AttributeList &Attr) {
4558  if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4559  !checkAttributeAtMostNumArgs(S, Attr, 2))
4560  return;
4561 
4562  S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4563  Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4565 }
4566 
4568  const AttributeList &Attr) {
4569  if (!Attr.isArgIdent(0)) {
4570  S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4571  << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4572  return;
4573  }
4574 
4575  if (!checkAttributeNumArgs(S, Attr, 3))
4576  return;
4577 
4578  IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
4579 
4580  if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4581  S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4582  << Attr.getName() << ExpectedFunctionOrMethod;
4583  return;
4584  }
4585 
4586  uint64_t ArgumentIdx;
4587  if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4588  ArgumentIdx))
4589  return;
4590 
4591  uint64_t TypeTagIdx;
4592  if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4593  TypeTagIdx))
4594  return;
4595 
4596  bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
4597  if (IsPointer) {
4598  // Ensure that buffer has a pointer type.
4599  QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
4600  if (!BufferTy->isPointerType()) {
4601  S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
4602  << Attr.getName() << 0;
4603  }
4604  }
4605 
4606  D->addAttr(::new (S.Context)
4607  ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4608  ArgumentIdx, TypeTagIdx, IsPointer,
4610 }
4611 
4613  const AttributeList &Attr) {
4614  if (!Attr.isArgIdent(0)) {
4615  S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4616  << Attr.getName() << 1 << AANT_ArgumentIdentifier;
4617  return;
4618  }
4619 
4620  if (!checkAttributeNumArgs(S, Attr, 1))
4621  return;
4622 
4623  if (!isa<VarDecl>(D)) {
4624  S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4625  << Attr.getName() << ExpectedVariable;
4626  return;
4627  }
4628 
4629  IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
4630  TypeSourceInfo *MatchingCTypeLoc = nullptr;
4631  S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4632  assert(MatchingCTypeLoc && "no type source info for attribute argument");
4633 
4634  D->addAttr(::new (S.Context)
4635  TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
4636  MatchingCTypeLoc,
4637  Attr.getLayoutCompatible(),
4638  Attr.getMustBeNull(),
4640 }
4641 
4642 static void handleXRayLogArgsAttr(Sema &S, Decl *D,
4643  const AttributeList &Attr) {
4644  uint64_t ArgCount;
4645 
4646  if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, Attr.getArgAsExpr(0),
4647  ArgCount,
4648  true /* AllowImplicitThis*/))
4649  return;
4650 
4651  // ArgCount isn't a parameter index [0;n), it's a count [1;n] - hence + 1.
4652  D->addAttr(::new (S.Context)
4653  XRayLogArgsAttr(Attr.getRange(), S.Context, ++ArgCount,
4655 }
4656 
4657 //===----------------------------------------------------------------------===//
4658 // Checker-specific attribute handlers.
4659 //===----------------------------------------------------------------------===//
4660 
4662  return type->isDependentType() ||
4663  type->isObjCRetainableType();
4664 }
4665 
4667  return type->isDependentType() ||
4668  type->isObjCObjectPointerType() ||
4669  S.Context.isObjCNSObjectType(type);
4670 }
4671 
4673  return type->isDependentType() ||
4674  type->isPointerType() ||
4675  isValidSubjectOfNSAttribute(S, type);
4676 }
4677 
4678 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4680  Attr.getKind() == AttributeList::AT_NSConsumed,
4681  /*template instantiation*/ false);
4682 }
4683 
4685  unsigned spellingIndex, bool isNSConsumed,
4686  bool isTemplateInstantiation) {
4687  ParmVarDecl *param = cast<ParmVarDecl>(D);
4688  bool typeOK;
4689 
4690  if (isNSConsumed) {
4691  typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
4692  } else {
4693  typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
4694  }
4695 
4696  if (!typeOK) {
4697  // These attributes are normally just advisory, but in ARC, ns_consumed
4698  // is significant. Allow non-dependent code to contain inappropriate
4699  // attributes even in ARC, but require template instantiations to be
4700  // set up correctly.
4701  Diag(D->getLocStart(),
4702  (isTemplateInstantiation && isNSConsumed &&
4703  getLangOpts().ObjCAutoRefCount
4704  ? diag::err_ns_attribute_wrong_parameter_type
4705  : diag::warn_ns_attribute_wrong_parameter_type))
4706  << attrRange
4707  << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4708  << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
4709  return;
4710  }
4711 
4712  if (isNSConsumed)
4713  param->addAttr(::new (Context)
4714  NSConsumedAttr(attrRange, Context, spellingIndex));
4715  else
4716  param->addAttr(::new (Context)
4717  CFConsumedAttr(attrRange, Context, spellingIndex));
4718 }
4719 
4721  QualType type) {
4723  return false;
4724 
4725  Diag(loc, diag::warn_ns_attribute_wrong_return_type)
4726  << "'ns_returns_retained'" << 0 << 0;
4727  return true;
4728 }
4729 
4731  const AttributeList &Attr) {
4732  QualType returnType;
4733 
4734  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4735  returnType = MD->getReturnType();
4736  else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4737  (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
4738  return; // ignore: was handled as a type attribute
4739  else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4740  returnType = PD->getType();
4741  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4742  returnType = FD->getReturnType();
4743  else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4744  returnType = Param->getType()->getPointeeType();
4745  if (returnType.isNull()) {
4746  S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4747  << Attr.getName() << /*pointer-to-CF*/2
4748  << Attr.getRange();
4749  return;
4750  }
4751  } else if (Attr.isUsedAsTypeAttr()) {
4752  return;
4753  } else {
4754  AttributeDeclKind ExpectedDeclKind;
4755  switch (Attr.getKind()) {
4756  default: llvm_unreachable("invalid ownership attribute");
4757  case AttributeList::AT_NSReturnsRetained:
4758  case AttributeList::AT_NSReturnsAutoreleased:
4759  case AttributeList::AT_NSReturnsNotRetained:
4760  ExpectedDeclKind = ExpectedFunctionOrMethod;
4761  break;
4762 
4763  case AttributeList::AT_CFReturnsRetained:
4764  case AttributeList::AT_CFReturnsNotRetained:
4765  ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4766  break;
4767  }
4768  S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4769  << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
4770  return;
4771  }
4772 
4773  bool typeOK;
4774  bool cf;
4775  switch (Attr.getKind()) {
4776  default: llvm_unreachable("invalid ownership attribute");
4777  case AttributeList::AT_NSReturnsRetained:
4778  typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
4779  cf = false;
4780  break;
4781 
4782  case AttributeList::AT_NSReturnsAutoreleased:
4783  case AttributeList::AT_NSReturnsNotRetained:
4784  typeOK = isValidSubjectOfNSAttribute(S, returnType);
4785  cf = false;
4786  break;
4787 
4788  case AttributeList::AT_CFReturnsRetained:
4789  case AttributeList::AT_CFReturnsNotRetained:
4790  typeOK = isValidSubjectOfCFAttribute(S, returnType);
4791  cf = true;
4792  break;
4793  }
4794 
4795  if (!typeOK) {
4796  if (Attr.isUsedAsTypeAttr())
4797  return;
4798 
4799  if (isa<ParmVarDecl>(D)) {
4800  S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4801  << Attr.getName() << /*pointer-to-CF*/2
4802  << Attr.getRange();
4803  } else {
4804  // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4805  enum : unsigned {
4806  Function,
4807  Method,
4808  Property
4809  } SubjectKind = Function;
4810  if (isa<ObjCMethodDecl>(D))
4811  SubjectKind = Method;
4812  else if (isa<ObjCPropertyDecl>(D))
4813  SubjectKind = Property;
4814  S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4815  << Attr.getName() << SubjectKind << cf
4816  << Attr.getRange();
4817  }
4818  return;
4819  }
4820 
4821  switch (Attr.getKind()) {
4822  default:
4823  llvm_unreachable("invalid ownership attribute");
4824  case AttributeList::AT_NSReturnsAutoreleased:
4825  D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4826  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4827  return;
4828  case AttributeList::AT_CFReturnsNotRetained:
4829  D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4830  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4831  return;
4832  case AttributeList::AT_NSReturnsNotRetained:
4833  D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4834  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4835  return;
4836  case AttributeList::AT_CFReturnsRetained:
4837  D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4838  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4839  return;
4840  case AttributeList::AT_NSReturnsRetained:
4841  D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4842  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4843  return;
4844  };
4845 }
4846 
4848  const AttributeList &Attrs) {
4849  const int EP_ObjCMethod = 1;
4850  const int EP_ObjCProperty = 2;
4851 
4852  SourceLocation loc = Attrs.getLoc();
4853  QualType resultType;
4854  if (isa<ObjCMethodDecl>(D))
4855  resultType = cast<ObjCMethodDecl>(D)->getReturnType();
4856  else
4857  resultType = cast<ObjCPropertyDecl>(D)->getType();
4858 
4859  if (!resultType->isReferenceType() &&
4860  (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4861  S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4862  << SourceRange(loc)
4863  << Attrs.getName()
4864  << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
4865  << /*non-retainable pointer*/ 2;
4866 
4867  // Drop the attribute.
4868  return;
4869  }
4870 
4871  D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4872  Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
4873 }
4874 
4876  const AttributeList &Attrs) {
4877  ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
4878 
4879  DeclContext *DC = method->getDeclContext();
4880  if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4881  S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4882  << Attrs.getName() << 0;
4883  S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4884  return;
4885  }
4886  if (method->getMethodFamily() == OMF_dealloc) {
4887  S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4888  << Attrs.getName() << 1;
4889  return;
4890  }
4891 
4892  method->addAttr(::new (S.Context)
4893  ObjCRequiresSuperAttr(Attrs.getRange(), S.Context,
4895 }
4896 
4898  const AttributeList &Attr) {
4899  if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4900  Attr.getName()))
4901  return;
4902 
4903  D->addAttr(::new (S.Context)
4904  CFAuditedTransferAttr(Attr.getRange(), S.Context,
4906 }
4907 
4909  const AttributeList &Attr) {
4910  if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4911  Attr.getName()))
4912  return;
4913 
4914  D->addAttr(::new (S.Context)
4915  CFUnknownTransferAttr(Attr.getRange(), S.Context,
4917 }
4918 
4919 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4920  const AttributeList &Attr) {
4921  IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4922 
4923  if (!Parm) {
4924  S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4925  return;
4926  }
4927 
4928  // Typedefs only allow objc_bridge(id) and have some additional checking.
4929  if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4930  if (!Parm->Ident->isStr("id")) {
4931  S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4932  << Attr.getName();
4933  return;
4934  }
4935 
4936  // Only allow 'cv void *'.
4937  QualType T = TD->getUnderlyingType();
4938  if (!T->isVoidPointerType()) {
4939  S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4940  return;
4941  }
4942  }
4943 
4944  D->addAttr(::new (S.Context)
4945  ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
4947 }
4948 
4949 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4950  const AttributeList &Attr) {
4951  IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4952 
4953  if (!Parm) {
4954  S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4955  return;
4956  }
4957 
4958  D->addAttr(::new (S.Context)
4959  ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4961 }
4962 
4963 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4964  const AttributeList &Attr) {
4965  IdentifierInfo *RelatedClass =
4966  Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
4967  if (!RelatedClass) {
4968  S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4969  return;
4970  }
4971  IdentifierInfo *ClassMethod =
4972  Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
4973  IdentifierInfo *InstanceMethod =
4974  Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
4975  D->addAttr(::new (S.Context)
4976  ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4977  ClassMethod, InstanceMethod,
4979 }
4980 
4982  const AttributeList &Attr) {
4983  ObjCInterfaceDecl *IFace;
4984  if (ObjCCategoryDecl *CatDecl =
4985  dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
4986  IFace = CatDecl->getClassInterface();
4987  else
4988  IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
4989 
4990  if (!IFace)
4991  return;
4992 
4994  D->addAttr(::new (S.Context)
4995  ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4997 }
4998 
4999 static void handleObjCRuntimeName(Sema &S, Decl *D,
5000  const AttributeList &Attr) {
5001  StringRef MetaDataName;
5002  if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
5003  return;
5004  D->addAttr(::new (S.Context)
5005  ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
5006  MetaDataName,
5008 }
5009 
5010 // When a user wants to use objc_boxable with a union or struct
5011 // but they don't have access to the declaration (legacy/third-party code)
5012 // then they can 'enable' this feature with a typedef:
5013 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5014 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
5015  bool notify = false;
5016 
5017  RecordDecl *RD = dyn_cast<RecordDecl>(D);
5018  if (RD && RD->getDefinition()) {
5019  RD = RD->getDefinition();
5020  notify = true;
5021  }
5022 
5023  if (RD) {
5024  ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
5025  ObjCBoxableAttr(Attr.getRange(), S.Context,
5027  RD->addAttr(BoxableAttr);
5028  if (notify) {
5029  // we need to notify ASTReader/ASTWriter about
5030  // modification of existing declaration
5032  L->AddedAttributeToRecord(BoxableAttr, RD);
5033  }
5034  }
5035 }
5036 
5037 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
5038  const AttributeList &Attr) {
5039  if (hasDeclarator(D)) return;
5040 
5041  S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
5042  << Attr.getRange() << Attr.getName() << ExpectedVariable;
5043 }
5044 
5046  const AttributeList &Attr) {
5047  ValueDecl *vd = cast<ValueDecl>(D);
5048  QualType type = vd->getType();
5049 
5050  if (!type->isDependentType() &&
5051  !type->isObjCLifetimeType()) {
5052  S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5053  << type;
5054  return;
5055  }
5056 
5057  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5058 
5059  // If we have no lifetime yet, check the lifetime we're presumably
5060  // going to infer.
5061  if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
5062  lifetime = type->getObjCARCImplicitLifetime();
5063 
5064  switch (lifetime) {
5065  case Qualifiers::OCL_None:
5066  assert(type->isDependentType() &&
5067  "didn't infer lifetime for non-dependent type?");
5068  break;
5069 
5070  case Qualifiers::OCL_Weak: // meaningful
5071  case Qualifiers::OCL_Strong: // meaningful
5072  break;
5073 
5076  S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5077  << (lifetime == Qualifiers::OCL_Autoreleasing);
5078  break;
5079  }
5080 
5081  D->addAttr(::new (S.Context)
5082  ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
5084 }
5085 
5086 //===----------------------------------------------------------------------===//
5087 // Microsoft specific attribute handlers.
5088 //===----------------------------------------------------------------------===//
5089 
5091  unsigned AttrSpellingListIndex, StringRef Uuid) {
5092  if (const auto *UA = D->getAttr<UuidAttr>()) {
5093  if (UA->getGuid().equals_lower(Uuid))
5094  return nullptr;
5095  Diag(UA->getLocation(), diag::err_mismatched_uuid);
5096  Diag(Range.getBegin(), diag::note_previous_uuid);
5097  D->dropAttr<UuidAttr>();
5098  }
5099 
5100  return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5101 }
5102 
5103 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5104  if (!S.LangOpts.CPlusPlus) {
5105  S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5106  << Attr.getName() << AttributeLangSupport::C;
5107  return;
5108  }
5109 
5110  StringRef StrRef;
5111  SourceLocation LiteralLoc;
5112  if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
5113  return;
5114 
5115  // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5116  // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5117  if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5118  StrRef = StrRef.drop_front().drop_back();
5119 
5120  // Validate GUID length.
5121  if (StrRef.size() != 36) {
5122  S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5123  return;
5124  }
5125 
5126  for (unsigned i = 0; i < 36; ++i) {
5127  if (i == 8 || i == 13 || i == 18 || i == 23) {
5128  if (StrRef[i] != '-') {
5129  S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5130  return;
5131  }
5132  } else if (!isHexDigit(StrRef[i])) {
5133  S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5134  return;
5135  }
5136  }
5137 
5138  // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5139  // the only thing in the [] list, the [] too), and add an insertion of
5140  // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
5141  // separating attributes nor of the [ and the ] are in the AST.
5142  // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
5143  // on cfe-dev.
5144  if (Attr.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5145  S.Diag(Attr.getLoc(), diag::warn_atl_uuid_deprecated);
5146 
5147  UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
5148  Attr.getAttributeSpellingListIndex(), StrRef);
5149  if (UA)
5150  D->addAttr(UA);
5151 }
5152 
5153 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5154  if (!S.LangOpts.CPlusPlus) {
5155  S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5156  << Attr.getName() << AttributeLangSupport::C;
5157  return;
5158  }
5159  MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5160  D, Attr.getRange(), /*BestCase=*/true,
5162  (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
5163  if (IA) {
5164  D->addAttr(IA);
5165  S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5166  }
5167 }
5168 
5170  const AttributeList &Attr) {
5171  VarDecl *VD = cast<VarDecl>(D);
5172  if (!S.Context.getTargetInfo().isTLSSupported()) {
5173  S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
5174  return;
5175  }
5176  if (VD->getTSCSpec() != TSCS_unspecified) {
5177  S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
5178  return;
5179  }
5180  if (VD->hasLocalStorage()) {
5181  S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5182  return;
5183  }
5184  VD->addAttr(::new (S.Context) ThreadAttr(
5185  Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5186 }
5187 
5188 static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5190  for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5191  StringRef Tag;
5192  if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
5193  return;
5194  Tags.push_back(Tag);
5195  }
5196