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