clang  8.0.0
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 const ParmVarDecl *getFunctionOrMethodParam(const Decl *D,
97  unsigned Idx) {
98  if (const auto *FD = dyn_cast<FunctionDecl>(D))
99  return FD->getParamDecl(Idx);
100  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
101  return MD->getParamDecl(Idx);
102  if (const auto *BD = dyn_cast<BlockDecl>(D))
103  return BD->getParamDecl(Idx);
104  return nullptr;
105 }
106 
107 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
108  if (const FunctionType *FnTy = D->getFunctionType())
109  return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
110  if (const auto *BD = dyn_cast<BlockDecl>(D))
111  return BD->getParamDecl(Idx)->getType();
112 
113  return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
114 }
115 
116 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
117  if (auto *PVD = getFunctionOrMethodParam(D, Idx))
118  return PVD->getSourceRange();
119  return SourceRange();
120 }
121 
123  if (const FunctionType *FnTy = D->getFunctionType())
124  return FnTy->getReturnType();
125  return cast<ObjCMethodDecl>(D)->getReturnType();
126 }
127 
129  if (const auto *FD = dyn_cast<FunctionDecl>(D))
130  return FD->getReturnTypeSourceRange();
131  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
132  return MD->getReturnTypeSourceRange();
133  return SourceRange();
134 }
135 
136 static bool isFunctionOrMethodVariadic(const Decl *D) {
137  if (const FunctionType *FnTy = D->getFunctionType())
138  return cast<FunctionProtoType>(FnTy)->isVariadic();
139  if (const auto *BD = dyn_cast<BlockDecl>(D))
140  return BD->isVariadic();
141  return cast<ObjCMethodDecl>(D)->isVariadic();
142 }
143 
144 static bool isInstanceMethod(const Decl *D) {
145  if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
146  return MethodDecl->isInstance();
147  return false;
148 }
149 
150 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
151  const auto *PT = T->getAs<ObjCObjectPointerType>();
152  if (!PT)
153  return false;
154 
155  ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
156  if (!Cls)
157  return false;
158 
159  IdentifierInfo* ClsName = Cls->getIdentifier();
160 
161  // FIXME: Should we walk the chain of classes?
162  return ClsName == &Ctx.Idents.get("NSString") ||
163  ClsName == &Ctx.Idents.get("NSMutableString");
164 }
165 
166 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
167  const auto *PT = T->getAs<PointerType>();
168  if (!PT)
169  return false;
170 
171  const auto *RT = PT->getPointeeType()->getAs<RecordType>();
172  if (!RT)
173  return false;
174 
175  const RecordDecl *RD = RT->getDecl();
176  if (RD->getTagKind() != TTK_Struct)
177  return false;
178 
179  return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
180 }
181 
182 static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
183  // FIXME: Include the type in the argument list.
184  return AL.getNumArgs() + AL.hasParsedType();
185 }
186 
187 template <typename Compare>
188 static bool checkAttributeNumArgsImpl(Sema &S, const ParsedAttr &AL,
189  unsigned Num, unsigned Diag,
190  Compare Comp) {
191  if (Comp(getNumAttributeArgs(AL), Num)) {
192  S.Diag(AL.getLoc(), Diag) << AL << Num;
193  return false;
194  }
195 
196  return true;
197 }
198 
199 /// Check if the attribute has exactly as many args as Num. May
200 /// output an error.
201 static bool checkAttributeNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num) {
202  return checkAttributeNumArgsImpl(S, AL, Num,
203  diag::err_attribute_wrong_number_arguments,
204  std::not_equal_to<unsigned>());
205 }
206 
207 /// Check if the attribute has at least as many args as Num. May
208 /// output an error.
209 static bool checkAttributeAtLeastNumArgs(Sema &S, const ParsedAttr &AL,
210  unsigned Num) {
211  return checkAttributeNumArgsImpl(S, AL, Num,
212  diag::err_attribute_too_few_arguments,
213  std::less<unsigned>());
214 }
215 
216 /// Check if the attribute has at most as many args as Num. May
217 /// output an error.
218 static bool checkAttributeAtMostNumArgs(Sema &S, const ParsedAttr &AL,
219  unsigned Num) {
220  return checkAttributeNumArgsImpl(S, AL, Num,
221  diag::err_attribute_too_many_arguments,
222  std::greater<unsigned>());
223 }
224 
225 /// A helper function to provide Attribute Location for the Attr types
226 /// AND the ParsedAttr.
227 template <typename AttrInfo>
228 static typename std::enable_if<std::is_base_of<Attr, AttrInfo>::value,
230 getAttrLoc(const AttrInfo &AL) {
231  return AL.getLocation();
232 }
233 static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
234 
235 /// If Expr is a valid integer constant, get the value of the integer
236 /// expression and return success or failure. May output an error.
237 ///
238 /// Negative argument is implicitly converted to unsigned, unless
239 /// \p StrictlyUnsigned is true.
240 template <typename AttrInfo>
241 static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
242  uint32_t &Val, unsigned Idx = UINT_MAX,
243  bool StrictlyUnsigned = false) {
244  llvm::APSInt I(32);
245  if (Expr->isTypeDependent() || Expr->isValueDependent() ||
246  !Expr->isIntegerConstantExpr(I, S.Context)) {
247  if (Idx != UINT_MAX)
248  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
249  << AI << Idx << AANT_ArgumentIntegerConstant
250  << Expr->getSourceRange();
251  else
252  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
253  << AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
254  return false;
255  }
256 
257  if (!I.isIntN(32)) {
258  S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
259  << I.toString(10, false) << 32 << /* Unsigned */ 1;
260  return false;
261  }
262 
263  if (StrictlyUnsigned && I.isSigned() && I.isNegative()) {
264  S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
265  << AI << /*non-negative*/ 1;
266  return false;
267  }
268 
269  Val = (uint32_t)I.getZExtValue();
270  return true;
271 }
272 
273 /// Wrapper around checkUInt32Argument, with an extra check to be sure
274 /// that the result will fit into a regular (signed) int. All args have the same
275 /// purpose as they do in checkUInt32Argument.
276 template <typename AttrInfo>
277 static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
278  int &Val, unsigned Idx = UINT_MAX) {
279  uint32_t UVal;
280  if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
281  return false;
282 
283  if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
284  llvm::APSInt I(32); // for toString
285  I = UVal;
286  S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
287  << I.toString(10, false) << 32 << /* Unsigned */ 0;
288  return false;
289  }
290 
291  Val = UVal;
292  return true;
293 }
294 
295 /// Diagnose mutually exclusive attributes when present on a given
296 /// declaration. Returns true if diagnosed.
297 template <typename AttrTy>
298 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
299  if (const auto *A = D->getAttr<AttrTy>()) {
300  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
301  S.Diag(A->getLocation(), diag::note_conflicting_attribute);
302  return true;
303  }
304  return false;
305 }
306 
307 template <typename AttrTy>
308 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
309  if (const auto *A = D->getAttr<AttrTy>()) {
310  S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL
311  << A;
312  S.Diag(A->getLocation(), diag::note_conflicting_attribute);
313  return true;
314  }
315  return false;
316 }
317 
318 /// Check if IdxExpr is a valid parameter index for a function or
319 /// instance method D. May output an error.
320 ///
321 /// \returns true if IdxExpr is a valid index.
322 template <typename AttrInfo>
324  Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
325  const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
326  assert(isFunctionOrMethodOrBlock(D));
327 
328  // In C++ the implicit 'this' function parameter also counts.
329  // Parameters are counted from one.
330  bool HP = hasFunctionProto(D);
331  bool HasImplicitThisParam = isInstanceMethod(D);
332  bool IV = HP && isFunctionOrMethodVariadic(D);
333  unsigned NumParams =
334  (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
335 
336  llvm::APSInt IdxInt;
337  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
338  !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
339  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
340  << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
341  << IdxExpr->getSourceRange();
342  return false;
343  }
344 
345  unsigned IdxSource = IdxInt.getLimitedValue(UINT_MAX);
346  if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
347  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
348  << &AI << AttrArgNum << IdxExpr->getSourceRange();
349  return false;
350  }
351  if (HasImplicitThisParam && !CanIndexImplicitThis) {
352  if (IdxSource == 1) {
353  S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
354  << &AI << IdxExpr->getSourceRange();
355  return false;
356  }
357  }
358 
359  Idx = ParamIdx(IdxSource, D);
360  return true;
361 }
362 
363 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
364 /// If not emit an error and return false. If the argument is an identifier it
365 /// will emit an error with a fixit hint and treat it as if it was a string
366 /// literal.
367 bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
368  StringRef &Str,
369  SourceLocation *ArgLocation) {
370  // Look for identifiers. If we have one emit a hint to fix it to a literal.
371  if (AL.isArgIdent(ArgNum)) {
372  IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
373  Diag(Loc->Loc, diag::err_attribute_argument_type)
374  << AL << AANT_ArgumentString
375  << FixItHint::CreateInsertion(Loc->Loc, "\"")
376  << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
377  Str = Loc->Ident->getName();
378  if (ArgLocation)
379  *ArgLocation = Loc->Loc;
380  return true;
381  }
382 
383  // Now check for an actual string literal.
384  Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
385  const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
386  if (ArgLocation)
387  *ArgLocation = ArgExpr->getBeginLoc();
388 
389  if (!Literal || !Literal->isAscii()) {
390  Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
391  << AL << AANT_ArgumentString;
392  return false;
393  }
394 
395  Str = Literal->getString();
396  return true;
397 }
398 
399 /// Applies the given attribute to the Decl without performing any
400 /// additional semantic checking.
401 template <typename AttrType>
403  unsigned SpellingIndex) {
404  D->addAttr(::new (S.Context) AttrType(SR, S.Context, SpellingIndex));
405 }
406 
407 template <typename AttrType>
408 static void handleSimpleAttribute(Sema &S, Decl *D, const ParsedAttr &AL) {
409  handleSimpleAttribute<AttrType>(S, D, AL.getRange(),
411 }
412 
413 
414 template <typename... DiagnosticArgs>
415 static const Sema::SemaDiagnosticBuilder&
417  return Bldr;
418 }
419 
420 template <typename T, typename... DiagnosticArgs>
421 static const Sema::SemaDiagnosticBuilder&
423  DiagnosticArgs &&... ExtraArgs) {
424  return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
425  std::forward<DiagnosticArgs>(ExtraArgs)...);
426 }
427 
428 /// Add an attribute {@code AttrType} to declaration {@code D}, provided that
429 /// {@code PassesCheck} is true.
430 /// Otherwise, emit diagnostic {@code DiagID}, passing in all parameters
431 /// specified in {@code ExtraArgs}.
432 template <typename AttrType, typename... DiagnosticArgs>
433 static void
434 handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, SourceRange SR,
435  unsigned SpellingIndex,
436  bool PassesCheck,
437  unsigned DiagID, DiagnosticArgs&&... ExtraArgs) {
438  if (!PassesCheck) {
439  Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
440  appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
441  return;
442  }
443  handleSimpleAttribute<AttrType>(S, D, SR, SpellingIndex);
444 }
445 
446 template <typename AttrType, typename... DiagnosticArgs>
447 static void
448 handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, const ParsedAttr &AL,
449  bool PassesCheck,
450  unsigned DiagID,
451  DiagnosticArgs&&... ExtraArgs) {
452  return handleSimpleAttributeOrDiagnose<AttrType>(
453  S, D, AL.getRange(), AL.getAttributeSpellingListIndex(), PassesCheck,
454  DiagID, std::forward<DiagnosticArgs>(ExtraArgs)...);
455 }
456 
457 template <typename AttrType>
458 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
459  const ParsedAttr &AL) {
460  handleSimpleAttribute<AttrType>(S, D, AL);
461 }
462 
463 /// Applies the given attribute to the Decl so long as the Decl doesn't
464 /// already have one of the given incompatible attributes.
465 template <typename AttrType, typename IncompatibleAttrType,
466  typename... IncompatibleAttrTypes>
467 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
468  const ParsedAttr &AL) {
469  if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, AL))
470  return;
471  handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
472  AL);
473 }
474 
475 /// Check if the passed-in expression is of type int or bool.
476 static bool isIntOrBool(Expr *Exp) {
477  QualType QT = Exp->getType();
478  return QT->isBooleanType() || QT->isIntegerType();
479 }
480 
481 
482 // Check to see if the type is a smart pointer of some kind. We assume
483 // it's a smart pointer if it defines both operator-> and operator*.
484 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
485  auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
487  DeclContextLookupResult Result =
489  return !Result.empty();
490  };
491 
492  const RecordDecl *Record = RT->getDecl();
493  bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
494  bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
495  if (foundStarOperator && foundArrowOperator)
496  return true;
497 
498  const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
499  if (!CXXRecord)
500  return false;
501 
502  for (auto BaseSpecifier : CXXRecord->bases()) {
503  if (!foundStarOperator)
504  foundStarOperator = IsOverloadedOperatorPresent(
505  BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
506  if (!foundArrowOperator)
507  foundArrowOperator = IsOverloadedOperatorPresent(
508  BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
509  }
510 
511  if (foundStarOperator && foundArrowOperator)
512  return true;
513 
514  return false;
515 }
516 
517 /// Check if passed in Decl is a pointer type.
518 /// Note that this function may produce an error message.
519 /// \return true if the Decl is a pointer type; false otherwise
520 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
521  const ParsedAttr &AL) {
522  const auto *VD = cast<ValueDecl>(D);
523  QualType QT = VD->getType();
524  if (QT->isAnyPointerType())
525  return true;
526 
527  if (const auto *RT = QT->getAs<RecordType>()) {
528  // If it's an incomplete type, it could be a smart pointer; skip it.
529  // (We don't want to force template instantiation if we can avoid it,
530  // since that would alter the order in which templates are instantiated.)
531  if (RT->isIncompleteType())
532  return true;
533 
534  if (threadSafetyCheckIsSmartPointer(S, RT))
535  return true;
536  }
537 
538  S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
539  return false;
540 }
541 
542 /// Checks that the passed in QualType either is of RecordType or points
543 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
544 static const RecordType *getRecordType(QualType QT) {
545  if (const auto *RT = QT->getAs<RecordType>())
546  return RT;
547 
548  // Now check if we point to record type.
549  if (const auto *PT = QT->getAs<PointerType>())
550  return PT->getPointeeType()->getAs<RecordType>();
551 
552  return nullptr;
553 }
554 
555 template <typename AttrType>
556 static bool checkRecordDeclForAttr(const RecordDecl *RD) {
557  // Check if the record itself has the attribute.
558  if (RD->hasAttr<AttrType>())
559  return true;
560 
561  // Else check if any base classes have the attribute.
562  if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
563  CXXBasePaths BPaths(false, false);
564  if (CRD->lookupInBases(
565  [](const CXXBaseSpecifier *BS, CXXBasePath &) {
566  const auto &Ty = *BS->getType();
567  // If it's type-dependent, we assume it could have the attribute.
568  if (Ty.isDependentType())
569  return true;
570  return Ty.getAs<RecordType>()->getDecl()->hasAttr<AttrType>();
571  },
572  BPaths, true))
573  return true;
574  }
575  return false;
576 }
577 
578 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
579  const RecordType *RT = getRecordType(Ty);
580 
581  if (!RT)
582  return false;
583 
584  // Don't check for the capability if the class hasn't been defined yet.
585  if (RT->isIncompleteType())
586  return true;
587 
588  // Allow smart pointers to be used as capability objects.
589  // FIXME -- Check the type that the smart pointer points to.
590  if (threadSafetyCheckIsSmartPointer(S, RT))
591  return true;
592 
593  return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
594 }
595 
596 static bool checkTypedefTypeForCapability(QualType Ty) {
597  const auto *TD = Ty->getAs<TypedefType>();
598  if (!TD)
599  return false;
600 
601  TypedefNameDecl *TN = TD->getDecl();
602  if (!TN)
603  return false;
604 
605  return TN->hasAttr<CapabilityAttr>();
606 }
607 
608 static bool typeHasCapability(Sema &S, QualType Ty) {
609  if (checkTypedefTypeForCapability(Ty))
610  return true;
611 
612  if (checkRecordTypeForCapability(S, Ty))
613  return true;
614 
615  return false;
616 }
617 
618 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
619  // Capability expressions are simple expressions involving the boolean logic
620  // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
621  // a DeclRefExpr is found, its type should be checked to determine whether it
622  // is a capability or not.
623 
624  if (const auto *E = dyn_cast<CastExpr>(Ex))
625  return isCapabilityExpr(S, E->getSubExpr());
626  else if (const auto *E = dyn_cast<ParenExpr>(Ex))
627  return isCapabilityExpr(S, E->getSubExpr());
628  else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
629  if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
630  E->getOpcode() == UO_Deref)
631  return isCapabilityExpr(S, E->getSubExpr());
632  return false;
633  } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
634  if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
635  return isCapabilityExpr(S, E->getLHS()) &&
636  isCapabilityExpr(S, E->getRHS());
637  return false;
638  }
639 
640  return typeHasCapability(S, Ex->getType());
641 }
642 
643 /// Checks that all attribute arguments, starting from Sidx, resolve to
644 /// a capability object.
645 /// \param Sidx The attribute argument index to start checking with.
646 /// \param ParamIdxOk Whether an argument can be indexing into a function
647 /// parameter list.
648 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
649  const ParsedAttr &AL,
651  unsigned Sidx = 0,
652  bool ParamIdxOk = false) {
653  if (Sidx == AL.getNumArgs()) {
654  // If we don't have any capability arguments, the attribute implicitly
655  // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
656  // a non-static method, and that the class is a (scoped) capability.
657  const auto *MD = dyn_cast<const CXXMethodDecl>(D);
658  if (MD && !MD->isStatic()) {
659  const CXXRecordDecl *RD = MD->getParent();
660  // FIXME -- need to check this again on template instantiation
661  if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
662  !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
663  S.Diag(AL.getLoc(),
664  diag::warn_thread_attribute_not_on_capability_member)
665  << AL << MD->getParent();
666  } else {
667  S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
668  << AL;
669  }
670  }
671 
672  for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
673  Expr *ArgExp = AL.getArgAsExpr(Idx);
674 
675  if (ArgExp->isTypeDependent()) {
676  // FIXME -- need to check this again on template instantiation
677  Args.push_back(ArgExp);
678  continue;
679  }
680 
681  if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
682  if (StrLit->getLength() == 0 ||
683  (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
684  // Pass empty strings to the analyzer without warnings.
685  // Treat "*" as the universal lock.
686  Args.push_back(ArgExp);
687  continue;
688  }
689 
690  // We allow constant strings to be used as a placeholder for expressions
691  // that are not valid C++ syntax, but warn that they are ignored.
692  S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
693  Args.push_back(ArgExp);
694  continue;
695  }
696 
697  QualType ArgTy = ArgExp->getType();
698 
699  // A pointer to member expression of the form &MyClass::mu is treated
700  // specially -- we need to look at the type of the member.
701  if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
702  if (UOp->getOpcode() == UO_AddrOf)
703  if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
704  if (DRE->getDecl()->isCXXInstanceMember())
705  ArgTy = DRE->getDecl()->getType();
706 
707  // First see if we can just cast to record type, or pointer to record type.
708  const RecordType *RT = getRecordType(ArgTy);
709 
710  // Now check if we index into a record type function param.
711  if(!RT && ParamIdxOk) {
712  const auto *FD = dyn_cast<FunctionDecl>(D);
713  const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
714  if(FD && IL) {
715  unsigned int NumParams = FD->getNumParams();
716  llvm::APInt ArgValue = IL->getValue();
717  uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
718  uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
719  if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
720  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
721  << AL << Idx + 1 << NumParams;
722  continue;
723  }
724  ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
725  }
726  }
727 
728  // If the type does not have a capability, see if the components of the
729  // expression have capabilities. This allows for writing C code where the
730  // capability may be on the type, and the expression is a capability
731  // boolean logic expression. Eg) requires_capability(A || B && !C)
732  if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
733  S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
734  << AL << ArgTy;
735 
736  Args.push_back(ArgExp);
737  }
738 }
739 
740 //===----------------------------------------------------------------------===//
741 // Attribute Implementations
742 //===----------------------------------------------------------------------===//
743 
744 static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
745  if (!threadSafetyCheckIsPointer(S, D, AL))
746  return;
747 
748  D->addAttr(::new (S.Context)
749  PtGuardedVarAttr(AL.getRange(), S.Context,
751 }
752 
753 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
754  Expr *&Arg) {
756  // check that all arguments are lockable objects
757  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
758  unsigned Size = Args.size();
759  if (Size != 1)
760  return false;
761 
762  Arg = Args[0];
763 
764  return true;
765 }
766 
767 static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
768  Expr *Arg = nullptr;
769  if (!checkGuardedByAttrCommon(S, D, AL, Arg))
770  return;
771 
772  D->addAttr(::new (S.Context) GuardedByAttr(
773  AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex()));
774 }
775 
776 static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
777  Expr *Arg = nullptr;
778  if (!checkGuardedByAttrCommon(S, D, AL, Arg))
779  return;
780 
781  if (!threadSafetyCheckIsPointer(S, D, AL))
782  return;
783 
784  D->addAttr(::new (S.Context) PtGuardedByAttr(
785  AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex()));
786 }
787 
788 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
789  SmallVectorImpl<Expr *> &Args) {
790  if (!checkAttributeAtLeastNumArgs(S, AL, 1))
791  return false;
792 
793  // Check that this attribute only applies to lockable types.
794  QualType QT = cast<ValueDecl>(D)->getType();
795  if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
796  S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
797  return false;
798  }
799 
800  // Check that all arguments are lockable objects.
801  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
802  if (Args.empty())
803  return false;
804 
805  return true;
806 }
807 
808 static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
810  if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
811  return;
812 
813  Expr **StartArg = &Args[0];
814  D->addAttr(::new (S.Context) AcquiredAfterAttr(
815  AL.getRange(), S.Context, StartArg, Args.size(),
817 }
818 
819 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
821  if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
822  return;
823 
824  Expr **StartArg = &Args[0];
825  D->addAttr(::new (S.Context) AcquiredBeforeAttr(
826  AL.getRange(), S.Context, StartArg, Args.size(),
828 }
829 
830 static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
831  SmallVectorImpl<Expr *> &Args) {
832  // zero or more arguments ok
833  // check that all arguments are lockable objects
834  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
835 
836  return true;
837 }
838 
839 static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
841  if (!checkLockFunAttrCommon(S, D, AL, Args))
842  return;
843 
844  unsigned Size = Args.size();
845  Expr **StartArg = Size == 0 ? nullptr : &Args[0];
846  D->addAttr(::new (S.Context)
847  AssertSharedLockAttr(AL.getRange(), S.Context, StartArg, Size,
849 }
850 
851 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
852  const ParsedAttr &AL) {
854  if (!checkLockFunAttrCommon(S, D, AL, Args))
855  return;
856 
857  unsigned Size = Args.size();
858  Expr **StartArg = Size == 0 ? nullptr : &Args[0];
859  D->addAttr(::new (S.Context) AssertExclusiveLockAttr(
860  AL.getRange(), S.Context, StartArg, Size,
862 }
863 
864 /// Checks to be sure that the given parameter number is in bounds, and
865 /// is an integral type. Will emit appropriate diagnostics if this returns
866 /// false.
867 ///
868 /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
869 template <typename AttrInfo>
870 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
871  const AttrInfo &AI, unsigned AttrArgNo) {
872  assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
873  Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
874  ParamIdx Idx;
875  if (!checkFunctionOrMethodParameterIndex(S, FD, AI, AttrArgNo + 1, AttrArg,
876  Idx))
877  return false;
878 
879  const ParmVarDecl *Param = FD->getParamDecl(Idx.getASTIndex());
880  if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
881  SourceLocation SrcLoc = AttrArg->getBeginLoc();
882  S.Diag(SrcLoc, diag::err_attribute_integers_only)
883  << AI << Param->getSourceRange();
884  return false;
885  }
886  return true;
887 }
888 
889 static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
890  if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
891  !checkAttributeAtMostNumArgs(S, AL, 2))
892  return;
893 
894  const auto *FD = cast<FunctionDecl>(D);
895  if (!FD->getReturnType()->isPointerType()) {
896  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
897  return;
898  }
899 
900  const Expr *SizeExpr = AL.getArgAsExpr(0);
901  int SizeArgNoVal;
902  // Parameter indices are 1-indexed, hence Index=1
903  if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Index=*/1))
904  return;
905  if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/0))
906  return;
907  ParamIdx SizeArgNo(SizeArgNoVal, D);
908 
909  ParamIdx NumberArgNo;
910  if (AL.getNumArgs() == 2) {
911  const Expr *NumberExpr = AL.getArgAsExpr(1);
912  int Val;
913  // Parameter indices are 1-based, hence Index=2
914  if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Index=*/2))
915  return;
916  if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/1))
917  return;
918  NumberArgNo = ParamIdx(Val, D);
919  }
920 
921  D->addAttr(::new (S.Context)
922  AllocSizeAttr(AL.getRange(), S.Context, SizeArgNo, NumberArgNo,
924 }
925 
926 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
927  SmallVectorImpl<Expr *> &Args) {
928  if (!checkAttributeAtLeastNumArgs(S, AL, 1))
929  return false;
930 
931  if (!isIntOrBool(AL.getArgAsExpr(0))) {
932  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
933  << AL << 1 << AANT_ArgumentIntOrBool;
934  return false;
935  }
936 
937  // check that all arguments are lockable objects
938  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
939 
940  return true;
941 }
942 
943 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
944  const ParsedAttr &AL) {
946  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
947  return;
948 
949  D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
950  AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), Args.size(),
952 }
953 
954 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
955  const ParsedAttr &AL) {
957  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
958  return;
959 
960  D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
961  AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(),
962  Args.size(), AL.getAttributeSpellingListIndex()));
963 }
964 
965 static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
966  // check that the argument is lockable object
968  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
969  unsigned Size = Args.size();
970  if (Size == 0)
971  return;
972 
973  D->addAttr(::new (S.Context)
974  LockReturnedAttr(AL.getRange(), S.Context, Args[0],
976 }
977 
978 static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
979  if (!checkAttributeAtLeastNumArgs(S, AL, 1))
980  return;
981 
982  // check that all arguments are lockable objects
984  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
985  unsigned Size = Args.size();
986  if (Size == 0)
987  return;
988  Expr **StartArg = &Args[0];
989 
990  D->addAttr(::new (S.Context)
991  LocksExcludedAttr(AL.getRange(), S.Context, StartArg, Size,
993 }
994 
995 static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
996  Expr *&Cond, StringRef &Msg) {
997  Cond = AL.getArgAsExpr(0);
998  if (!Cond->isTypeDependent()) {
999  ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
1000  if (Converted.isInvalid())
1001  return false;
1002  Cond = Converted.get();
1003  }
1004 
1005  if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
1006  return false;
1007 
1008  if (Msg.empty())
1009  Msg = "<no message provided>";
1010 
1012  if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
1013  !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
1014  Diags)) {
1015  S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
1016  for (const PartialDiagnosticAt &PDiag : Diags)
1017  S.Diag(PDiag.first, PDiag.second);
1018  return false;
1019  }
1020  return true;
1021 }
1022 
1023 static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1024  S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
1025 
1026  Expr *Cond;
1027  StringRef Msg;
1028  if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1029  D->addAttr(::new (S.Context)
1030  EnableIfAttr(AL.getRange(), S.Context, Cond, Msg,
1032 }
1033 
1034 namespace {
1035 /// Determines if a given Expr references any of the given function's
1036 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
1037 class ArgumentDependenceChecker
1038  : public RecursiveASTVisitor<ArgumentDependenceChecker> {
1039 #ifndef NDEBUG
1040  const CXXRecordDecl *ClassType;
1041 #endif
1042  llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
1043  bool Result;
1044 
1045 public:
1046  ArgumentDependenceChecker(const FunctionDecl *FD) {
1047 #ifndef NDEBUG
1048  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1049  ClassType = MD->getParent();
1050  else
1051  ClassType = nullptr;
1052 #endif
1053  Parms.insert(FD->param_begin(), FD->param_end());
1054  }
1055 
1056  bool referencesArgs(Expr *E) {
1057  Result = false;
1058  TraverseStmt(E);
1059  return Result;
1060  }
1061 
1062  bool VisitCXXThisExpr(CXXThisExpr *E) {
1063  assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1064  "`this` doesn't refer to the enclosing class?");
1065  Result = true;
1066  return false;
1067  }
1068 
1069  bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1070  if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1071  if (Parms.count(PVD)) {
1072  Result = true;
1073  return false;
1074  }
1075  return true;
1076  }
1077 };
1078 }
1079 
1080 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1081  S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
1082 
1083  Expr *Cond;
1084  StringRef Msg;
1085  if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1086  return;
1087 
1088  StringRef DiagTypeStr;
1089  if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
1090  return;
1091 
1092  DiagnoseIfAttr::DiagnosticType DiagType;
1093  if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1094  S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1095  diag::err_diagnose_if_invalid_diagnostic_type);
1096  return;
1097  }
1098 
1099  bool ArgDependent = false;
1100  if (const auto *FD = dyn_cast<FunctionDecl>(D))
1101  ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1102  D->addAttr(::new (S.Context) DiagnoseIfAttr(
1103  AL.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent,
1104  cast<NamedDecl>(D), AL.getAttributeSpellingListIndex()));
1105 }
1106 
1107 static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1108  if (D->hasAttr<PassObjectSizeAttr>()) {
1109  S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1110  return;
1111  }
1112 
1113  Expr *E = AL.getArgAsExpr(0);
1114  uint32_t Type;
1115  if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1116  return;
1117 
1118  // pass_object_size's argument is passed in as the second argument of
1119  // __builtin_object_size. So, it has the same constraints as that second
1120  // argument; namely, it must be in the range [0, 3].
1121  if (Type > 3) {
1122  S.Diag(E->getBeginLoc(), diag::err_attribute_argument_outof_range)
1123  << AL << 0 << 3 << E->getSourceRange();
1124  return;
1125  }
1126 
1127  // pass_object_size is only supported on constant pointer parameters; as a
1128  // kindness to users, we allow the parameter to be non-const for declarations.
1129  // At this point, we have no clue if `D` belongs to a function declaration or
1130  // definition, so we defer the constness check until later.
1131  if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1132  S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1133  return;
1134  }
1135 
1136  D->addAttr(::new (S.Context) PassObjectSizeAttr(
1137  AL.getRange(), S.Context, (int)Type, AL.getAttributeSpellingListIndex()));
1138 }
1139 
1140 static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1141  ConsumableAttr::ConsumedState DefaultState;
1142 
1143  if (AL.isArgIdent(0)) {
1144  IdentifierLoc *IL = AL.getArgAsIdent(0);
1145  if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1146  DefaultState)) {
1147  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1148  << IL->Ident;
1149  return;
1150  }
1151  } else {
1152  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1153  << AL << AANT_ArgumentIdentifier;
1154  return;
1155  }
1156 
1157  D->addAttr(::new (S.Context)
1158  ConsumableAttr(AL.getRange(), S.Context, DefaultState,
1160 }
1161 
1162 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1163  const ParsedAttr &AL) {
1164  QualType ThisType = MD->getThisType()->getPointeeType();
1165 
1166  if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1167  if (!RD->hasAttr<ConsumableAttr>()) {
1168  S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1169  RD->getNameAsString();
1170 
1171  return false;
1172  }
1173  }
1174 
1175  return true;
1176 }
1177 
1178 static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1179  if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1180  return;
1181 
1182  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1183  return;
1184 
1186  for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1187  CallableWhenAttr::ConsumedState CallableState;
1188 
1189  StringRef StateString;
1190  SourceLocation Loc;
1191  if (AL.isArgIdent(ArgIndex)) {
1192  IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1193  StateString = Ident->Ident->getName();
1194  Loc = Ident->Loc;
1195  } else {
1196  if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1197  return;
1198  }
1199 
1200  if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1201  CallableState)) {
1202  S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1203  return;
1204  }
1205 
1206  States.push_back(CallableState);
1207  }
1208 
1209  D->addAttr(::new (S.Context)
1210  CallableWhenAttr(AL.getRange(), S.Context, States.data(),
1211  States.size(), AL.getAttributeSpellingListIndex()));
1212 }
1213 
1214 static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1216 
1217  if (AL.isArgIdent(0)) {
1218  IdentifierLoc *Ident = AL.getArgAsIdent(0);
1219  StringRef StateString = Ident->Ident->getName();
1220 
1221  if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1222  ParamState)) {
1223  S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1224  << AL << StateString;
1225  return;
1226  }
1227  } else {
1228  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1229  << AL << AANT_ArgumentIdentifier;
1230  return;
1231  }
1232 
1233  // FIXME: This check is currently being done in the analysis. It can be
1234  // enabled here only after the parser propagates attributes at
1235  // template specialization definition, not declaration.
1236  //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1237  //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1238  //
1239  //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1240  // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1241  // ReturnType.getAsString();
1242  // return;
1243  //}
1244 
1245  D->addAttr(::new (S.Context)
1246  ParamTypestateAttr(AL.getRange(), S.Context, ParamState,
1248 }
1249 
1250 static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1252 
1253  if (AL.isArgIdent(0)) {
1254  IdentifierLoc *IL = AL.getArgAsIdent(0);
1255  if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1256  ReturnState)) {
1257  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1258  << IL->Ident;
1259  return;
1260  }
1261  } else {
1262  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1263  << AL << AANT_ArgumentIdentifier;
1264  return;
1265  }
1266 
1267  // FIXME: This check is currently being done in the analysis. It can be
1268  // enabled here only after the parser propagates attributes at
1269  // template specialization definition, not declaration.
1270  //QualType ReturnType;
1271  //
1272  //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1273  // ReturnType = Param->getType();
1274  //
1275  //} else if (const CXXConstructorDecl *Constructor =
1276  // dyn_cast<CXXConstructorDecl>(D)) {
1277  // ReturnType = Constructor->getThisType()->getPointeeType();
1278  //
1279  //} else {
1280  //
1281  // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1282  //}
1283  //
1284  //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1285  //
1286  //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1287  // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1288  // ReturnType.getAsString();
1289  // return;
1290  //}
1291 
1292  D->addAttr(::new (S.Context)
1293  ReturnTypestateAttr(AL.getRange(), S.Context, ReturnState,
1295 }
1296 
1297 static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1298  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1299  return;
1300 
1302  if (AL.isArgIdent(0)) {
1303  IdentifierLoc *Ident = AL.getArgAsIdent(0);
1304  StringRef Param = Ident->Ident->getName();
1305  if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1306  S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1307  << Param;
1308  return;
1309  }
1310  } else {
1311  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1312  << AL << AANT_ArgumentIdentifier;
1313  return;
1314  }
1315 
1316  D->addAttr(::new (S.Context)
1317  SetTypestateAttr(AL.getRange(), S.Context, NewState,
1319 }
1320 
1321 static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1322  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1323  return;
1324 
1326  if (AL.isArgIdent(0)) {
1327  IdentifierLoc *Ident = AL.getArgAsIdent(0);
1328  StringRef Param = Ident->Ident->getName();
1329  if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1330  S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1331  << Param;
1332  return;
1333  }
1334  } else {
1335  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1336  << AL << AANT_ArgumentIdentifier;
1337  return;
1338  }
1339 
1340  D->addAttr(::new (S.Context)
1341  TestTypestateAttr(AL.getRange(), S.Context, TestState,
1343 }
1344 
1345 static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1346  // Remember this typedef decl, we will need it later for diagnostics.
1347  S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1348 }
1349 
1350 static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1351  if (auto *TD = dyn_cast<TagDecl>(D))
1352  TD->addAttr(::new (S.Context) PackedAttr(AL.getRange(), S.Context,
1354  else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1355  bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1356  !FD->getType()->isIncompleteType() &&
1357  FD->isBitField() &&
1358  S.Context.getTypeAlign(FD->getType()) <= 8);
1359 
1360  if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
1361  if (BitfieldByteAligned)
1362  // The PS4 target needs to maintain ABI backwards compatibility.
1363  S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1364  << AL << FD->getType();
1365  else
1366  FD->addAttr(::new (S.Context) PackedAttr(
1368  } else {
1369  // Report warning about changed offset in the newer compiler versions.
1370  if (BitfieldByteAligned)
1371  S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1372 
1373  FD->addAttr(::new (S.Context) PackedAttr(
1375  }
1376 
1377  } else
1378  S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1379 }
1380 
1381 static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1382  // The IBOutlet/IBOutletCollection attributes only apply to instance
1383  // variables or properties of Objective-C classes. The outlet must also
1384  // have an object reference type.
1385  if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1386  if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1387  S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1388  << AL << VD->getType() << 0;
1389  return false;
1390  }
1391  }
1392  else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1393  if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1394  S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1395  << AL << PD->getType() << 1;
1396  return false;
1397  }
1398  }
1399  else {
1400  S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1401  return false;
1402  }
1403 
1404  return true;
1405 }
1406 
1407 static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1408  if (!checkIBOutletCommon(S, D, AL))
1409  return;
1410 
1411  D->addAttr(::new (S.Context)
1412  IBOutletAttr(AL.getRange(), S.Context,
1414 }
1415 
1416 static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1417 
1418  // The iboutletcollection attribute can have zero or one arguments.
1419  if (AL.getNumArgs() > 1) {
1420  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1421  return;
1422  }
1423 
1424  if (!checkIBOutletCommon(S, D, AL))
1425  return;
1426 
1427  ParsedType PT;
1428 
1429  if (AL.hasParsedType())
1430  PT = AL.getTypeArg();
1431  else {
1432  PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1434  if (!PT) {
1435  S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1436  return;
1437  }
1438  }
1439 
1440  TypeSourceInfo *QTLoc = nullptr;
1441  QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1442  if (!QTLoc)
1443  QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1444 
1445  // Diagnose use of non-object type in iboutletcollection attribute.
1446  // FIXME. Gnu attribute extension ignores use of builtin types in
1447  // attributes. So, __attribute__((iboutletcollection(char))) will be
1448  // treated as __attribute__((iboutletcollection())).
1449  if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1450  S.Diag(AL.getLoc(),
1451  QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1452  : diag::err_iboutletcollection_type) << QT;
1453  return;
1454  }
1455 
1456  D->addAttr(::new (S.Context)
1457  IBOutletCollectionAttr(AL.getRange(), S.Context, QTLoc,
1459 }
1460 
1461 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1462  if (RefOkay) {
1463  if (T->isReferenceType())
1464  return true;
1465  } else {
1466  T = T.getNonReferenceType();
1467  }
1468 
1469  // The nonnull attribute, and other similar attributes, can be applied to a
1470  // transparent union that contains a pointer type.
1471  if (const RecordType *UT = T->getAsUnionType()) {
1472  if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1473  RecordDecl *UD = UT->getDecl();
1474  for (const auto *I : UD->fields()) {
1475  QualType QT = I->getType();
1476  if (QT->isAnyPointerType() || QT->isBlockPointerType())
1477  return true;
1478  }
1479  }
1480  }
1481 
1482  return T->isAnyPointerType() || T->isBlockPointerType();
1483 }
1484 
1485 static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1486  SourceRange AttrParmRange,
1487  SourceRange TypeRange,
1488  bool isReturnValue = false) {
1489  if (!S.isValidPointerAttrType(T)) {
1490  if (isReturnValue)
1491  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1492  << AL << AttrParmRange << TypeRange;
1493  else
1494  S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1495  << AL << AttrParmRange << TypeRange << 0;
1496  return false;
1497  }
1498  return true;
1499 }
1500 
1501 static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1502  SmallVector<ParamIdx, 8> NonNullArgs;
1503  for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1504  Expr *Ex = AL.getArgAsExpr(I);
1505  ParamIdx Idx;
1506  if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1507  return;
1508 
1509  // Is the function argument a pointer type?
1510  if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1511  !attrNonNullArgCheck(
1512  S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1513  Ex->getSourceRange(),
1515  continue;
1516 
1517  NonNullArgs.push_back(Idx);
1518  }
1519 
1520  // If no arguments were specified to __attribute__((nonnull)) then all pointer
1521  // arguments have a nonnull attribute; warn if there aren't any. Skip this
1522  // check if the attribute came from a macro expansion or a template
1523  // instantiation.
1524  if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1525  !S.inTemplateInstantiation()) {
1526  bool AnyPointers = isFunctionOrMethodVariadic(D);
1527  for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1528  I != E && !AnyPointers; ++I) {
1530  if (T->isDependentType() || S.isValidPointerAttrType(T))
1531  AnyPointers = true;
1532  }
1533 
1534  if (!AnyPointers)
1535  S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1536  }
1537 
1538  ParamIdx *Start = NonNullArgs.data();
1539  unsigned Size = NonNullArgs.size();
1540  llvm::array_pod_sort(Start, Start + Size);
1541  D->addAttr(::new (S.Context)
1542  NonNullAttr(AL.getRange(), S.Context, Start, Size,
1544 }
1545 
1546 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1547  const ParsedAttr &AL) {
1548  if (AL.getNumArgs() > 0) {
1549  if (D->getFunctionType()) {
1550  handleNonNullAttr(S, D, AL);
1551  } else {
1552  S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1553  << D->getSourceRange();
1554  }
1555  return;
1556  }
1557 
1558  // Is the argument a pointer type?
1559  if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1560  D->getSourceRange()))
1561  return;
1562 
1563  D->addAttr(::new (S.Context)
1564  NonNullAttr(AL.getRange(), S.Context, nullptr, 0,
1566 }
1567 
1568 static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1569  QualType ResultType = getFunctionOrMethodResultType(D);
1571  if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1572  /* isReturnValue */ true))
1573  return;
1574 
1575  D->addAttr(::new (S.Context)
1576  ReturnsNonNullAttr(AL.getRange(), S.Context,
1578 }
1579 
1580 static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1581  if (D->isInvalidDecl())
1582  return;
1583 
1584  // noescape only applies to pointer types.
1585  QualType T = cast<ParmVarDecl>(D)->getType();
1586  if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1587  S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1588  << AL << AL.getRange() << 0;
1589  return;
1590  }
1591 
1592  D->addAttr(::new (S.Context) NoEscapeAttr(
1594 }
1595 
1596 static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1597  Expr *E = AL.getArgAsExpr(0),
1598  *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1599  S.AddAssumeAlignedAttr(AL.getRange(), D, E, OE,
1601 }
1602 
1603 static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1604  S.AddAllocAlignAttr(AL.getRange(), D, AL.getArgAsExpr(0),
1606 }
1607 
1608 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1609  Expr *OE, unsigned SpellingListIndex) {
1610  QualType ResultType = getFunctionOrMethodResultType(D);
1612 
1613  AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1614  SourceLocation AttrLoc = AttrRange.getBegin();
1615 
1616  if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1617  Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1618  << &TmpAttr << AttrRange << SR;
1619  return;
1620  }
1621 
1622  if (!E->isValueDependent()) {
1623  llvm::APSInt I(64);
1624  if (!E->isIntegerConstantExpr(I, Context)) {
1625  if (OE)
1626  Diag(AttrLoc, diag::err_attribute_argument_n_type)
1627  << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1628  << E->getSourceRange();
1629  else
1630  Diag(AttrLoc, diag::err_attribute_argument_type)
1631  << &TmpAttr << AANT_ArgumentIntegerConstant
1632  << E->getSourceRange();
1633  return;
1634  }
1635 
1636  if (!I.isPowerOf2()) {
1637  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1638  << E->getSourceRange();
1639  return;
1640  }
1641  }
1642 
1643  if (OE) {
1644  if (!OE->isValueDependent()) {
1645  llvm::APSInt I(64);
1646  if (!OE->isIntegerConstantExpr(I, Context)) {
1647  Diag(AttrLoc, diag::err_attribute_argument_n_type)
1648  << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1649  << OE->getSourceRange();
1650  return;
1651  }
1652  }
1653  }
1654 
1655  D->addAttr(::new (Context)
1656  AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1657 }
1658 
1659 void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
1660  unsigned SpellingListIndex) {
1661  QualType ResultType = getFunctionOrMethodResultType(D);
1662 
1663  AllocAlignAttr TmpAttr(AttrRange, Context, ParamIdx(), SpellingListIndex);
1664  SourceLocation AttrLoc = AttrRange.getBegin();
1665 
1666  if (!ResultType->isDependentType() &&
1667  !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1668  Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1669  << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D);
1670  return;
1671  }
1672 
1673  ParamIdx Idx;
1674  const auto *FuncDecl = cast<FunctionDecl>(D);
1675  if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1676  /*AttrArgNo=*/1, ParamExpr, Idx))
1677  return;
1678 
1680  if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) {
1681  Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1682  << &TmpAttr
1683  << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1684  return;
1685  }
1686 
1687  D->addAttr(::new (Context)
1688  AllocAlignAttr(AttrRange, Context, Idx, SpellingListIndex));
1689 }
1690 
1691 /// Normalize the attribute, __foo__ becomes foo.
1692 /// Returns true if normalization was applied.
1693 static bool normalizeName(StringRef &AttrName) {
1694  if (AttrName.size() > 4 && AttrName.startswith("__") &&
1695  AttrName.endswith("__")) {
1696  AttrName = AttrName.drop_front(2).drop_back(2);
1697  return true;
1698  }
1699  return false;
1700 }
1701 
1702 static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1703  // This attribute must be applied to a function declaration. The first
1704  // argument to the attribute must be an identifier, the name of the resource,
1705  // for example: malloc. The following arguments must be argument indexes, the
1706  // arguments must be of integer type for Returns, otherwise of pointer type.
1707  // The difference between Holds and Takes is that a pointer may still be used
1708  // after being held. free() should be __attribute((ownership_takes)), whereas
1709  // a list append function may well be __attribute((ownership_holds)).
1710 
1711  if (!AL.isArgIdent(0)) {
1712  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1713  << AL << 1 << AANT_ArgumentIdentifier;
1714  return;
1715  }
1716 
1717  // Figure out our Kind.
1718  OwnershipAttr::OwnershipKind K =
1719  OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1720  AL.getAttributeSpellingListIndex()).getOwnKind();
1721 
1722  // Check arguments.
1723  switch (K) {
1724  case OwnershipAttr::Takes:
1725  case OwnershipAttr::Holds:
1726  if (AL.getNumArgs() < 2) {
1727  S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1728  return;
1729  }
1730  break;
1731  case OwnershipAttr::Returns:
1732  if (AL.getNumArgs() > 2) {
1733  S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1734  return;
1735  }
1736  break;
1737  }
1738 
1740 
1741  StringRef ModuleName = Module->getName();
1742  if (normalizeName(ModuleName)) {
1743  Module = &S.PP.getIdentifierTable().get(ModuleName);
1744  }
1745 
1746  SmallVector<ParamIdx, 8> OwnershipArgs;
1747  for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1748  Expr *Ex = AL.getArgAsExpr(i);
1749  ParamIdx Idx;
1750  if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1751  return;
1752 
1753  // Is the function argument a pointer type?
1755  int Err = -1; // No error
1756  switch (K) {
1757  case OwnershipAttr::Takes:
1758  case OwnershipAttr::Holds:
1759  if (!T->isAnyPointerType() && !T->isBlockPointerType())
1760  Err = 0;
1761  break;
1762  case OwnershipAttr::Returns:
1763  if (!T->isIntegerType())
1764  Err = 1;
1765  break;
1766  }
1767  if (-1 != Err) {
1768  S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1769  << Ex->getSourceRange();
1770  return;
1771  }
1772 
1773  // Check we don't have a conflict with another ownership attribute.
1774  for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1775  // Cannot have two ownership attributes of different kinds for the same
1776  // index.
1777  if (I->getOwnKind() != K && I->args_end() !=
1778  std::find(I->args_begin(), I->args_end(), Idx)) {
1779  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I;
1780  return;
1781  } else if (K == OwnershipAttr::Returns &&
1782  I->getOwnKind() == OwnershipAttr::Returns) {
1783  // A returns attribute conflicts with any other returns attribute using
1784  // a different index.
1785  if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1786  S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1787  << I->args_begin()->getSourceIndex();
1788  if (I->args_size())
1789  S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1790  << Idx.getSourceIndex() << Ex->getSourceRange();
1791  return;
1792  }
1793  }
1794  }
1795  OwnershipArgs.push_back(Idx);
1796  }
1797 
1798  ParamIdx *Start = OwnershipArgs.data();
1799  unsigned Size = OwnershipArgs.size();
1800  llvm::array_pod_sort(Start, Start + Size);
1801  D->addAttr(::new (S.Context)
1802  OwnershipAttr(AL.getLoc(), S.Context, Module, Start, Size,
1804 }
1805 
1806 static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1807  // Check the attribute arguments.
1808  if (AL.getNumArgs() > 1) {
1809  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1810  return;
1811  }
1812 
1813  // gcc rejects
1814  // class c {
1815  // static int a __attribute__((weakref ("v2")));
1816  // static int b() __attribute__((weakref ("f3")));
1817  // };
1818  // and ignores the attributes of
1819  // void f(void) {
1820  // static int a __attribute__((weakref ("v2")));
1821  // }
1822  // we reject them
1823  const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1824  if (!Ctx->isFileContext()) {
1825  S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1826  << cast<NamedDecl>(D);
1827  return;
1828  }
1829 
1830  // The GCC manual says
1831  //
1832  // At present, a declaration to which `weakref' is attached can only
1833  // be `static'.
1834  //
1835  // It also says
1836  //
1837  // Without a TARGET,
1838  // given as an argument to `weakref' or to `alias', `weakref' is
1839  // equivalent to `weak'.
1840  //
1841  // gcc 4.4.1 will accept
1842  // int a7 __attribute__((weakref));
1843  // as
1844  // int a7 __attribute__((weak));
1845  // This looks like a bug in gcc. We reject that for now. We should revisit
1846  // it if this behaviour is actually used.
1847 
1848  // GCC rejects
1849  // static ((alias ("y"), weakref)).
1850  // Should we? How to check that weakref is before or after alias?
1851 
1852  // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1853  // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1854  // StringRef parameter it was given anyway.
1855  StringRef Str;
1856  if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1857  // GCC will accept anything as the argument of weakref. Should we
1858  // check for an existing decl?
1859  D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str,
1861 
1862  D->addAttr(::new (S.Context)
1863  WeakRefAttr(AL.getRange(), S.Context,
1865 }
1866 
1867 static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1868  StringRef Str;
1869  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1870  return;
1871 
1872  // Aliases should be on declarations, not definitions.
1873  const auto *FD = cast<FunctionDecl>(D);
1874  if (FD->isThisDeclarationADefinition()) {
1875  S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1876  return;
1877  }
1878 
1879  D->addAttr(::new (S.Context) IFuncAttr(AL.getRange(), S.Context, Str,
1881 }
1882 
1883 static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1884  StringRef Str;
1885  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1886  return;
1887 
1888  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1889  S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
1890  return;
1891  }
1892  if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1893  S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
1894  }
1895 
1896  // Aliases should be on declarations, not definitions.
1897  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1898  if (FD->isThisDeclarationADefinition()) {
1899  S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
1900  return;
1901  }
1902  } else {
1903  const auto *VD = cast<VarDecl>(D);
1904  if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1905  S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
1906  return;
1907  }
1908  }
1909 
1910  // Mark target used to prevent unneeded-internal-declaration warnings.
1911  if (!S.LangOpts.CPlusPlus) {
1912  // FIXME: demangle Str for C++, as the attribute refers to the mangled
1913  // linkage name, not the pre-mangled identifier.
1914  const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
1915  LookupResult LR(S, target, Sema::LookupOrdinaryName);
1917  for (NamedDecl *ND : LR)
1918  ND->markUsed(S.Context);
1919  }
1920 
1921  D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str,
1923 }
1924 
1925 static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1926  StringRef Model;
1927  SourceLocation LiteralLoc;
1928  // Check that it is a string.
1929  if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
1930  return;
1931 
1932  // Check that the value.
1933  if (Model != "global-dynamic" && Model != "local-dynamic"
1934  && Model != "initial-exec" && Model != "local-exec") {
1935  S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1936  return;
1937  }
1938 
1939  D->addAttr(::new (S.Context)
1940  TLSModelAttr(AL.getRange(), S.Context, Model,
1942 }
1943 
1944 static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1945  QualType ResultType = getFunctionOrMethodResultType(D);
1946  if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1947  D->addAttr(::new (S.Context) RestrictAttr(
1949  return;
1950  }
1951 
1952  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1954 }
1955 
1956 static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1957  FunctionDecl *FD = cast<FunctionDecl>(D);
1958 
1959  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
1960  if (MD->getParent()->isLambda()) {
1961  S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
1962  return;
1963  }
1964  }
1965 
1966  if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1967  return;
1968 
1970  for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
1971  if (!AL.isArgIdent(ArgNo)) {
1972  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1973  << AL << AANT_ArgumentIdentifier;
1974  return;
1975  }
1976 
1977  IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
1978  StringRef CPUName = CPUArg->Ident->getName().trim();
1979 
1981  S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
1982  << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
1983  return;
1984  }
1985 
1986  const TargetInfo &Target = S.Context.getTargetInfo();
1987  if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
1988  return Target.CPUSpecificManglingCharacter(CPUName) ==
1989  Target.CPUSpecificManglingCharacter(Cur->getName());
1990  })) {
1991  S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
1992  return;
1993  }
1994  CPUs.push_back(CPUArg->Ident);
1995  }
1996 
1997  FD->setIsMultiVersion(true);
1998  if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
1999  D->addAttr(::new (S.Context) CPUSpecificAttr(
2000  AL.getRange(), S.Context, CPUs.data(), CPUs.size(),
2002  else
2003  D->addAttr(::new (S.Context) CPUDispatchAttr(
2004  AL.getRange(), S.Context, CPUs.data(), CPUs.size(),
2006 }
2007 
2008 static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2009  if (S.LangOpts.CPlusPlus) {
2010  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
2011  << AL << AttributeLangSupport::Cpp;
2012  return;
2013  }
2014 
2015  if (CommonAttr *CA = S.mergeCommonAttr(D, AL))
2016  D->addAttr(CA);
2017 }
2018 
2019 static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2020  if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, AL))
2021  return;
2022 
2023  if (AL.isDeclspecAttribute()) {
2024  const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2025  const auto &Arch = Triple.getArch();
2026  if (Arch != llvm::Triple::x86 &&
2027  (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2028  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2029  << AL << Triple.getArchName();
2030  return;
2031  }
2032  }
2033 
2034  D->addAttr(::new (S.Context) NakedAttr(AL.getRange(), S.Context,
2036 }
2037 
2038 static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2039  if (hasDeclarator(D)) return;
2040 
2041  if (!isa<ObjCMethodDecl>(D)) {
2042  S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2043  << Attrs << ExpectedFunctionOrMethod;
2044  return;
2045  }
2046 
2047  D->addAttr(::new (S.Context) NoReturnAttr(
2048  Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
2049 }
2050 
2051 static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2052  if (!S.getLangOpts().CFProtectionBranch)
2053  S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2054  else
2055  handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2056 }
2057 
2058 bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2059  if (!checkAttributeNumArgs(*this, Attrs, 0)) {
2060  Attrs.setInvalid();
2061  return true;
2062  }
2063 
2064  return false;
2065 }
2066 
2067 bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
2068  // Check whether the attribute is valid on the current target.
2069  if (!AL.existsInTarget(Context.getTargetInfo())) {
2070  Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL;
2071  AL.setInvalid();
2072  return true;
2073  }
2074 
2075  return false;
2076 }
2077 
2078 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2079 
2080  // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2081  // because 'analyzer_noreturn' does not impact the type.
2082  if (!isFunctionOrMethodOrBlock(D)) {
2083  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2084  if (!VD || (!VD->getType()->isBlockPointerType() &&
2085  !VD->getType()->isFunctionPointerType())) {
2086  S.Diag(AL.getLoc(), AL.isCXX11Attribute()
2087  ? diag::err_attribute_wrong_decl_type
2088  : diag::warn_attribute_wrong_decl_type)
2090  return;
2091  }
2092  }
2093 
2094  D->addAttr(::new (S.Context)
2095  AnalyzerNoReturnAttr(AL.getRange(), S.Context,
2097 }
2098 
2099 // PS3 PPU-specific.
2100 static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2101  /*
2102  Returning a Vector Class in Registers
2103 
2104  According to the PPU ABI specifications, a class with a single member of
2105  vector type is returned in memory when used as the return value of a
2106  function.
2107  This results in inefficient code when implementing vector classes. To return
2108  the value in a single vector register, add the vecreturn attribute to the
2109  class definition. This attribute is also applicable to struct types.
2110 
2111  Example:
2112 
2113  struct Vector
2114  {
2115  __vector float xyzw;
2116  } __attribute__((vecreturn));
2117 
2118  Vector Add(Vector lhs, Vector rhs)
2119  {
2120  Vector result;
2121  result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2122  return result; // This will be returned in a register
2123  }
2124  */
2125  if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2126  S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2127  return;
2128  }
2129 
2130  const auto *R = cast<RecordDecl>(D);
2131  int count = 0;
2132 
2133  if (!isa<CXXRecordDecl>(R)) {
2134  S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2135  return;
2136  }
2137 
2138  if (!cast<CXXRecordDecl>(R)->isPOD()) {
2139  S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2140  return;
2141  }
2142 
2143  for (const auto *I : R->fields()) {
2144  if ((count == 1) || !I->getType()->isVectorType()) {
2145  S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2146  return;
2147  }
2148  count++;
2149  }
2150 
2151  D->addAttr(::new (S.Context) VecReturnAttr(
2153 }
2154 
2155 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2156  const ParsedAttr &AL) {
2157  if (isa<ParmVarDecl>(D)) {
2158  // [[carries_dependency]] can only be applied to a parameter if it is a
2159  // parameter of a function declaration or lambda.
2161  S.Diag(AL.getLoc(),
2162  diag::err_carries_dependency_param_not_function_decl);
2163  return;
2164  }
2165  }
2166 
2167  D->addAttr(::new (S.Context) CarriesDependencyAttr(
2168  AL.getRange(), S.Context,
2170 }
2171 
2172 static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2173  bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2174 
2175  // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2176  // about using it as an extension.
2177  if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2178  S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2179 
2180  D->addAttr(::new (S.Context) UnusedAttr(
2182 }
2183 
2184 static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2185  uint32_t priority = ConstructorAttr::DefaultPriority;
2186  if (AL.getNumArgs() &&
2187  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2188  return;
2189 
2190  D->addAttr(::new (S.Context)
2191  ConstructorAttr(AL.getRange(), S.Context, priority,
2193 }
2194 
2195 static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2196  uint32_t priority = DestructorAttr::DefaultPriority;
2197  if (AL.getNumArgs() &&
2198  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2199  return;
2200 
2201  D->addAttr(::new (S.Context)
2202  DestructorAttr(AL.getRange(), S.Context, priority,
2204 }
2205 
2206 template <typename AttrTy>
2207 static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2208  // Handle the case where the attribute has a text message.
2209  StringRef Str;
2210  if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2211  return;
2212 
2213  D->addAttr(::new (S.Context) AttrTy(AL.getRange(), S.Context, Str,
2215 }
2216 
2217 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2218  const ParsedAttr &AL) {
2219  if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2220  S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2221  << AL << AL.getRange();
2222  return;
2223  }
2224 
2225  D->addAttr(::new (S.Context)
2226  ObjCExplicitProtocolImplAttr(AL.getRange(), S.Context,
2228 }
2229 
2230 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2231  IdentifierInfo *Platform,
2232  VersionTuple Introduced,
2233  VersionTuple Deprecated,
2234  VersionTuple Obsoleted) {
2235  StringRef PlatformName
2236  = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2237  if (PlatformName.empty())
2238  PlatformName = Platform->getName();
2239 
2240  // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2241  // of these steps are needed).
2242  if (!Introduced.empty() && !Deprecated.empty() &&
2243  !(Introduced <= Deprecated)) {
2244  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2245  << 1 << PlatformName << Deprecated.getAsString()
2246  << 0 << Introduced.getAsString();
2247  return true;
2248  }
2249 
2250  if (!Introduced.empty() && !Obsoleted.empty() &&
2251  !(Introduced <= Obsoleted)) {
2252  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2253  << 2 << PlatformName << Obsoleted.getAsString()
2254  << 0 << Introduced.getAsString();
2255  return true;
2256  }
2257 
2258  if (!Deprecated.empty() && !Obsoleted.empty() &&
2259  !(Deprecated <= Obsoleted)) {
2260  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2261  << 2 << PlatformName << Obsoleted.getAsString()
2262  << 1 << Deprecated.getAsString();
2263  return true;
2264  }
2265 
2266  return false;
2267 }
2268 
2269 /// Check whether the two versions match.
2270 ///
2271 /// If either version tuple is empty, then they are assumed to match. If
2272 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2273 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2274  bool BeforeIsOkay) {
2275  if (X.empty() || Y.empty())
2276  return true;
2277 
2278  if (X == Y)
2279  return true;
2280 
2281  if (BeforeIsOkay && X < Y)
2282  return true;
2283 
2284  return false;
2285 }
2286 
2287 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2288  IdentifierInfo *Platform,
2289  bool Implicit,
2290  VersionTuple Introduced,
2291  VersionTuple Deprecated,
2292  VersionTuple Obsoleted,
2293  bool IsUnavailable,
2294  StringRef Message,
2295  bool IsStrict,
2296  StringRef Replacement,
2297  AvailabilityMergeKind AMK,
2298  unsigned AttrSpellingListIndex) {
2299  VersionTuple MergedIntroduced = Introduced;
2300  VersionTuple MergedDeprecated = Deprecated;
2301  VersionTuple MergedObsoleted = Obsoleted;
2302  bool FoundAny = false;
2303  bool OverrideOrImpl = false;
2304  switch (AMK) {
2305  case AMK_None:
2306  case AMK_Redeclaration:
2307  OverrideOrImpl = false;
2308  break;
2309 
2310  case AMK_Override:
2311  case AMK_ProtocolImplementation:
2312  OverrideOrImpl = true;
2313  break;
2314  }
2315 
2316  if (D->hasAttrs()) {
2317  AttrVec &Attrs = D->getAttrs();
2318  for (unsigned i = 0, e = Attrs.size(); i != e;) {
2319  const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2320  if (!OldAA) {
2321  ++i;
2322  continue;
2323  }
2324 
2325  IdentifierInfo *OldPlatform = OldAA->getPlatform();
2326  if (OldPlatform != Platform) {
2327  ++i;
2328  continue;
2329  }
2330 
2331  // If there is an existing availability attribute for this platform that
2332  // is explicit and the new one is implicit use the explicit one and
2333  // discard the new implicit attribute.
2334  if (!OldAA->isImplicit() && Implicit) {
2335  return nullptr;
2336  }
2337 
2338  // If there is an existing attribute for this platform that is implicit
2339  // and the new attribute is explicit then erase the old one and
2340  // continue processing the attributes.
2341  if (!Implicit && OldAA->isImplicit()) {
2342  Attrs.erase(Attrs.begin() + i);
2343  --e;
2344  continue;
2345  }
2346 
2347  FoundAny = true;
2348  VersionTuple OldIntroduced = OldAA->getIntroduced();
2349  VersionTuple OldDeprecated = OldAA->getDeprecated();
2350  VersionTuple OldObsoleted = OldAA->getObsoleted();
2351  bool OldIsUnavailable = OldAA->getUnavailable();
2352 
2353  if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2354  !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2355  !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2356  !(OldIsUnavailable == IsUnavailable ||
2357  (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2358  if (OverrideOrImpl) {
2359  int Which = -1;
2360  VersionTuple FirstVersion;
2361  VersionTuple SecondVersion;
2362  if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2363  Which = 0;
2364  FirstVersion = OldIntroduced;
2365  SecondVersion = Introduced;
2366  } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2367  Which = 1;
2368  FirstVersion = Deprecated;
2369  SecondVersion = OldDeprecated;
2370  } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2371  Which = 2;
2372  FirstVersion = Obsoleted;
2373  SecondVersion = OldObsoleted;
2374  }
2375 
2376  if (Which == -1) {
2377  Diag(OldAA->getLocation(),
2378  diag::warn_mismatched_availability_override_unavail)
2379  << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2380  << (AMK == AMK_Override);
2381  } else {
2382  Diag(OldAA->getLocation(),
2383  diag::warn_mismatched_availability_override)
2384  << Which
2385  << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2386  << FirstVersion.getAsString() << SecondVersion.getAsString()
2387  << (AMK == AMK_Override);
2388  }
2389  if (AMK == AMK_Override)
2390  Diag(Range.getBegin(), diag::note_overridden_method);
2391  else
2392  Diag(Range.getBegin(), diag::note_protocol_method);
2393  } else {
2394  Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2395  Diag(Range.getBegin(), diag::note_previous_attribute);
2396  }
2397 
2398  Attrs.erase(Attrs.begin() + i);
2399  --e;
2400  continue;
2401  }
2402 
2403  VersionTuple MergedIntroduced2 = MergedIntroduced;
2404  VersionTuple MergedDeprecated2 = MergedDeprecated;
2405  VersionTuple MergedObsoleted2 = MergedObsoleted;
2406 
2407  if (MergedIntroduced2.empty())
2408  MergedIntroduced2 = OldIntroduced;
2409  if (MergedDeprecated2.empty())
2410  MergedDeprecated2 = OldDeprecated;
2411  if (MergedObsoleted2.empty())
2412  MergedObsoleted2 = OldObsoleted;
2413 
2414  if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2415  MergedIntroduced2, MergedDeprecated2,
2416  MergedObsoleted2)) {
2417  Attrs.erase(Attrs.begin() + i);
2418  --e;
2419  continue;
2420  }
2421 
2422  MergedIntroduced = MergedIntroduced2;
2423  MergedDeprecated = MergedDeprecated2;
2424  MergedObsoleted = MergedObsoleted2;
2425  ++i;
2426  }
2427  }
2428 
2429  if (FoundAny &&
2430  MergedIntroduced == Introduced &&
2431  MergedDeprecated == Deprecated &&
2432  MergedObsoleted == Obsoleted)
2433  return nullptr;
2434 
2435  // Only create a new attribute if !OverrideOrImpl, but we want to do
2436  // the checking.
2437  if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2438  MergedDeprecated, MergedObsoleted) &&
2439  !OverrideOrImpl) {
2440  auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
2441  Introduced, Deprecated,
2442  Obsoleted, IsUnavailable, Message,
2443  IsStrict, Replacement,
2444  AttrSpellingListIndex);
2445  Avail->setImplicit(Implicit);
2446  return Avail;
2447  }
2448  return nullptr;
2449 }
2450 
2451 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2452  if (!checkAttributeNumArgs(S, AL, 1))
2453  return;
2454  IdentifierLoc *Platform = AL.getArgAsIdent(0);
2455  unsigned Index = AL.getAttributeSpellingListIndex();
2456 
2457  IdentifierInfo *II = Platform->Ident;
2458  if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2459  S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2460  << Platform->Ident;
2461 
2462  auto *ND = dyn_cast<NamedDecl>(D);
2463  if (!ND) // We warned about this already, so just return.
2464  return;
2465 
2469  bool IsUnavailable = AL.getUnavailableLoc().isValid();
2470  bool IsStrict = AL.getStrictLoc().isValid();
2471  StringRef Str;
2472  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2473  Str = SE->getString();
2474  StringRef Replacement;
2475  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2476  Replacement = SE->getString();
2477 
2478  if (II->isStr("swift")) {
2479  if (Introduced.isValid() || Obsoleted.isValid() ||
2480  (!IsUnavailable && !Deprecated.isValid())) {
2481  S.Diag(AL.getLoc(),
2482  diag::warn_availability_swift_unavailable_deprecated_only);
2483  return;
2484  }
2485  }
2486 
2487  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, AL.getRange(), II,
2488  false/*Implicit*/,
2489  Introduced.Version,
2490  Deprecated.Version,
2491  Obsoleted.Version,
2492  IsUnavailable, Str,
2493  IsStrict, Replacement,
2495  Index);
2496  if (NewAttr)
2497  D->addAttr(NewAttr);
2498 
2499  // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2500  // matches before the start of the watchOS platform.
2501  if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2502  IdentifierInfo *NewII = nullptr;
2503  if (II->getName() == "ios")
2504  NewII = &S.Context.Idents.get("watchos");
2505  else if (II->getName() == "ios_app_extension")
2506  NewII = &S.Context.Idents.get("watchos_app_extension");
2507 
2508  if (NewII) {
2509  auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2510  if (Version.empty())
2511  return Version;
2512  auto Major = Version.getMajor();
2513  auto NewMajor = Major >= 9 ? Major - 7 : 0;
2514  if (NewMajor >= 2) {
2515  if (Version.getMinor().hasValue()) {
2516  if (Version.getSubminor().hasValue())
2517  return VersionTuple(NewMajor, Version.getMinor().getValue(),
2518  Version.getSubminor().getValue());
2519  else
2520  return VersionTuple(NewMajor, Version.getMinor().getValue());
2521  }
2522  }
2523 
2524  return VersionTuple(2, 0);
2525  };
2526 
2527  auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2528  auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2529  auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2530 
2531  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2532  AL.getRange(),
2533  NewII,
2534  true/*Implicit*/,
2535  NewIntroduced,
2536  NewDeprecated,
2537  NewObsoleted,
2538  IsUnavailable, Str,
2539  IsStrict,
2540  Replacement,
2542  Index);
2543  if (NewAttr)
2544  D->addAttr(NewAttr);
2545  }
2546  } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2547  // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2548  // matches before the start of the tvOS platform.
2549  IdentifierInfo *NewII = nullptr;
2550  if (II->getName() == "ios")
2551  NewII = &S.Context.Idents.get("tvos");
2552  else if (II->getName() == "ios_app_extension")
2553  NewII = &S.Context.Idents.get("tvos_app_extension");
2554 
2555  if (NewII) {
2556  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2557  AL.getRange(),
2558  NewII,
2559  true/*Implicit*/,
2560  Introduced.Version,
2561  Deprecated.Version,
2562  Obsoleted.Version,
2563  IsUnavailable, Str,
2564  IsStrict,
2565  Replacement,
2567  Index);
2568  if (NewAttr)
2569  D->addAttr(NewAttr);
2570  }
2571  }
2572 }
2573 
2574 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2575  const ParsedAttr &AL) {
2576  if (!checkAttributeAtLeastNumArgs(S, AL, 1))
2577  return;
2578  assert(checkAttributeAtMostNumArgs(S, AL, 3) &&
2579  "Invalid number of arguments in an external_source_symbol attribute");
2580 
2581  StringRef Language;
2582  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2583  Language = SE->getString();
2584  StringRef DefinedIn;
2585  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2586  DefinedIn = SE->getString();
2587  bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2588 
2589  D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2590  AL.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2592 }
2593 
2594 template <class T>
2595 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2596  typename T::VisibilityType value,
2597  unsigned attrSpellingListIndex) {
2598  T *existingAttr = D->getAttr<T>();
2599  if (existingAttr) {
2600  typename T::VisibilityType existingValue = existingAttr->getVisibility();
2601  if (existingValue == value)
2602  return nullptr;
2603  S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2604  S.Diag(range.getBegin(), diag::note_previous_attribute);
2605  D->dropAttr<T>();
2606  }
2607  return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2608 }
2609 
2610 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2611  VisibilityAttr::VisibilityType Vis,
2612  unsigned AttrSpellingListIndex) {
2613  return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2614  AttrSpellingListIndex);
2615 }
2616 
2617 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2618  TypeVisibilityAttr::VisibilityType Vis,
2619  unsigned AttrSpellingListIndex) {
2620  return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2621  AttrSpellingListIndex);
2622 }
2623 
2624 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2625  bool isTypeVisibility) {
2626  // Visibility attributes don't mean anything on a typedef.
2627  if (isa<TypedefNameDecl>(D)) {
2628  S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2629  return;
2630  }
2631 
2632  // 'type_visibility' can only go on a type or namespace.
2633  if (isTypeVisibility &&
2634  !(isa<TagDecl>(D) ||
2635  isa<ObjCInterfaceDecl>(D) ||
2636  isa<NamespaceDecl>(D))) {
2637  S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2638  << AL << ExpectedTypeOrNamespace;
2639  return;
2640  }
2641 
2642  // Check that the argument is a string literal.
2643  StringRef TypeStr;
2644  SourceLocation LiteralLoc;
2645  if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2646  return;
2647 
2648  VisibilityAttr::VisibilityType type;
2649  if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2650  S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2651  << TypeStr;
2652  return;
2653  }
2654 
2655  // Complain about attempts to use protected visibility on targets
2656  // (like Darwin) that don't support it.
2657  if (type == VisibilityAttr::Protected &&
2659  S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2660  type = VisibilityAttr::Default;
2661  }
2662 
2663  unsigned Index = AL.getAttributeSpellingListIndex();
2664  Attr *newAttr;
2665  if (isTypeVisibility) {
2666  newAttr = S.mergeTypeVisibilityAttr(D, AL.getRange(),
2667  (TypeVisibilityAttr::VisibilityType) type,
2668  Index);
2669  } else {
2670  newAttr = S.mergeVisibilityAttr(D, AL.getRange(), type, Index);
2671  }
2672  if (newAttr)
2673  D->addAttr(newAttr);
2674 }
2675 
2676 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2677  const auto *M = cast<ObjCMethodDecl>(D);
2678  if (!AL.isArgIdent(0)) {
2679  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2680  << AL << 1 << AANT_ArgumentIdentifier;
2681  return;
2682  }
2683 
2684  IdentifierLoc *IL = AL.getArgAsIdent(0);
2685  ObjCMethodFamilyAttr::FamilyKind F;
2686  if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2687  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2688  return;
2689  }
2690 
2691  if (F == ObjCMethodFamilyAttr::OMF_init &&
2692  !M->getReturnType()->isObjCObjectPointerType()) {
2693  S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2694  << M->getReturnType();
2695  // Ignore the attribute.
2696  return;
2697  }
2698 
2699  D->addAttr(new (S.Context) ObjCMethodFamilyAttr(
2700  AL.getRange(), S.Context, F, AL.getAttributeSpellingListIndex()));
2701 }
2702 
2703 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2704  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2705  QualType T = TD->getUnderlyingType();
2706  if (!T->isCARCBridgableType()) {
2707  S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2708  return;
2709  }
2710  }
2711  else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2712  QualType T = PD->getType();
2713  if (!T->isCARCBridgableType()) {
2714  S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2715  return;
2716  }
2717  }
2718  else {
2719  // It is okay to include this attribute on properties, e.g.:
2720  //
2721  // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2722  //
2723  // In this case it follows tradition and suppresses an error in the above
2724  // case.
2725  S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2726  }
2727  D->addAttr(::new (S.Context)
2728  ObjCNSObjectAttr(AL.getRange(), S.Context,
2730 }
2731 
2732 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
2733  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2734  QualType T = TD->getUnderlyingType();
2735  if (!T->isObjCObjectPointerType()) {
2736  S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2737  return;
2738  }
2739  } else {
2740  S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2741  return;
2742  }
2743  D->addAttr(::new (S.Context)
2744  ObjCIndependentClassAttr(AL.getRange(), S.Context,
2746 }
2747 
2748 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2749  if (!AL.isArgIdent(0)) {
2750  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2751  << AL << 1 << AANT_ArgumentIdentifier;
2752  return;
2753  }
2754 
2755  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
2756  BlocksAttr::BlockType type;
2757  if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2758  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
2759  return;
2760  }
2761 
2762  D->addAttr(::new (S.Context)
2763  BlocksAttr(AL.getRange(), S.Context, type,
2765 }
2766 
2767 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2768  unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2769  if (AL.getNumArgs() > 0) {
2770  Expr *E = AL.getArgAsExpr(0);
2771  llvm::APSInt Idx(32);
2772  if (E->isTypeDependent() || E->isValueDependent() ||
2773  !E->isIntegerConstantExpr(Idx, S.Context)) {
2774  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2775  << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2776  return;
2777  }
2778 
2779  if (Idx.isSigned() && Idx.isNegative()) {
2780  S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2781  << E->getSourceRange();
2782  return;
2783  }
2784 
2785  sentinel = Idx.getZExtValue();
2786  }
2787 
2788  unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2789  if (AL.getNumArgs() > 1) {
2790  Expr *E = AL.getArgAsExpr(1);
2791  llvm::APSInt Idx(32);
2792  if (E->isTypeDependent() || E->isValueDependent() ||
2793  !E->isIntegerConstantExpr(Idx, S.Context)) {
2794  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2795  << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2796  return;
2797  }
2798  nullPos = Idx.getZExtValue();
2799 
2800  if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2801  // FIXME: This error message could be improved, it would be nice
2802  // to say what the bounds actually are.
2803  S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2804  << E->getSourceRange();
2805  return;
2806  }
2807  }
2808 
2809  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2810  const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2811  if (isa<FunctionNoProtoType>(FT)) {
2812  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2813  return;
2814  }
2815 
2816  if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2817  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2818  return;
2819  }
2820  } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2821  if (!MD->isVariadic()) {
2822  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2823  return;
2824  }
2825  } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2826  if (!BD->isVariadic()) {
2827  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2828  return;
2829  }
2830  } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2831  QualType Ty = V->getType();
2832  if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2833  const FunctionType *FT = Ty->isFunctionPointerType()
2834  ? D->getFunctionType()
2835  : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2836  if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2837  int m = Ty->isFunctionPointerType() ? 0 : 1;
2838  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2839  return;
2840  }
2841  } else {
2842  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2844  return;
2845  }
2846  } else {
2847  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2849  return;
2850  }
2851  D->addAttr(::new (S.Context)
2852  SentinelAttr(AL.getRange(), S.Context, sentinel, nullPos,
2854 }
2855 
2856 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2857  if (D->getFunctionType() &&
2859  S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2860  return;
2861  }
2862  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2863  if (MD->getReturnType()->isVoidType()) {
2864  S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2865  return;
2866  }
2867 
2868  // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2869  // about using it as an extension.
2870  if (!S.getLangOpts().CPlusPlus17 && AL.isCXX11Attribute() &&
2871  !AL.getScopeName())
2872  S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2873 
2874  D->addAttr(::new (S.Context)
2875  WarnUnusedResultAttr(AL.getRange(), S.Context,
2877 }
2878 
2879 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2880  // weak_import only applies to variable & function declarations.
2881  bool isDef = false;
2882  if (!D->canBeWeakImported(isDef)) {
2883  if (isDef)
2884  S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2885  << "weak_import";
2886  else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2887  (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2888  (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2889  // Nothing to warn about here.
2890  } else
2891  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2892  << AL << ExpectedVariableOrFunction;
2893 
2894  return;
2895  }
2896 
2897  D->addAttr(::new (S.Context)
2898  WeakImportAttr(AL.getRange(), S.Context,
2900 }
2901 
2902 // Handles reqd_work_group_size and work_group_size_hint.
2903 template <typename WorkGroupAttr>
2904 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2905  uint32_t WGSize[3];
2906  for (unsigned i = 0; i < 3; ++i) {
2907  const Expr *E = AL.getArgAsExpr(i);
2908  if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
2909  /*StrictlyUnsigned=*/true))
2910  return;
2911  if (WGSize[i] == 0) {
2912  S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2913  << AL << E->getSourceRange();
2914  return;
2915  }
2916  }
2917 
2918  WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2919  if (Existing && !(Existing->getXDim() == WGSize[0] &&
2920  Existing->getYDim() == WGSize[1] &&
2921  Existing->getZDim() == WGSize[2]))
2922  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2923 
2924  D->addAttr(::new (S.Context) WorkGroupAttr(AL.getRange(), S.Context,
2925  WGSize[0], WGSize[1], WGSize[2],
2927 }
2928 
2929 // Handles intel_reqd_sub_group_size.
2930 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2931  uint32_t SGSize;
2932  const Expr *E = AL.getArgAsExpr(0);
2933  if (!checkUInt32Argument(S, AL, E, SGSize))
2934  return;
2935  if (SGSize == 0) {
2936  S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2937  << AL << E->getSourceRange();
2938  return;
2939  }
2940 
2941  OpenCLIntelReqdSubGroupSizeAttr *Existing =
2942  D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2943  if (Existing && Existing->getSubGroupSize() != SGSize)
2944  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2945 
2946  D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr(
2947  AL.getRange(), S.Context, SGSize,
2949 }
2950 
2951 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
2952  if (!AL.hasParsedType()) {
2953  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2954  return;
2955  }
2956 
2957  TypeSourceInfo *ParmTSI = nullptr;
2958  QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
2959  assert(ParmTSI && "no type source info for attribute argument");
2960 
2961  if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2962  (ParmType->isBooleanType() ||
2963  !ParmType->isIntegralType(S.getASTContext()))) {
2964  S.Diag(AL.getLoc(), diag::err_attribute_argument_vec_type_hint)
2965  << ParmType;
2966  return;
2967  }
2968 
2969  if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2970  if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2971  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2972  return;
2973  }
2974  }
2975 
2976  D->addAttr(::new (S.Context) VecTypeHintAttr(AL.getLoc(), S.Context,
2977  ParmTSI,
2979 }
2980 
2981 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2982  StringRef Name,
2983  unsigned AttrSpellingListIndex) {
2984  // Explicit or partial specializations do not inherit
2985  // the section attribute from the primary template.
2986  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2987  if (AttrSpellingListIndex == SectionAttr::Declspec_allocate &&
2989  return nullptr;
2990  }
2991  if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2992  if (ExistingAttr->getName() == Name)
2993  return nullptr;
2994  Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2995  << 1 /*section*/;
2996  Diag(Range.getBegin(), diag::note_previous_attribute);
2997  return nullptr;
2998  }
2999  return ::new (Context) SectionAttr(Range, Context, Name,
3000  AttrSpellingListIndex);
3001 }
3002 
3003 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
3004  std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
3005  if (!Error.empty()) {
3006  Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
3007  << 1 /*'section'*/;
3008  return false;
3009  }
3010  return true;
3011 }
3012 
3013 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3014  // Make sure that there is a string literal as the sections's single
3015  // argument.
3016  StringRef Str;
3017  SourceLocation LiteralLoc;
3018  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3019  return;
3020 
3021  if (!S.checkSectionName(LiteralLoc, Str))
3022  return;
3023 
3024  // If the target wants to validate the section specifier, make it happen.
3025  std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
3026  if (!Error.empty()) {
3027  S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3028  << Error;
3029  return;
3030  }
3031 
3032  unsigned Index = AL.getAttributeSpellingListIndex();
3033  SectionAttr *NewAttr = S.mergeSectionAttr(D, AL.getRange(), Str, Index);
3034  if (NewAttr)
3035  D->addAttr(NewAttr);
3036 }
3037 
3038 static bool checkCodeSegName(Sema&S, SourceLocation LiteralLoc, StringRef CodeSegName) {
3039  std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(CodeSegName);
3040  if (!Error.empty()) {
3041  S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
3042  << 0 /*'code-seg'*/;
3043  return false;
3044  }
3045  return true;
3046 }
3047 
3048 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, SourceRange Range,
3049  StringRef Name,
3050  unsigned AttrSpellingListIndex) {
3051  // Explicit or partial specializations do not inherit
3052  // the code_seg attribute from the primary template.
3053  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3055  return nullptr;
3056  }
3057  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3058  if (ExistingAttr->getName() == Name)
3059  return nullptr;
3060  Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3061  << 0 /*codeseg*/;
3062  Diag(Range.getBegin(), diag::note_previous_attribute);
3063  return nullptr;
3064  }
3065  return ::new (Context) CodeSegAttr(Range, Context, Name,
3066  AttrSpellingListIndex);
3067 }
3068 
3069 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3070  StringRef Str;
3071  SourceLocation LiteralLoc;
3072  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3073  return;
3074  if (!checkCodeSegName(S, LiteralLoc, Str))
3075  return;
3076  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3077  if (!ExistingAttr->isImplicit()) {
3078  S.Diag(AL.getLoc(),
3079  ExistingAttr->getName() == Str
3080  ? diag::warn_duplicate_codeseg_attribute
3081  : diag::err_conflicting_codeseg_attribute);
3082  return;
3083  }
3084  D->dropAttr<CodeSegAttr>();
3085  }
3086  if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL.getRange(), Str,
3088  D->addAttr(CSA);
3089 }
3090 
3091 // Check for things we'd like to warn about. Multiversioning issues are
3092 // handled later in the process, once we know how many exist.
3093 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3094  enum FirstParam { Unsupported, Duplicate };
3095  enum SecondParam { None, Architecture };
3096  for (auto Str : {"tune=", "fpmath="})
3097  if (AttrStr.find(Str) != StringRef::npos)
3098  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3099  << Unsupported << None << Str;
3100 
3101  TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3102 
3103  if (!ParsedAttrs.Architecture.empty() &&
3104  !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3105  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3106  << Unsupported << Architecture << ParsedAttrs.Architecture;
3107 
3108  if (ParsedAttrs.DuplicateArchitecture)
3109  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3110  << Duplicate << None << "arch=";
3111 
3112  for (const auto &Feature : ParsedAttrs.Features) {
3113  auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3114  if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3115  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3116  << Unsupported << None << CurFeature;
3117  }
3118 
3119  return false;
3120 }
3121 
3122 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3123  StringRef Str;
3124  SourceLocation LiteralLoc;
3125  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3126  S.checkTargetAttr(LiteralLoc, Str))
3127  return;
3128 
3129  unsigned Index = AL.getAttributeSpellingListIndex();
3130  TargetAttr *NewAttr =
3131  ::new (S.Context) TargetAttr(AL.getRange(), S.Context, Str, Index);
3132  D->addAttr(NewAttr);
3133 }
3134 
3135 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3136  Expr *E = AL.getArgAsExpr(0);
3137  uint32_t VecWidth;
3138  if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3139  AL.setInvalid();
3140  return;
3141  }
3142 
3143  MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3144  if (Existing && Existing->getVectorWidth() != VecWidth) {
3145  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3146  return;
3147  }
3148 
3149  D->addAttr(::new (S.Context)
3150  MinVectorWidthAttr(AL.getRange(), S.Context, VecWidth,
3152 }
3153 
3154 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3155  Expr *E = AL.getArgAsExpr(0);
3156  SourceLocation Loc = E->getExprLoc();
3157  FunctionDecl *FD = nullptr;
3159 
3160  // gcc only allows for simple identifiers. Since we support more than gcc, we
3161  // will warn the user.
3162  if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3163  if (DRE->hasQualifier())
3164  S.Diag(Loc, diag::warn_cleanup_ext);
3165  FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3166  NI = DRE->getNameInfo();
3167  if (!FD) {
3168  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3169  << NI.getName();
3170  return;
3171  }
3172  } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3173  if (ULE->hasExplicitTemplateArgs())
3174  S.Diag(Loc, diag::warn_cleanup_ext);
3176  NI = ULE->getNameInfo();
3177  if (!FD) {
3178  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3179  << NI.getName();
3180  if (ULE->getType() == S.Context.OverloadTy)
3182  return;
3183  }
3184  } else {
3185  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3186  return;
3187  }
3188 
3189  if (FD->getNumParams() != 1) {
3190  S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3191  << NI.getName();
3192  return;
3193  }
3194 
3195  // We're currently more strict than GCC about what function types we accept.
3196  // If this ever proves to be a problem it should be easy to fix.
3197  QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3198  QualType ParamTy = FD->getParamDecl(0)->getType();
3200  ParamTy, Ty) != Sema::Compatible) {
3201  S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3202  << NI.getName() << ParamTy << Ty;
3203  return;
3204  }
3205 
3206  D->addAttr(::new (S.Context)
3207  CleanupAttr(AL.getRange(), S.Context, FD,
3209 }
3210 
3211 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3212  const ParsedAttr &AL) {
3213  if (!AL.isArgIdent(0)) {
3214  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3215  << AL << 0 << AANT_ArgumentIdentifier;
3216  return;
3217  }
3218 
3219  EnumExtensibilityAttr::Kind ExtensibilityKind;
3220  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3221  if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3222  ExtensibilityKind)) {
3223  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3224  return;
3225  }
3226 
3227  D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3228  AL.getRange(), S.Context, ExtensibilityKind,
3230 }
3231 
3232 /// Handle __attribute__((format_arg((idx)))) attribute based on
3233 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3234 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3235  Expr *IdxExpr = AL.getArgAsExpr(0);
3236  ParamIdx Idx;
3237  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3238  return;
3239 
3240  // Make sure the format string is really a string.
3242 
3243  bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3244  if (NotNSStringTy &&
3245  !isCFStringType(Ty, S.Context) &&
3246  (!Ty->isPointerType() ||
3247  !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3248  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3249  << "a string type" << IdxExpr->getSourceRange()
3251  return;
3252  }
3254  if (!isNSStringType(Ty, S.Context) &&
3255  !isCFStringType(Ty, S.Context) &&
3256  (!Ty->isPointerType() ||
3257  !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3258  S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3259  << (NotNSStringTy ? "string type" : "NSString")
3260  << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3261  return;
3262  }
3263 
3264  D->addAttr(::new (S.Context) FormatArgAttr(
3265  AL.getRange(), S.Context, Idx, AL.getAttributeSpellingListIndex()));
3266 }
3267 
3268 enum FormatAttrKind {
3269  CFStringFormat,
3270  NSStringFormat,
3271  StrftimeFormat,
3272  SupportedFormat,
3273  IgnoredFormat,
3274  InvalidFormat
3275 };
3276 
3277 /// getFormatAttrKind - Map from format attribute names to supported format
3278 /// types.
3279 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3280  return llvm::StringSwitch<FormatAttrKind>(Format)
3281  // Check for formats that get handled specially.
3282  .Case("NSString", NSStringFormat)
3283  .Case("CFString", CFStringFormat)
3284  .Case("strftime", StrftimeFormat)
3285 
3286  // Otherwise, check for supported formats.
3287  .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3288  .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3289  .Case("kprintf", SupportedFormat) // OpenBSD.
3290  .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3291  .Case("os_trace", SupportedFormat)
3292  .Case("os_log", SupportedFormat)
3293 
3294  .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3295  .Default(InvalidFormat);
3296 }
3297 
3298 /// Handle __attribute__((init_priority(priority))) attributes based on
3299 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3300 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3301  if (!S.getLangOpts().CPlusPlus) {
3302  S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3303  return;
3304  }
3305 
3306  if (S.getCurFunctionOrMethodDecl()) {
3307  S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3308  AL.setInvalid();
3309  return;
3310  }
3311  QualType T = cast<VarDecl>(D)->getType();
3312  if (S.Context.getAsArrayType(T))
3313  T = S.Context.getBaseElementType(T);
3314  if (!T->getAs<RecordType>()) {
3315  S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3316  AL.setInvalid();
3317  return;
3318  }
3319 
3320  Expr *E = AL.getArgAsExpr(0);
3321  uint32_t prioritynum;
3322  if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3323  AL.setInvalid();
3324  return;
3325  }
3326 
3327  if (prioritynum < 101 || prioritynum > 65535) {
3328  S.Diag(AL.getLoc(), diag::err_attribute_argument_outof_range)
3329  << E->getSourceRange() << AL << 101 << 65535;
3330  AL.setInvalid();
3331  return;
3332  }
3333  D->addAttr(::new (S.Context)
3334  InitPriorityAttr(AL.getRange(), S.Context, prioritynum,
3336 }
3337 
3338 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3339  IdentifierInfo *Format, int FormatIdx,
3340  int FirstArg,
3341  unsigned AttrSpellingListIndex) {
3342  // Check whether we already have an equivalent format attribute.
3343  for (auto *F : D->specific_attrs<FormatAttr>()) {
3344  if (F->getType() == Format &&
3345  F->getFormatIdx() == FormatIdx &&
3346  F->getFirstArg() == FirstArg) {
3347  // If we don't have a valid location for this attribute, adopt the
3348  // location.
3349  if (F->getLocation().isInvalid())
3350  F->setRange(Range);
3351  return nullptr;
3352  }
3353  }
3354 
3355  return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3356  FirstArg, AttrSpellingListIndex);
3357 }
3358 
3359 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3360 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3361 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3362  if (!AL.isArgIdent(0)) {
3363  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3364  << AL << 1 << AANT_ArgumentIdentifier;
3365  return;
3366  }
3367 
3368  // In C++ the implicit 'this' function parameter also counts, and they are
3369  // counted from one.
3370  bool HasImplicitThisParam = isInstanceMethod(D);
3371  unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3372 
3373  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3374  StringRef Format = II->getName();
3375 
3376  if (normalizeName(Format)) {
3377  // If we've modified the string name, we need a new identifier for it.
3378  II = &S.Context.Idents.get(Format);
3379  }
3380 
3381  // Check for supported formats.
3382  FormatAttrKind Kind = getFormatAttrKind(Format);
3383 
3384  if (Kind == IgnoredFormat)
3385  return;
3386 
3387  if (Kind == InvalidFormat) {
3388  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3389  << AL << II->getName();
3390  return;
3391  }
3392 
3393  // checks for the 2nd argument
3394  Expr *IdxExpr = AL.getArgAsExpr(1);
3395  uint32_t Idx;
3396  if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3397  return;
3398 
3399  if (Idx < 1 || Idx > NumArgs) {
3400  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3401  << AL << 2 << IdxExpr->getSourceRange();
3402  return;
3403  }
3404 
3405  // FIXME: Do we need to bounds check?
3406  unsigned ArgIdx = Idx - 1;
3407 
3408  if (HasImplicitThisParam) {
3409  if (ArgIdx == 0) {
3410  S.Diag(AL.getLoc(),
3411  diag::err_format_attribute_implicit_this_format_string)
3412  << IdxExpr->getSourceRange();
3413  return;
3414  }
3415  ArgIdx--;
3416  }
3417 
3418  // make sure the format string is really a string
3419  QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3420 
3421  if (Kind == CFStringFormat) {
3422  if (!isCFStringType(Ty, S.Context)) {
3423  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3424  << "a CFString" << IdxExpr->getSourceRange()
3425  << getFunctionOrMethodParamRange(D, ArgIdx);
3426  return;
3427  }
3428  } else if (Kind == NSStringFormat) {
3429  // FIXME: do we need to check if the type is NSString*? What are the
3430  // semantics?
3431  if (!isNSStringType(Ty, S.Context)) {
3432  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3433  << "an NSString" << IdxExpr->getSourceRange()
3434  << getFunctionOrMethodParamRange(D, ArgIdx);
3435  return;
3436  }
3437  } else if (!Ty->isPointerType() ||
3438  !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3439  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3440  << "a string type" << IdxExpr->getSourceRange()
3441  << getFunctionOrMethodParamRange(D, ArgIdx);
3442  return;
3443  }
3444 
3445  // check the 3rd argument
3446  Expr *FirstArgExpr = AL.getArgAsExpr(2);
3447  uint32_t FirstArg;
3448  if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3449  return;
3450 
3451  // check if the function is variadic if the 3rd argument non-zero
3452  if (FirstArg != 0) {
3453  if (isFunctionOrMethodVariadic(D)) {
3454  ++NumArgs; // +1 for ...
3455  } else {
3456  S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3457  return;
3458  }
3459  }
3460 
3461  // strftime requires FirstArg to be 0 because it doesn't read from any
3462  // variable the input is just the current time + the format string.
3463  if (Kind == StrftimeFormat) {
3464  if (FirstArg != 0) {
3465  S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3466  << FirstArgExpr->getSourceRange();
3467  return;
3468  }
3469  // if 0 it disables parameter checking (to use with e.g. va_list)
3470  } else if (FirstArg != 0 && FirstArg != NumArgs) {
3471  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3472  << AL << 3 << FirstArgExpr->getSourceRange();
3473  return;
3474  }
3475 
3476  FormatAttr *NewAttr = S.mergeFormatAttr(D, AL.getRange(), II,
3477  Idx, FirstArg,
3479  if (NewAttr)
3480  D->addAttr(NewAttr);
3481 }
3482 
3483 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3484  // Try to find the underlying union declaration.
3485  RecordDecl *RD = nullptr;
3486  const auto *TD = dyn_cast<TypedefNameDecl>(D);
3487  if (TD && TD->getUnderlyingType()->isUnionType())
3488  RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3489  else
3490  RD = dyn_cast<RecordDecl>(D);
3491 
3492  if (!RD || !RD->isUnion()) {
3493  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
3494  << ExpectedUnion;
3495  return;
3496  }
3497 
3498  if (!RD->isCompleteDefinition()) {
3499  if (!RD->isBeingDefined())
3500  S.Diag(AL.getLoc(),
3501  diag::warn_transparent_union_attribute_not_definition);
3502  return;
3503  }
3504 
3506  FieldEnd = RD->field_end();
3507  if (Field == FieldEnd) {
3508  S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3509  return;
3510  }
3511 
3512  FieldDecl *FirstField = *Field;
3513  QualType FirstType = FirstField->getType();
3514  if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3515  S.Diag(FirstField->getLocation(),
3516  diag::warn_transparent_union_attribute_floating)
3517  << FirstType->isVectorType() << FirstType;
3518  return;
3519  }
3520 
3521  if (FirstType->isIncompleteType())
3522  return;
3523  uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3524  uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3525  for (; Field != FieldEnd; ++Field) {
3526  QualType FieldType = Field->getType();
3527  if (FieldType->isIncompleteType())
3528  return;
3529  // FIXME: this isn't fully correct; we also need to test whether the
3530  // members of the union would all have the same calling convention as the
3531  // first member of the union. Checking just the size and alignment isn't
3532  // sufficient (consider structs passed on the stack instead of in registers
3533  // as an example).
3534  if (S.Context.getTypeSize(FieldType) != FirstSize ||
3535  S.Context.getTypeAlign(FieldType) > FirstAlign) {
3536  // Warn if we drop the attribute.
3537  bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3538  unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3539  : S.Context.getTypeAlign(FieldType);
3540  S.Diag(Field->getLocation(),
3541  diag::warn_transparent_union_attribute_field_size_align)
3542  << isSize << Field->getDeclName() << FieldBits;
3543  unsigned FirstBits = isSize? FirstSize : FirstAlign;
3544  S.Diag(FirstField->getLocation(),
3545  diag::note_transparent_union_first_field_size_align)
3546  << isSize << FirstBits;
3547  return;
3548  }
3549  }
3550 
3551  RD->addAttr(::new (S.Context)
3552  TransparentUnionAttr(AL.getRange(), S.Context,
3554 }
3555 
3556 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3557  // Make sure that there is a string literal as the annotation's single
3558  // argument.
3559  StringRef Str;
3560  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3561  return;
3562 
3563  // Don't duplicate annotations that are already set.
3564  for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3565  if (I->getAnnotation() == Str)
3566  return;
3567  }
3568 
3569  D->addAttr(::new (S.Context)
3570  AnnotateAttr(AL.getRange(), S.Context, Str,
3572 }
3573 
3574 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3575  S.AddAlignValueAttr(AL.getRange(), D, AL.getArgAsExpr(0),
3577 }
3578 
3579 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3580  unsigned SpellingListIndex) {
3581  AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3582  SourceLocation AttrLoc = AttrRange.getBegin();
3583 
3584  QualType T;
3585  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3586  T = TD->getUnderlyingType();
3587  else if (const auto *VD = dyn_cast<ValueDecl>(D))
3588  T = VD->getType();
3589  else
3590  llvm_unreachable("Unknown decl type for align_value");
3591 
3592  if (!T->isDependentType() && !T->isAnyPointerType() &&
3593  !T->isReferenceType() && !T->isMemberPointerType()) {
3594  Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3595  << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3596  return;
3597  }
3598 
3599  if (!E->isValueDependent()) {
3600  llvm::APSInt Alignment;
3601  ExprResult ICE
3602  = VerifyIntegerConstantExpression(E, &Alignment,
3603  diag::err_align_value_attribute_argument_not_int,
3604  /*AllowFold*/ false);
3605  if (ICE.isInvalid())
3606  return;
3607 
3608  if (!Alignment.isPowerOf2()) {
3609  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3610  << E->getSourceRange();
3611  return;
3612  }
3613 
3614  D->addAttr(::new (Context)
3615  AlignValueAttr(AttrRange, Context, ICE.get(),
3616  SpellingListIndex));
3617  return;
3618  }
3619 
3620  // Save dependent expressions in the AST to be instantiated.
3621  D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3622 }
3623 
3624 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3625  // check the attribute arguments.
3626  if (AL.getNumArgs() > 1) {
3627  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3628  return;
3629  }
3630 
3631  if (AL.getNumArgs() == 0) {
3632  D->addAttr(::new (S.Context) AlignedAttr(AL.getRange(), S.Context,
3633  true, nullptr, AL.getAttributeSpellingListIndex()));
3634  return;
3635  }
3636 
3637  Expr *E = AL.getArgAsExpr(0);
3639  S.Diag(AL.getEllipsisLoc(),
3640  diag::err_pack_expansion_without_parameter_packs);
3641  return;
3642  }
3643 
3645  return;
3646 
3648  AL.isPackExpansion());
3649 }
3650 
3651 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3652  unsigned SpellingListIndex, bool IsPackExpansion) {
3653  AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3654  SourceLocation AttrLoc = AttrRange.getBegin();
3655 
3656  // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3657  if (TmpAttr.isAlignas()) {
3658  // C++11 [dcl.align]p1:
3659  // An alignment-specifier may be applied to a variable or to a class
3660  // data member, but it shall not be applied to a bit-field, a function
3661  // parameter, the formal parameter of a catch clause, or a variable
3662  // declared with the register storage class specifier. An
3663  // alignment-specifier may also be applied to the declaration of a class
3664  // or enumeration type.
3665  // C11 6.7.5/2:
3666  // An alignment attribute shall not be specified in a declaration of
3667  // a typedef, or a bit-field, or a function, or a parameter, or an
3668  // object declared with the register storage-class specifier.
3669  int DiagKind = -1;
3670  if (isa<ParmVarDecl>(D)) {
3671  DiagKind = 0;
3672  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3673  if (VD->getStorageClass() == SC_Register)
3674  DiagKind = 1;
3675  if (VD->isExceptionVariable())
3676  DiagKind = 2;
3677  } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3678  if (FD->isBitField())
3679  DiagKind = 3;
3680  } else if (!isa<TagDecl>(D)) {
3681  Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3682  << (TmpAttr.isC11() ? ExpectedVariableOrField
3684  return;
3685  }
3686  if (DiagKind != -1) {
3687  Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3688  << &TmpAttr << DiagKind;
3689  return;
3690  }
3691  }
3692 
3693  if (E->isValueDependent()) {
3694  // We can't support a dependent alignment on a non-dependent type,
3695  // because we have no way to model that a type is "alignment-dependent"
3696  // but not dependent in any other way.
3697  if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3698  if (!TND->getUnderlyingType()->isDependentType()) {
3699  Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
3700  << E->getSourceRange();
3701  return;
3702  }
3703  }
3704 
3705  // Save dependent expressions in the AST to be instantiated.
3706  AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3707  AA->setPackExpansion(IsPackExpansion);
3708  D->addAttr(AA);
3709  return;
3710  }
3711 
3712  // FIXME: Cache the number on the AL object?
3713  llvm::APSInt Alignment;
3714  ExprResult ICE
3715  = VerifyIntegerConstantExpression(E, &Alignment,
3716  diag::err_aligned_attribute_argument_not_int,
3717  /*AllowFold*/ false);
3718  if (ICE.isInvalid())
3719  return;
3720 
3721  uint64_t AlignVal = Alignment.getZExtValue();
3722 
3723  // C++11 [dcl.align]p2:
3724  // -- if the constant expression evaluates to zero, the alignment
3725  // specifier shall have no effect
3726  // C11 6.7.5p6:
3727  // An alignment specification of zero has no effect.
3728  if (!(TmpAttr.isAlignas() && !Alignment)) {
3729  if (!llvm::isPowerOf2_64(AlignVal)) {
3730  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3731  << E->getSourceRange();
3732  return;
3733  }
3734  }
3735 
3736  // Alignment calculations can wrap around if it's greater than 2**28.
3737  unsigned MaxValidAlignment =
3738  Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3739  : 268435456;
3740  if (AlignVal > MaxValidAlignment) {
3741  Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3742  << E->getSourceRange();
3743  return;
3744  }
3745 
3746  if (Context.getTargetInfo().isTLSSupported()) {
3747  unsigned MaxTLSAlign =
3748  Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3749  .getQuantity();
3750  const auto *VD = dyn_cast<VarDecl>(D);
3751  if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3752  VD->getTLSKind() != VarDecl::TLS_None) {
3753  Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3754  << (unsigned)AlignVal << VD << MaxTLSAlign;
3755  return;
3756  }
3757  }
3758 
3759  AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3760  ICE.get(), SpellingListIndex);
3761  AA->setPackExpansion(IsPackExpansion);
3762  D->addAttr(AA);
3763 }
3764 
3765 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3766  unsigned SpellingListIndex, bool IsPackExpansion) {
3767  // FIXME: Cache the number on the AL object if non-dependent?
3768  // FIXME: Perform checking of type validity
3769  AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3770  SpellingListIndex);
3771  AA->setPackExpansion(IsPackExpansion);
3772  D->addAttr(AA);
3773 }
3774 
3776  assert(D->hasAttrs() && "no attributes on decl");
3777 
3778  QualType UnderlyingTy, DiagTy;
3779  if (const auto *VD = dyn_cast<ValueDecl>(D)) {
3780  UnderlyingTy = DiagTy = VD->getType();
3781  } else {
3782  UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3783  if (const auto *ED = dyn_cast<EnumDecl>(D))
3784  UnderlyingTy = ED->getIntegerType();
3785  }
3786  if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3787  return;
3788 
3789  // C++11 [dcl.align]p5, C11 6.7.5/4:
3790  // The combined effect of all alignment attributes in a declaration shall
3791  // not specify an alignment that is less strict than the alignment that
3792  // would otherwise be required for the entity being declared.
3793  AlignedAttr *AlignasAttr = nullptr;
3794  unsigned Align = 0;
3795  for (auto *I : D->specific_attrs<AlignedAttr>()) {
3796  if (I->isAlignmentDependent())
3797  return;
3798  if (I->isAlignas())
3799  AlignasAttr = I;
3800  Align = std::max(Align, I->getAlignment(Context));
3801  }
3802 
3803  if (AlignasAttr && Align) {
3804  CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3805  CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3806  if (NaturalAlign > RequestedAlign)
3807  Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3808  << DiagTy << (unsigned)NaturalAlign.getQuantity();
3809  }
3810 }
3811 
3813  CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3814  MSInheritanceAttr::Spelling SemanticSpelling) {
3815  assert(RD->hasDefinition() && "RD has no definition!");
3816 
3817  // We may not have seen base specifiers or any virtual methods yet. We will
3818  // have to wait until the record is defined to catch any mismatches.
3819  if (!RD->getDefinition()->isCompleteDefinition())
3820  return false;
3821 
3822  // The unspecified model never matches what a definition could need.
3823  if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3824  return false;
3825 
3826  if (BestCase) {
3827  if (RD->calculateInheritanceModel() == SemanticSpelling)
3828  return false;
3829  } else {
3830  if (RD->calculateInheritanceModel() <= SemanticSpelling)
3831  return false;
3832  }
3833 
3834  Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3835  << 0 /*definition*/;
3836  Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3837  << RD->getNameAsString();
3838  return true;
3839 }
3840 
3841 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3842 /// attribute.
3843 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3844  bool &IntegerMode, bool &ComplexMode) {
3845  IntegerMode = true;
3846  ComplexMode = false;
3847  switch (Str.size()) {
3848  case 2:
3849  switch (Str[0]) {
3850  case 'Q':
3851  DestWidth = 8;
3852  break;
3853  case 'H':
3854  DestWidth = 16;
3855  break;
3856  case 'S':
3857  DestWidth = 32;
3858  break;
3859  case 'D':
3860  DestWidth = 64;
3861  break;
3862  case 'X':
3863  DestWidth = 96;
3864  break;
3865  case 'T':
3866  DestWidth = 128;
3867  break;
3868  }
3869  if (Str[1] == 'F') {
3870  IntegerMode = false;
3871  } else if (Str[1] == 'C') {
3872  IntegerMode = false;
3873  ComplexMode = true;
3874  } else if (Str[1] != 'I') {
3875  DestWidth = 0;
3876  }
3877  break;
3878  case 4:
3879  // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3880  // pointer on PIC16 and other embedded platforms.
3881  if (Str == "word")
3882  DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3883  else if (Str == "byte")
3884  DestWidth = S.Context.getTargetInfo().getCharWidth();
3885  break;
3886  case 7:
3887  if (Str == "pointer")
3888  DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3889  break;
3890  case 11:
3891  if (Str == "unwind_word")
3892  DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3893  break;
3894  }
3895 }
3896 
3897 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3898 /// type.
3899 ///
3900 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3901 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3902 /// HImode, not an intermediate pointer.
3903 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3904  // This attribute isn't documented, but glibc uses it. It changes
3905  // the width of an int or unsigned int to the specified size.
3906  if (!AL.isArgIdent(0)) {
3907  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
3908  << AL << AANT_ArgumentIdentifier;
3909  return;
3910  }
3911 
3912  IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
3913 
3914  S.AddModeAttr(AL.getRange(), D, Name, AL.getAttributeSpellingListIndex());
3915 }
3916 
3917 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3918  unsigned SpellingListIndex, bool InInstantiation) {
3919  StringRef Str = Name->getName();
3920  normalizeName(Str);
3921  SourceLocation AttrLoc = AttrRange.getBegin();
3922 
3923  unsigned DestWidth = 0;
3924  bool IntegerMode = true;
3925  bool ComplexMode = false;
3926  llvm::APInt VectorSize(64, 0);
3927  if (Str.size() >= 4 && Str[0] == 'V') {
3928  // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3929  size_t StrSize = Str.size();
3930  size_t VectorStringLength = 0;
3931  while ((VectorStringLength + 1) < StrSize &&
3932  isdigit(Str[VectorStringLength + 1]))
3933  ++VectorStringLength;
3934  if (VectorStringLength &&
3935  !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3936  VectorSize.isPowerOf2()) {
3937  parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3938  IntegerMode, ComplexMode);
3939  // Avoid duplicate warning from template instantiation.
3940  if (!InInstantiation)
3941  Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3942  } else {
3943  VectorSize = 0;
3944  }
3945  }
3946 
3947  if (!VectorSize)
3948  parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3949 
3950  // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3951  // and friends, at least with glibc.
3952  // FIXME: Make sure floating-point mappings are accurate
3953  // FIXME: Support XF and TF types
3954  if (!DestWidth) {
3955  Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3956  return;
3957  }
3958 
3959  QualType OldTy;
3960  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3961  OldTy = TD->getUnderlyingType();
3962  else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
3963  // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3964  // Try to get type from enum declaration, default to int.
3965  OldTy = ED->getIntegerType();
3966  if (OldTy.isNull())
3967  OldTy = Context.IntTy;
3968  } else
3969  OldTy = cast<ValueDecl>(D)->getType();
3970 
3971  if (OldTy->isDependentType()) {
3972  D->addAttr(::new (Context)
3973  ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3974  return;
3975  }
3976 
3977  // Base type can also be a vector type (see PR17453).
3978  // Distinguish between base type and base element type.
3979  QualType OldElemTy = OldTy;
3980  if (const auto *VT = OldTy->getAs<VectorType>())
3981  OldElemTy = VT->getElementType();
3982 
3983  // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3984  // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3985  // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3986  if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3987  VectorSize.getBoolValue()) {
3988  Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3989  return;
3990  }
3991  bool IntegralOrAnyEnumType =
3992  OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3993 
3994  if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3995  !IntegralOrAnyEnumType)
3996  Diag(AttrLoc, diag::err_mode_not_primitive);
3997  else if (IntegerMode) {
3998  if (!IntegralOrAnyEnumType)
3999  Diag(AttrLoc, diag::err_mode_wrong_type);
4000  } else if (ComplexMode) {
4001  if (!OldElemTy->isComplexType())
4002  Diag(AttrLoc, diag::err_mode_wrong_type);
4003  } else {
4004  if (!OldElemTy->isFloatingType())
4005  Diag(AttrLoc, diag::err_mode_wrong_type);
4006  }
4007 
4008  QualType NewElemTy;
4009 
4010  if (IntegerMode)
4011  NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4012  OldElemTy->isSignedIntegerType());
4013  else
4014  NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
4015 
4016  if (NewElemTy.isNull()) {
4017  Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4018  return;
4019  }
4020 
4021  if (ComplexMode) {
4022  NewElemTy = Context.getComplexType(NewElemTy);
4023  }
4024 
4025  QualType NewTy = NewElemTy;
4026  if (VectorSize.getBoolValue()) {
4027  NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4029  } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4030  // Complex machine mode does not support base vector types.
4031  if (ComplexMode) {
4032  Diag(AttrLoc, diag::err_complex_mode_vector_type);
4033  return;
4034  }
4035  unsigned NumElements = Context.getTypeSize(OldElemTy) *
4036  OldVT->getNumElements() /
4037  Context.getTypeSize(NewElemTy);
4038  NewTy =
4039  Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4040  }
4041 
4042  if (NewTy.isNull()) {
4043  Diag(AttrLoc, diag::err_mode_wrong_type);
4044  return;
4045  }
4046 
4047  // Install the new type.
4048  if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4049  TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4050  else if (auto *ED = dyn_cast<EnumDecl>(D))
4051  ED->setIntegerType(NewTy);
4052  else
4053  cast<ValueDecl>(D)->setType(NewTy);
4054 
4055  D->addAttr(::new (Context)
4056  ModeAttr(AttrRange, Context, Name, SpellingListIndex));
4057 }
4058 
4059 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4060  D->addAttr(::new (S.Context)
4061  NoDebugAttr(AL.getRange(), S.Context,
4063 }
4064 
4065 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
4066  IdentifierInfo *Ident,
4067  unsigned AttrSpellingListIndex) {
4068  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4069  Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
4070  Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4071  return nullptr;
4072  }
4073 
4074  if (D->hasAttr<AlwaysInlineAttr>())
4075  return nullptr;
4076 
4077  return ::new (Context) AlwaysInlineAttr(Range, Context,
4078  AttrSpellingListIndex);
4079 }
4080 
4081 CommonAttr *Sema::mergeCommonAttr(Decl *D, const ParsedAttr &AL) {
4082  if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4083  return nullptr;
4084 
4085  return ::new (Context)
4086  CommonAttr(AL.getRange(), Context, AL.getAttributeSpellingListIndex());
4087 }
4088 
4089 CommonAttr *Sema::mergeCommonAttr(Decl *D, const CommonAttr &AL) {
4090  if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4091  return nullptr;
4092 
4093  return ::new (Context)
4094  CommonAttr(AL.getRange(), Context, AL.getSpellingListIndex());
4095 }
4096 
4097 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4098  const ParsedAttr &AL) {
4099  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4100  // Attribute applies to Var but not any subclass of it (like ParmVar,
4101  // ImplicitParm or VarTemplateSpecialization).
4102  if (VD->getKind() != Decl::Var) {
4103  Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4104  << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4106  return nullptr;
4107  }
4108  // Attribute does not apply to non-static local variables.
4109  if (VD->hasLocalStorage()) {
4110  Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4111  return nullptr;
4112  }
4113  }
4114 
4115  if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4116  return nullptr;
4117 
4118  return ::new (Context) InternalLinkageAttr(
4119  AL.getRange(), Context, AL.getAttributeSpellingListIndex());
4120 }
4121 InternalLinkageAttr *
4122 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4123  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4124  // Attribute applies to Var but not any subclass of it (like ParmVar,
4125  // ImplicitParm or VarTemplateSpecialization).
4126  if (VD->getKind() != Decl::Var) {
4127  Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4128  << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4130  return nullptr;
4131  }
4132  // Attribute does not apply to non-static local variables.
4133  if (VD->hasLocalStorage()) {
4134  Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4135  return nullptr;
4136  }
4137  }
4138 
4139  if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4140  return nullptr;
4141 
4142  return ::new (Context)
4143  InternalLinkageAttr(AL.getRange(), Context, AL.getSpellingListIndex());
4144 }
4145 
4146 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
4147  unsigned AttrSpellingListIndex) {
4148  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4149  Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
4150  Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4151  return nullptr;
4152  }
4153 
4154  if (D->hasAttr<MinSizeAttr>())
4155  return nullptr;
4156 
4157  return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
4158 }
4159 
4160 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
4161  unsigned AttrSpellingListIndex) {
4162  if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4163  Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4164  Diag(Range.getBegin(), diag::note_conflicting_attribute);
4165  D->dropAttr<AlwaysInlineAttr>();
4166  }
4167  if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4168  Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4169  Diag(Range.getBegin(), diag::note_conflicting_attribute);
4170  D->dropAttr<MinSizeAttr>();
4171  }
4172 
4173  if (D->hasAttr<OptimizeNoneAttr>())
4174  return nullptr;
4175 
4176  return ::new (Context) OptimizeNoneAttr(Range, Context,
4177  AttrSpellingListIndex);
4178 }
4179 
4180 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4181  if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, AL))
4182  return;
4183 
4184  if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
4185  D, AL.getRange(), AL.getName(),
4187  D->addAttr(Inline);
4188 }
4189 
4190 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4191  if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4192  D, AL.getRange(), AL.getAttributeSpellingListIndex()))
4193  D->addAttr(MinSize);
4194 }
4195 
4196 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4197  if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4198  D, AL.getRange(), AL.getAttributeSpellingListIndex()))
4199  D->addAttr(Optnone);
4200 }
4201 
4202 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4203  if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, AL))
4204  return;
4205  const auto *VD = cast<VarDecl>(D);
4206  if (!VD->hasGlobalStorage()) {
4207  S.Diag(AL.getLoc(), diag::err_cuda_nonglobal_constant);
4208  return;
4209  }
4210  D->addAttr(::new (S.Context) CUDAConstantAttr(
4212 }
4213 
4214 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4215  if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, AL))
4216  return;
4217  const auto *VD = cast<VarDecl>(D);
4218  // extern __shared__ is only allowed on arrays with no length (e.g.
4219  // "int x[]").
4220  if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4221  !isa<IncompleteArrayType>(VD->getType())) {
4222  S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4223  return;
4224  }
4225  if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4226  S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4227  << S.CurrentCUDATarget())
4228  return;
4229  D->addAttr(::new (S.Context) CUDASharedAttr(
4231 }
4232 
4233 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4234  if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, AL) ||
4235  checkAttrMutualExclusion<CUDAHostAttr>(S, D, AL)) {
4236  return;
4237  }
4238  const auto *FD = cast<FunctionDecl>(D);
4239  if (!FD->getReturnType()->isVoidType()) {
4240  SourceRange RTRange = FD->getReturnTypeSourceRange();
4241  S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4242  << FD->getType()
4243  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4244  : FixItHint());
4245  return;
4246  }
4247  if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4248  if (Method->isInstance()) {
4249  S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4250  << Method;
4251  return;
4252  }
4253  S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4254  }
4255  // Only warn for "inline" when compiling for host, to cut down on noise.
4256  if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4257  S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4258 
4259  D->addAttr(::new (S.Context)
4260  CUDAGlobalAttr(AL.getRange(), S.Context,
4262 }
4263 
4264 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4265  const auto *Fn = cast<FunctionDecl>(D);
4266  if (!Fn->isInlineSpecified()) {
4267  S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4268  return;
4269  }
4270 
4271  D->addAttr(::new (S.Context)
4272  GNUInlineAttr(AL.getRange(), S.Context,
4274 }
4275 
4276 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4277  if (hasDeclarator(D)) return;
4278 
4279  // Diagnostic is emitted elsewhere: here we store the (valid) AL
4280  // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4281  CallingConv CC;
4282  if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4283  return;
4284 
4285  if (!isa<ObjCMethodDecl>(D)) {
4286  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4287  << AL << ExpectedFunctionOrMethod;
4288  return;
4289  }
4290 
4291  switch (AL.getKind()) {
4292  case ParsedAttr::AT_FastCall:
4293  D->addAttr(::new (S.Context)
4294  FastCallAttr(AL.getRange(), S.Context,
4296  return;
4297  case ParsedAttr::AT_StdCall:
4298  D->addAttr(::new (S.Context)
4299  StdCallAttr(AL.getRange(), S.Context,
4301  return;
4302  case ParsedAttr::AT_ThisCall:
4303  D->addAttr(::new (S.Context)
4304  ThisCallAttr(AL.getRange(), S.Context,
4306  return;
4307  case ParsedAttr::AT_CDecl:
4308  D->addAttr(::new (S.Context)
4309  CDeclAttr(AL.getRange(), S.Context,
4311  return;
4312  case ParsedAttr::AT_Pascal:
4313  D->addAttr(::new (S.Context)
4314  PascalAttr(AL.getRange(), S.Context,
4316  return;
4317  case ParsedAttr::AT_SwiftCall:
4318  D->addAttr(::new (S.Context)
4319  SwiftCallAttr(AL.getRange(), S.Context,
4321  return;
4322  case ParsedAttr::AT_VectorCall:
4323  D->addAttr(::new (S.Context)
4324  VectorCallAttr(AL.getRange(), S.Context,
4326  return;
4327  case ParsedAttr::AT_MSABI:
4328  D->addAttr(::new (S.Context)
4329  MSABIAttr(AL.getRange(), S.Context,
4331  return;
4332  case ParsedAttr::AT_SysVABI:
4333  D->addAttr(::new (S.Context)
4334  SysVABIAttr(AL.getRange(), S.Context,
4336  return;
4337  case ParsedAttr::AT_RegCall:
4338  D->addAttr(::new (S.Context) RegCallAttr(
4340  return;
4341  case ParsedAttr::AT_Pcs: {
4342  PcsAttr::PCSType PCS;
4343  switch (CC) {
4344  case CC_AAPCS:
4345  PCS = PcsAttr::AAPCS;
4346  break;
4347  case CC_AAPCS_VFP:
4348  PCS = PcsAttr::AAPCS_VFP;
4349  break;
4350  default:
4351  llvm_unreachable("unexpected calling convention in pcs attribute");
4352  }
4353 
4354  D->addAttr(::new (S.Context)
4355  PcsAttr(AL.getRange(), S.Context, PCS,
4357  return;
4358  }
4359  case ParsedAttr::AT_AArch64VectorPcs:
4360  D->addAttr(::new(S.Context)
4361  AArch64VectorPcsAttr(AL.getRange(), S.Context,
4363  return;
4364  case ParsedAttr::AT_IntelOclBicc:
4365  D->addAttr(::new (S.Context)
4366  IntelOclBiccAttr(AL.getRange(), S.Context,
4368  return;
4369  case ParsedAttr::AT_PreserveMost:
4370  D->addAttr(::new (S.Context) PreserveMostAttr(
4372  return;
4373  case ParsedAttr::AT_PreserveAll:
4374  D->addAttr(::new (S.Context) PreserveAllAttr(
4376  return;
4377  default:
4378  llvm_unreachable("unexpected attribute kind");
4379  }
4380 }
4381 
4382 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4383  if (!checkAttributeAtLeastNumArgs(S, AL, 1))
4384  return;
4385 
4386  std::vector<StringRef> DiagnosticIdentifiers;
4387  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4388  StringRef RuleName;
4389 
4390  if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4391  return;
4392 
4393  // FIXME: Warn if the rule name is unknown. This is tricky because only
4394  // clang-tidy knows about available rules.
4395  DiagnosticIdentifiers.push_back(RuleName);
4396  }
4397  D->addAttr(::new (S.Context) SuppressAttr(
4398  AL.getRange(), S.Context, DiagnosticIdentifiers.data(),
4399  DiagnosticIdentifiers.size(), AL.getAttributeSpellingListIndex()));
4400 }
4401 
4402 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
4403  const FunctionDecl *FD) {
4404  if (Attrs.isInvalid())
4405  return true;
4406 
4407  if (Attrs.hasProcessingCache()) {
4408  CC = (CallingConv) Attrs.getProcessingCache();
4409  return false;
4410  }
4411 
4412  unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4413  if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4414  Attrs.setInvalid();
4415  return true;
4416  }
4417 
4418  // TODO: diagnose uses of these conventions on the wrong target.
4419  switch (Attrs.getKind()) {
4420  case ParsedAttr::AT_CDecl:
4421  CC = CC_C;
4422  break;
4423  case ParsedAttr::AT_FastCall:
4424  CC = CC_X86FastCall;
4425  break;
4426  case ParsedAttr::AT_StdCall:
4427  CC = CC_X86StdCall;
4428  break;
4429  case ParsedAttr::AT_ThisCall:
4430  CC = CC_X86ThisCall;
4431  break;
4432  case ParsedAttr::AT_Pascal:
4433  CC = CC_X86Pascal;
4434  break;
4435  case ParsedAttr::AT_SwiftCall:
4436  CC = CC_Swift;
4437  break;
4438  case ParsedAttr::AT_VectorCall:
4439  CC = CC_X86VectorCall;
4440  break;
4441  case ParsedAttr::AT_AArch64VectorPcs:
4442  CC = CC_AArch64VectorCall;
4443  break;
4444  case ParsedAttr::AT_RegCall:
4445  CC = CC_X86RegCall;
4446  break;
4447  case ParsedAttr::AT_MSABI:
4448  CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4449  CC_Win64;
4450  break;
4451  case ParsedAttr::AT_SysVABI:
4452  CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4453  CC_C;
4454  break;
4455  case ParsedAttr::AT_Pcs: {
4456  StringRef StrRef;
4457  if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4458  Attrs.setInvalid();
4459  return true;
4460  }
4461  if (StrRef == "aapcs") {
4462  CC = CC_AAPCS;
4463  break;
4464  } else if (StrRef == "aapcs-vfp") {
4465  CC = CC_AAPCS_VFP;
4466  break;
4467  }
4468 
4469  Attrs.setInvalid();
4470  Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4471  return true;
4472  }
4473  case ParsedAttr::AT_IntelOclBicc:
4474  CC = CC_IntelOclBicc;
4475  break;
4476  case ParsedAttr::AT_PreserveMost:
4477  CC = CC_PreserveMost;
4478  break;
4479  case ParsedAttr::AT_PreserveAll:
4480  CC = CC_PreserveAll;
4481  break;
4482  default: llvm_unreachable("unexpected attribute kind");
4483  }
4484 
4485  const TargetInfo &TI = Context.getTargetInfo();
4487  if (A != TargetInfo::CCCR_OK) {
4488  if (A == TargetInfo::CCCR_Warning)
4489  Diag(Attrs.getLoc(), diag::warn_cconv_ignored) << Attrs;
4490 
4491  // This convention is not valid for the target. Use the default function or
4492  // method calling convention.
4493  bool IsCXXMethod = false, IsVariadic = false;
4494  if (FD) {
4495  IsCXXMethod = FD->isCXXInstanceMember();
4496  IsVariadic = FD->isVariadic();
4497  }
4498  CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4499  }
4500 
4501  Attrs.setProcessingCache((unsigned) CC);
4502  return false;
4503 }
4504 
4505 /// Pointer-like types in the default address space.
4506 static bool isValidSwiftContextType(QualType Ty) {
4507  if (!Ty->hasPointerRepresentation())
4508  return Ty->isDependentType();
4510 }
4511 
4512 /// Pointers and references in the default address space.
4513 static bool isValidSwiftIndirectResultType(QualType Ty) {
4514  if (const auto *PtrType = Ty->getAs<PointerType>()) {
4515  Ty = PtrType->getPointeeType();
4516  } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4517  Ty = RefType->getPointeeType();
4518  } else {
4519  return Ty->isDependentType();
4520  }
4521  return Ty.getAddressSpace() == LangAS::Default;
4522 }
4523 
4524 /// Pointers and references to pointers in the default address space.
4525 static bool isValidSwiftErrorResultType(QualType Ty) {
4526  if (const auto *PtrType = Ty->getAs<PointerType>()) {
4527  Ty = PtrType->getPointeeType();
4528  } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4529  Ty = RefType->getPointeeType();
4530  } else {
4531  return Ty->isDependentType();
4532  }
4533  if (!Ty.getQualifiers().empty())
4534  return false;
4535  return isValidSwiftContextType(Ty);
4536 }
4537 
4538 static void handleParameterABIAttr(Sema &S, Decl *D, const ParsedAttr &Attrs,
4539  ParameterABI Abi) {
4540  S.AddParameterABIAttr(Attrs.getRange(), D, Abi,
4542 }
4543 
4545  unsigned spellingIndex) {
4546 
4547  QualType type = cast<ParmVarDecl>(D)->getType();
4548 
4549  if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4550  if (existingAttr->getABI() != abi) {
4551  Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4552  << getParameterABISpelling(abi) << existingAttr;
4553  Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4554  return;
4555  }
4556  }
4557 
4558  switch (abi) {
4560  llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4561 
4563  if (!isValidSwiftContextType(type)) {
4564  Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4565  << getParameterABISpelling(abi)
4566  << /*pointer to pointer */ 0 << type;
4567  }
4568  D->addAttr(::new (Context)
4569  SwiftContextAttr(range, Context, spellingIndex));
4570  return;
4571 
4573  if (!isValidSwiftErrorResultType(type)) {
4574  Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4575  << getParameterABISpelling(abi)
4576  << /*pointer to pointer */ 1 << type;
4577  }
4578  D->addAttr(::new (Context)
4579  SwiftErrorResultAttr(range, Context, spellingIndex));
4580  return;
4581 
4583  if (!isValidSwiftIndirectResultType(type)) {
4584  Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4585  << getParameterABISpelling(abi)
4586  << /*pointer*/ 0 << type;
4587  }
4588  D->addAttr(::new (Context)
4589  SwiftIndirectResultAttr(range, Context, spellingIndex));
4590  return;
4591  }
4592  llvm_unreachable("bad parameter ABI attribute");
4593 }
4594 
4595 /// Checks a regparm attribute, returning true if it is ill-formed and
4596 /// otherwise setting numParams to the appropriate value.
4597 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
4598  if (AL.isInvalid())
4599  return true;
4600 
4601  if (!checkAttributeNumArgs(*this, AL, 1)) {
4602  AL.setInvalid();
4603  return true;
4604  }
4605 
4606  uint32_t NP;
4607  Expr *NumParamsExpr = AL.getArgAsExpr(0);
4608  if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
4609  AL.setInvalid();
4610  return true;
4611  }
4612 
4613  if (Context.getTargetInfo().getRegParmMax() == 0) {
4614  Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
4615  << NumParamsExpr->getSourceRange();
4616  AL.setInvalid();
4617  return true;
4618  }
4619 
4620  numParams = NP;
4621  if (numParams > Context.getTargetInfo().getRegParmMax()) {
4622  Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
4623  << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4624  AL.setInvalid();
4625  return true;
4626  }
4627 
4628  return false;
4629 }
4630 
4631 // Checks whether an argument of launch_bounds attribute is
4632 // acceptable, performs implicit conversion to Rvalue, and returns
4633 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4634 // and may output an error.
4635 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4636  const CUDALaunchBoundsAttr &AL,
4637  const unsigned Idx) {
4639  return nullptr;
4640 
4641  // Accept template arguments for now as they depend on something else.
4642  // We'll get to check them when they eventually get instantiated.
4643  if (E->isValueDependent())
4644  return E;
4645 
4646  llvm::APSInt I(64);
4647  if (!E->isIntegerConstantExpr(I, S.Context)) {
4648  S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4649  << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4650  return nullptr;
4651  }
4652  // Make sure we can fit it in 32 bits.
4653  if (!I.isIntN(32)) {
4654  S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4655  << 32 << /* Unsigned */ 1;
4656  return nullptr;
4657  }
4658  if (I < 0)
4659  S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4660  << &AL << Idx << E->getSourceRange();
4661 
4662  // We may need to perform implicit conversion of the argument.
4664  S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4665  ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4666  assert(!ValArg.isInvalid() &&
4667  "Unexpected PerformCopyInitialization() failure.");
4668 
4669  return ValArg.getAs<Expr>();
4670 }
4671 
4672 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4673  Expr *MinBlocks, unsigned SpellingListIndex) {
4674  CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4675  SpellingListIndex);
4676  MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4677  if (MaxThreads == nullptr)
4678  return;
4679 
4680  if (MinBlocks) {
4681  MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4682  if (MinBlocks == nullptr)
4683  return;
4684  }
4685 
4686  D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4687  AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4688 }
4689 
4690 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4691  if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
4692  !checkAttributeAtMostNumArgs(S, AL, 2))
4693  return;
4694 
4695  S.AddLaunchBoundsAttr(AL.getRange(), D, AL.getArgAsExpr(0),
4696  AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr,
4698 }
4699 
4700 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4701  const ParsedAttr &AL) {
4702  if (!AL.isArgIdent(0)) {
4703  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4704  << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4705  return;
4706  }
4707 
4708  ParamIdx ArgumentIdx;
4709  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
4710  ArgumentIdx))
4711  return;
4712 
4713  ParamIdx TypeTagIdx;
4714  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
4715  TypeTagIdx))
4716  return;
4717 
4718  bool IsPointer = AL.getName()->getName() == "pointer_with_type_tag";
4719  if (IsPointer) {
4720  // Ensure that buffer has a pointer type.
4721  unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
4722  if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
4723  !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
4724  S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
4725  }
4726 
4727  D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
4728  AL.getRange(), S.Context, AL.getArgAsIdent(0)->Ident, ArgumentIdx,
4729  TypeTagIdx, IsPointer, AL.getAttributeSpellingListIndex()));
4730 }
4731 
4732 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4733  const ParsedAttr &AL) {
4734  if (!AL.isArgIdent(0)) {
4735  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4736  << AL << 1 << AANT_ArgumentIdentifier;
4737  return;
4738  }
4739 
4740  if (!checkAttributeNumArgs(S, AL, 1))
4741  return;
4742 
4743  if (!isa<VarDecl>(D)) {
4744  S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
4745  << AL << ExpectedVariable;
4746  return;
4747  }
4748 
4749  IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
4750  TypeSourceInfo *MatchingCTypeLoc = nullptr;
4751  S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
4752  assert(MatchingCTypeLoc && "no type source info for attribute argument");
4753 
4754  D->addAttr(::new (S.Context)
4755  TypeTagForDatatypeAttr(AL.getRange(), S.Context, PointerKind,
4756  MatchingCTypeLoc,
4757  AL.getLayoutCompatible(),
4758  AL.getMustBeNull(),
4760 }
4761 
4762 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4763  ParamIdx ArgCount;
4764 
4765  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
4766  ArgCount,
4767  true /* CanIndexImplicitThis */))
4768  return;
4769 
4770  // ArgCount isn't a parameter index [0;n), it's a count [1;n]
4771  D->addAttr(::new (S.Context) XRayLogArgsAttr(
4772  AL.getRange(), S.Context, ArgCount.getSourceIndex(),
4774 }
4775 
4776 //===----------------------------------------------------------------------===//
4777 // Checker-specific attribute handlers.
4778 //===----------------------------------------------------------------------===//
4779 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
4780  return QT->isDependentType() || QT->isObjCRetainableType();
4781 }
4782 
4783 static bool isValidSubjectOfNSAttribute(QualType QT) {
4784  return QT->isDependentType() || QT->isObjCObjectPointerType() ||
4785  QT->isObjCNSObjectType();
4786 }
4787 
4788 static bool isValidSubjectOfCFAttribute(QualType QT) {
4789  return QT->isDependentType() || QT->isPointerType() ||
4790  isValidSubjectOfNSAttribute(QT);
4791 }
4792 
4793 static bool isValidSubjectOfOSAttribute(QualType QT) {
4794  if (QT->isDependentType())
4795  return true;
4796  QualType PT = QT->getPointeeType();
4797  return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
4798 }
4799 
4800 void Sema::AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex,
4801  RetainOwnershipKind K,
4802  bool IsTemplateInstantiation) {
4803  ValueDecl *VD = cast<ValueDecl>(D);
4804  switch (K) {
4805  case RetainOwnershipKind::OS:
4806  handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
4807  *this, VD, SR, SpellingIndex, isValidSubjectOfOSAttribute(VD->getType()),
4808  diag::warn_ns_attribute_wrong_parameter_type,
4809  /*ExtraArgs=*/SR, "os_consumed", /*pointers*/ 1);
4810  return;
4811  case RetainOwnershipKind::NS:
4812  handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
4813  *this, VD, SR, SpellingIndex, isValidSubjectOfNSAttribute(VD->getType()),
4814 
4815  // These attributes are normally just advisory, but in ARC, ns_consumed
4816  // is significant. Allow non-dependent code to contain inappropriate
4817  // attributes even in ARC, but require template instantiations to be
4818  // set up correctly.
4819  ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
4820  ? diag::err_ns_attribute_wrong_parameter_type
4821  : diag::warn_ns_attribute_wrong_parameter_type),
4822  /*ExtraArgs=*/SR, "ns_consumed", /*objc pointers*/ 0);
4823  return;
4824  case RetainOwnershipKind::CF:
4825  handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
4826  *this, VD, SR, SpellingIndex,
4827  isValidSubjectOfCFAttribute(VD->getType()),
4828  diag::warn_ns_attribute_wrong_parameter_type,
4829  /*ExtraArgs=*/SR, "cf_consumed", /*pointers*/1);
4830  return;
4831  }
4832 }
4833 
4835 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
4836  switch (AL.getKind()) {
4837  case ParsedAttr::AT_CFConsumed:
4838  case ParsedAttr::AT_CFReturnsRetained:
4839  case ParsedAttr::AT_CFReturnsNotRetained:
4841  case ParsedAttr::AT_OSConsumesThis:
4842  case ParsedAttr::AT_OSConsumed:
4843  case ParsedAttr::AT_OSReturnsRetained:
4844  case ParsedAttr::AT_OSReturnsNotRetained:
4845  case ParsedAttr::AT_OSReturnsRetainedOnZero:
4846  case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
4848  case ParsedAttr::AT_NSConsumesSelf:
4849  case ParsedAttr::AT_NSConsumed:
4850  case ParsedAttr::AT_NSReturnsRetained:
4851  case ParsedAttr::AT_NSReturnsNotRetained:
4852  case ParsedAttr::AT_NSReturnsAutoreleased:
4854  default:
4855  llvm_unreachable("Wrong argument supplied");
4856  }
4857 }
4858 
4860  if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
4861  return false;
4862 
4863  Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
4864  << "'ns_returns_retained'" << 0 << 0;
4865  return true;
4866 }
4867 
4868 /// \return whether the parameter is a pointer to OSObject pointer.
4869 static bool isValidOSObjectOutParameter(const Decl *D) {
4870  const auto *PVD = dyn_cast<ParmVarDecl>(D);
4871  if (!PVD)
4872  return false;
4873  QualType QT = PVD->getType();
4874  QualType PT = QT->getPointeeType();
4875  return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
4876 }
4877 
4878 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
4879  const ParsedAttr &AL) {
4880  QualType ReturnType;
4881  Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
4882 
4883  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
4884  ReturnType = MD->getReturnType();
4885  } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4886  (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
4887  return; // ignore: was handled as a type attribute
4888  } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
4889  ReturnType = PD->getType();
4890  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4891  ReturnType = FD->getReturnType();
4892  } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
4893  // Attributes on parameters are used for out-parameters,
4894  // passed as pointers-to-pointers.
4895  unsigned DiagID = K == Sema::RetainOwnershipKind::CF
4896  ? /*pointer-to-CF-pointer*/2
4897  : /*pointer-to-OSObject-pointer*/3;
4898  ReturnType = Param->getType()->getPointeeType();
4899  if (ReturnType.isNull()) {
4900  S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
4901  << AL << DiagID << AL.getRange();
4902  return;
4903  }
4904  } else if (AL.isUsedAsTypeAttr()) {
4905  return;
4906  } else {
4907  AttributeDeclKind ExpectedDeclKind;
4908  switch (AL.getKind()) {
4909  default: llvm_unreachable("invalid ownership attribute");
4910  case ParsedAttr::AT_NSReturnsRetained:
4911  case ParsedAttr::AT_NSReturnsAutoreleased:
4912  case ParsedAttr::AT_NSReturnsNotRetained:
4913  ExpectedDeclKind = ExpectedFunctionOrMethod;
4914  break;
4915 
4916  case ParsedAttr::AT_OSReturnsRetained:
4917  case ParsedAttr::AT_OSReturnsNotRetained:
4918  case ParsedAttr::AT_CFReturnsRetained:
4919  case ParsedAttr::AT_CFReturnsNotRetained:
4920  ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4921  break;
4922  }
4923  S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
4924  << AL.getRange() << AL << ExpectedDeclKind;
4925  return;
4926  }
4927 
4928  bool TypeOK;
4929  bool Cf;
4930  unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
4931  switch (AL.getKind()) {
4932  default: llvm_unreachable("invalid ownership attribute");
4933  case ParsedAttr::AT_NSReturnsRetained:
4934  TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
4935  Cf = false;
4936  break;
4937 
4938  case ParsedAttr::AT_NSReturnsAutoreleased:
4939  case ParsedAttr::AT_NSReturnsNotRetained:
4940  TypeOK = isValidSubjectOfNSAttribute(ReturnType);
4941  Cf = false;
4942  break;
4943 
4944  case ParsedAttr::AT_CFReturnsRetained:
4945  case ParsedAttr::AT_CFReturnsNotRetained:
4946  TypeOK = isValidSubjectOfCFAttribute(ReturnType);
4947  Cf = true;
4948  break;
4949 
4950  case ParsedAttr::AT_OSReturnsRetained:
4951  case ParsedAttr::AT_OSReturnsNotRetained:
4952  TypeOK = isValidSubjectOfOSAttribute(ReturnType);
4953  Cf = true;
4954  ParmDiagID = 3; // Pointer-to-OSObject-pointer
4955  break;
4956  }
4957 
4958  if (!TypeOK) {
4959  if (AL.isUsedAsTypeAttr())
4960  return;
4961 
4962  if (isa<ParmVarDecl>(D)) {
4963  S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
4964  << AL << ParmDiagID << AL.getRange();
4965  } else {
4966  // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4967  enum : unsigned {
4968  Function,
4969  Method,
4970  Property
4971  } SubjectKind = Function;
4972  if (isa<ObjCMethodDecl>(D))
4973  SubjectKind = Method;
4974  else if (isa<ObjCPropertyDecl>(D))
4975  SubjectKind = Property;
4976  S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
4977  << AL << SubjectKind << Cf << AL.getRange();
4978  }
4979  return;
4980  }
4981 
4982  switch (AL.getKind()) {
4983  default:
4984  llvm_unreachable("invalid ownership attribute");
4985  case ParsedAttr::AT_NSReturnsAutoreleased:
4986  handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
4987  return;
4988  case ParsedAttr::AT_CFReturnsNotRetained:
4989  handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
4990  return;
4991  case ParsedAttr::AT_NSReturnsNotRetained:
4992  handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
4993  return;
4994  case ParsedAttr::AT_CFReturnsRetained:
4995  handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
4996  return;
4997  case ParsedAttr::AT_NSReturnsRetained:
4998  handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
4999  return;
5000  case ParsedAttr::AT_OSReturnsRetained:
5001  handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
5002  return;
5003  case ParsedAttr::AT_OSReturnsNotRetained:
5004  handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
5005  return;
5006  };
5007 }
5008 
5009 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
5010  const ParsedAttr &Attrs) {
5011  const int EP_ObjCMethod = 1;
5012  const int EP_ObjCProperty = 2;
5013 
5014  SourceLocation loc = Attrs.getLoc();
5015  QualType resultType;
5016  if (isa<ObjCMethodDecl>(D))
5017  resultType = cast<ObjCMethodDecl>(D)->getReturnType();
5018  else
5019  resultType = cast<ObjCPropertyDecl>(D)->getType();
5020 
5021  if (!resultType->isReferenceType() &&
5022  (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
5023  S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5024  << SourceRange(loc) << Attrs
5025  << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
5026  << /*non-retainable pointer*/ 2;
5027 
5028  // Drop the attribute.
5029  return;
5030  }
5031 
5032  D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
5033  Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
5034 }
5035 
5036 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
5037  const ParsedAttr &Attrs) {
5038  const auto *Method = cast<ObjCMethodDecl>(D);
5039 
5040  const DeclContext *DC = Method->getDeclContext();
5041  if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
5042  S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5043  << 0;
5044  S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
5045  return;
5046  }
5047  if (Method->getMethodFamily() == OMF_dealloc) {
5048  S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5049  << 1;
5050  return;
5051  }
5052 
5053  D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(
5054  Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
5055 }
5056 
5057 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5058  IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5059 
5060  if (!Parm) {
5061  S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5062  return;
5063  }
5064 
5065  // Typedefs only allow objc_bridge(id) and have some additional checking.
5066  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
5067  if (!Parm->Ident->isStr("id")) {
5068  S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
5069  return;
5070  }
5071 
5072  // Only allow 'cv void *'.
5073  QualType T = TD->getUnderlyingType();
5074  if (!T->isVoidPointerType()) {
5075  S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
5076  return;
5077  }
5078  }
5079 
5080  D->addAttr(::new (S.Context)
5081  ObjCBridgeAttr(AL.getRange(), S.Context, Parm->Ident,
5083 }
5084 
5085 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
5086  const ParsedAttr &AL) {
5087  IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5088 
5089  if (!Parm) {
5090  S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5091  return;
5092  }
5093 
5094  D->addAttr(::new (S.Context)
5095  ObjCBridgeMutableAttr(AL.getRange(), S.Context, Parm->Ident,
5097 }
5098 
5099 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
5100  const ParsedAttr &AL) {
5101  IdentifierInfo *RelatedClass =
5102  AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
5103  if (!RelatedClass) {
5104  S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5105  return;
5106  }
5107  IdentifierInfo *ClassMethod =
5108  AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
5109  IdentifierInfo *InstanceMethod =
5110  AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
5111  D->addAttr(::new (S.Context)
5112  ObjCBridgeRelatedAttr(AL.getRange(), S.Context, RelatedClass,
5113  ClassMethod, InstanceMethod,
5115 }
5116 
5117 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
5118  const ParsedAttr &AL) {
5119  DeclContext *Ctx = D->getDeclContext();
5120 
5121  // This attribute can only be applied to methods in interfaces or class
5122  // extensions.
5123  if (!isa<ObjCInterfaceDecl>(Ctx) &&
5124  !(isa<ObjCCategoryDecl>(Ctx) &&
5125  cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
5126  S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
5127  return;
5128  }
5129 
5130  ObjCInterfaceDecl *IFace;
5131  if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
5132  IFace = CatDecl->getClassInterface();
5133  else
5134  IFace = cast<ObjCInterfaceDecl>(Ctx);
5135 
5136  if (!IFace)
5137  return;
5138 
5140  D->addAttr(::new (S.Context)
5141  ObjCDesignatedInitializerAttr(AL.getRange(), S.Context,
5143 }
5144 
5145 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
5146  StringRef MetaDataName;
5147  if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
5148  return;
5149  D->addAttr(::new (S.Context)
5150  ObjCRuntimeNameAttr(AL.getRange(), S.Context,
5151  MetaDataName,
5153 }
5154 
5155 // When a user wants to use objc_boxable with a union or struct
5156 // but they don't have access to the declaration (legacy/third-party code)
5157 // then they can 'enable' this feature with a typedef:
5158 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5159 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
5160  bool notify = false;
5161 
5162  auto *RD = dyn_cast<RecordDecl>(D);
5163  if (RD && RD->getDefinition()) {
5164  RD = RD->getDefinition();
5165  notify = true;
5166  }
5167 
5168  if (RD) {
5169  ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
5170  ObjCBoxableAttr(AL.getRange(), S.Context,
5172  RD->addAttr(BoxableAttr);
5173  if (notify) {
5174  // we need to notify ASTReader/ASTWriter about
5175  // modification of existing declaration
5177  L->AddedAttributeToRecord(BoxableAttr, RD);
5178  }
5179  }
5180 }
5181 
5182 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5183  if (hasDeclarator(D)) return;
5184 
5185  S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
5186  << AL.getRange() << AL << ExpectedVariable;
5187 }
5188 
5189 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5190  const ParsedAttr &AL) {
5191  const auto *VD = cast<ValueDecl>(D);
5192  QualType QT = VD->getType();
5193 
5194  if (!QT->isDependentType() &&
5195  !QT->isObjCLifetimeType()) {
5196  S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5197  << QT;
5198  return;
5199  }
5200 
5201  Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
5202 
5203  // If we have no lifetime yet, check the lifetime we're presumably
5204  // going to infer.
5205  if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
5206  Lifetime = QT->getObjCARCImplicitLifetime();
5207 
5208  switch (Lifetime) {
5209  case Qualifiers::OCL_None:
5210  assert(QT->isDependentType() &&
5211  "didn't infer lifetime for non-dependent type?");
5212  break;
5213 
5214  case Qualifiers::OCL_Weak: // meaningful
5215  case Qualifiers::OCL_Strong: // meaningful
5216  break;
5217 
5220  S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5221  << (Lifetime == Qualifiers::OCL_Autoreleasing);
5222  break;
5223  }
5224 
5225  D->addAttr(::new (S.Context)
5226  ObjCPreciseLifetimeAttr(AL.getRange(), S.Context,
5228 }
5229 
5230 //===----------------------------------------------------------------------===//
5231 // Microsoft specific attribute handlers.
5232 //===----------------------------------------------------------------------===//
5233 
5234 UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
5235  unsigned AttrSpellingListIndex, StringRef Uuid) {
5236  if (const auto *UA = D->getAttr<UuidAttr>()) {
5237  if (UA->getGuid().equals_lower(Uuid))
5238  return nullptr;
5239  Diag(UA->getLocation(), diag::err_mismatched_uuid);
5240  Diag(Range.getBegin(), diag::note_previous_uuid);
5241  D->dropAttr<UuidAttr>();
5242  }
5243 
5244  return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5245 }
5246 
5247 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5248  if (!S.LangOpts.CPlusPlus) {
5249  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5250  << AL << AttributeLangSupport::C;
5251  return;
5252  }
5253 
5254  StringRef StrRef;
5255  SourceLocation LiteralLoc;
5256  if (!S.checkStringLiteralArgumentAttr(AL, 0, StrRef, &LiteralLoc))
5257  return;
5258 
5259  // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5260  // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5261  if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5262  StrRef = StrRef.drop_front().drop_back();
5263 
5264  // Validate GUID length.
5265  if (StrRef.size() != 36) {
5266  S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5267  return;
5268  }
5269 
5270  for (unsigned i = 0; i < 36; ++i) {
5271  if (i == 8 || i == 13 || i == 18 || i == 23) {
5272  if (StrRef[i] != '-') {
5273  S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5274  return;
5275  }
5276  } else if (!isHexDigit(StrRef[i])) {
5277  S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5278  return;
5279  }
5280  }
5281 
5282  // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5283  // the only thing in the [] list, the [] too), and add an insertion of
5284  // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
5285  // separating attributes nor of the [ and the ] are in the AST.
5286  // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
5287  // on cfe-dev.
5288  if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5289  S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
5290 
5291  UuidAttr *UA = S.mergeUuidAttr(D, AL.getRange(),
5292  AL.getAttributeSpellingListIndex(), StrRef);
5293  if (UA)
5294  D->addAttr(UA);
5295 }
5296 
5297 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5298  if (!S.LangOpts.CPlusPlus) {
5299  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5300  << AL << AttributeLangSupport::C;
5301  return;
5302  }
5303  MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5304  D, AL.getRange(), /*BestCase=*/true,
5306  (MSInheritanceAttr::Spelling)AL.getSemanticSpelling());
5307  if (IA) {
5308  D->addAttr(IA);
5309  S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5310  }
5311 }
5312 
5313 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5314  const auto *VD = cast<VarDecl>(D);
5315  if (!S.Context.getTargetInfo().isTLSSupported()) {
5316  S.Diag(AL.getLoc(), diag::err_thread_unsupported);
5317  return;
5318  }
5319  if (VD->getTSCSpec() != TSCS_unspecified) {
5320  S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
5321  return;
5322  }
5323  if (VD->hasLocalStorage()) {
5324  S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5325  return;
5326  }
5327  D->addAttr(::new (S.Context) ThreadAttr(AL.getRange(), S.Context,
5329 }
5330 
5331 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5333  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5334  StringRef Tag;
5335  if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
5336  return;
5337  Tags.push_back(Tag);
5338  }
5339 
5340  if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5341  if (!NS->isInline()) {
5342  S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5343  return;
5344  }
5345  if (NS->isAnonymousNamespace()) {
5346  S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5347  return;
5348  }
5349  if (AL.getNumArgs() == 0)
5350  Tags.push_back(NS->getName());
5351  } else if (!checkAttributeAtLeastNumArgs(S, AL, 1))
5352  return;
5353 
5354  // Store tags sorted and without duplicates.
5355  llvm::sort(Tags);
5356  Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5357 
5358  D->addAttr(::new (S.Context)
5359  AbiTagAttr(AL.getRange(), S.Context, Tags.data(), Tags.size(),
5361 }
5362 
5363 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5364  // Check the attribute arguments.
5365  if (AL.getNumArgs() > 1) {
5366  S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5367  return;
5368  }
5369 
5370  StringRef Str;
5371  SourceLocation ArgLoc;
5372 
5373  if (AL.getNumArgs() == 0)
5374  Str = "";
5375  else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5376  return;
5377 
5378  ARMInterruptAttr::InterruptType Kind;
5379  if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5380  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
5381  << ArgLoc;
5382  return;
5383  }
5384 
5385  unsigned Index = AL.getAttributeSpellingListIndex();
5386  D->addAttr(::new (S.Context)
5387  ARMInterruptAttr(AL.getLoc(), S.Context, Kind, Index));
5388 }
5389 
5390 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5391  // MSP430 'interrupt' attribute is applied to
5392  // a function with no parameters and void return type.
5393  if (!isFunctionOrMethod(D)) {
5394  S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5395  << "'interrupt'" << ExpectedFunctionOrMethod;
5396  return;
5397  }
5398 
5399  if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5400  S.Diag(D->getLocation(), diag::warn_msp430_interrupt_attribute)
5401  << 0;
5402  return;
5403  }
5404 
5406  S.Diag(D->getLocation(), diag::warn_msp430_interrupt_attribute)
5407  << 1;
5408  return;
5409  }
5410 
5411  // The attribute takes one integer argument.
5412  if (!checkAttributeNumArgs(S, AL, 1))
5413  return;
5414 
5415  if (!AL.isArgExpr(0)) {
5416  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5418  return;
5419  }
5420 
5421  Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
5422  llvm::APSInt NumParams(32);
5423  if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5424  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5426  << NumParamsExpr->getSourceRange();
5427  return;
5428  }
5429  // The argument should be in range 0..63.
5430  unsigned Num = NumParams.getLimitedValue(255);
5431  if (Num > 63) {
5432  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5433  << AL << (int)NumParams.getSExtValue()
5434  << NumParamsExpr->getSourceRange();
5435  return;
5436  }
5437 
5438  D->addAttr(::new (S.Context)
5439  MSP430InterruptAttr(AL.getLoc(), S.Context, Num,
5441  D->addAttr(UsedAttr::CreateImplicit(S.Context));
5442 }
5443 
5444 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5445  // Only one optional argument permitted.
5446  if (AL.getNumArgs() > 1) {
5447  S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5448  return;
5449  }
5450 
5451  StringRef Str;
5452  SourceLocation ArgLoc;
5453 
5454  if (AL.getNumArgs() == 0)
5455  Str = "";
5456  else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5457  return;
5458 
5459  // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5460  // a) Must be a function.
5461  // b) Must have no parameters.
5462  // c) Must have the 'void' return type.
5463  // d) Cannot have the 'mips16' attribute, as that instruction set
5464  // lacks the 'eret' instruction.
5465  // e) The attribute itself must either have no argument or one of the
5466  // valid interrupt types, see [MipsInterruptDocs].
5467 
5468  if (!isFunctionOrMethod(D)) {
5469  S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5470  << "'interrupt'" << ExpectedFunctionOrMethod;
5471  return;
5472  }
5473 
5474  if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5475  S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5476  << 0;
5477  return;
5478  }
5479 
5481  S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5482  << 1;
5483  return;
5484  }
5485 
5486  if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
5487  return;
5488 
5489  MipsInterruptAttr::InterruptType Kind;
5490  if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5491  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5492  << AL << "'" + std::string(Str) + "'";
5493  return;
5494  }
5495 
5496  D->addAttr(::new (S.Context) MipsInterruptAttr(
5498 }
5499 
5500 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5501  // Semantic checks for a function with the 'interrupt' attribute.
5502  // a) Must be a function.
5503  // b) Must have the 'void' return type.
5504  // c) Must take 1 or 2 arguments.
5505  // d) The 1st argument must be a pointer.
5506  // e) The 2nd argument (if any) must be an unsigned integer.
5507  if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5509  cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5510  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5512  return;
5513  }
5514  // Interrupt handler must have void return type.
5517  diag::err_anyx86_interrupt_attribute)
5518  << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5519  ? 0
5520  : 1)
5521  << 0;
5522  return;
5523  }
5524  // Interrupt handler must have 1 or 2 parameters.
5525  unsigned NumParams = getFunctionOrMethodNumParams(D);
5526  if (NumParams < 1 || NumParams > 2) {
5527  S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
5528  << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5529  ? 0
5530  : 1)
5531  << 1;
5532  return;
5533  }
5534  // The first argument must be a pointer.
5536  S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5537  diag::err_anyx86_interrupt_attribute)
5538  << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5539  ? 0
5540  : 1)
5541  << 2;
5542  return;
5543  }
5544  // The second argument, if present, must be an unsigned integer.
5545  unsigned TypeSize =
5546  S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5547  ? 64
5548  : 32;
5549  if (NumParams == 2 &&
5550  (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5551  S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5552  S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5553  diag::err_anyx86_interrupt_attribute)
5554  << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5555  ? 0
5556  : 1)
5557  << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5558  return;
5559  }
5560  D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5562  D->addAttr(UsedAttr::CreateImplicit(S.Context));
5563 }
5564 
5565 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5566  if (!isFunctionOrMethod(D)) {
5567  S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5568  << "'interrupt'" << ExpectedFunction;
5569  return;
5570  }
5571 
5572  if (!checkAttributeNumArgs(S, AL, 0))
5573  return;
5574 
5575  handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
5576 }
5577 
5578 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5579  if (!isFunctionOrMethod(D)) {
5580  S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5581  << "'signal'" << ExpectedFunction;
5582  return;
5583  }
5584 
5585  if (!checkAttributeNumArgs(S, AL, 0))
5586  return;
5587 
5588  handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
5589 }
5590 
5591 static void handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5592  if (!isFunctionOrMethod(D)) {
5593  S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5594  << "'import_module'" << ExpectedFunction;
5595  return;
5596  }
5597 
5598  auto *FD = cast<FunctionDecl>(D);
5599  if (FD->isThisDeclarationADefinition()) {
5600  S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5601  return;
5602  }
5603 
5604  StringRef Str;
5605  SourceLocation ArgLoc;
5606  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5607  return;
5608 
5609  FD->addAttr(::new (S.Context) WebAssemblyImportModuleAttr(
5610  AL.getRange(), S.Context, Str,
5612 }
5613 
5614 static void handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5615  if (!isFunctionOrMethod(D)) {
5616  S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5617  << "'import_name'" << ExpectedFunction;
5618  return;
5619  }
5620 
5621  auto *FD = cast<FunctionDecl>(D);
5622  if (FD->isThisDeclarationADefinition()) {
5623  S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5624  return;
5625  }
5626 
5627  StringRef Str;
5628  SourceLocation ArgLoc;
5629  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5630  return;
5631 
5632  FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(
5633  AL.getRange(), S.Context, Str,
5635 }
5636 
5637 static void handleRISCVInterruptAttr(Sema &S, Decl *D,
5638  const ParsedAttr &AL) {
5639  // Warn about repeated attributes.
5640  if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
5641  S.Diag(AL.getRange().getBegin(),
5642  diag::warn_riscv_repeated_interrupt_attribute);
5643  S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
5644  return;
5645  }
5646 
5647  // Check the attribute argument. Argument is optional.
5648  if (!checkAttributeAtMostNumArgs(S, AL, 1))
5649  return;
5650 
5651  StringRef Str;
5652  SourceLocation ArgLoc;
5653 
5654  // 'machine'is the default interrupt mode.
5655  if (AL.getNumArgs() == 0)
5656  Str = "machine";
5657  else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5658  return;
5659 
5660  // Semantic checks for a function with the 'interrupt' attribute:
5661  // - Must be a function.
5662  // - Must have no parameters.
5663  // - Must have the 'void' return type.
5664  // - The attribute itself must either have no argument or one of the
5665  // valid interrupt types, see [RISCVInterruptDocs].
5666 
5667  if (D->getFunctionType() == nullptr) {
5668  S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5669  << "'interrupt'" << ExpectedFunction;
5670  return;
5671  }
5672 
5673  if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5674  S.Diag(D->getLocation(), diag::warn_riscv_interrupt_attribute) << 0;
5675  return;
5676  }
5677 
5679  S.Diag(D->getLocation(), diag::warn_riscv_interrupt_attribute) << 1;
5680  return;
5681  }
5682 
5683  RISCVInterruptAttr::InterruptType Kind;
5684  if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5685  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
5686  << ArgLoc;
5687  return;
5688  }
5689 
5690  D->addAttr(::new (S.Context) RISCVInterruptAttr(
5692 }
5693 
5694 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5695  // Dispatch the interrupt attribute based on the current target.
5696  switch (S.Context.getTargetInfo().getTriple().getArch()) {
5697  case llvm::Triple::msp430:
5698  handleMSP430InterruptAttr(S, D, AL);
5699  break;
5700  case llvm::Triple::mipsel:
5701  case llvm::Triple::mips:
5702  handleMipsInterruptAttr(S, D, AL);
5703  break;
5704  case llvm::Triple::x86:
5705  case llvm::Triple::x86_64:
5706  handleAnyX86InterruptAttr(S, D, AL);
5707  break;
5708  case llvm::Triple::avr:
5709  handleAVRInterruptAttr(S, D, AL);
5710  break;
5711  case llvm::Triple::riscv32:
5712  case llvm::Triple::riscv64:
5713  handleRISCVInterruptAttr(S, D, AL);
5714  break;
5715  default:
5716  handleARMInterruptAttr(S, D, AL);
5717  break;
5718  }
5719 }
5720 
5721 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5722  const ParsedAttr &AL) {
5723  uint32_t Min = 0;
5724  Expr *MinExpr = AL.getArgAsExpr(0);
5725  if (!checkUInt32Argument(S, AL, MinExpr, Min))
5726  return;
5727 
5728  uint32_t Max = 0;
5729  Expr *MaxExpr = AL.getArgAsExpr(1);
5730  if (!checkUInt32Argument(S, AL, MaxExpr, Max))
5731  return;
5732 
5733  if (Min == 0 && Max != 0) {
5734  S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 0;
5735  return;
5736  }
5737  if (Min > Max) {
5738  S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 1;
5739  return;
5740  }
5741 
5742  D->addAttr(::new (S.Context)
5743  AMDGPUFlatWorkGroupSizeAttr(AL.getLoc(), S.Context, Min, Max,
5745 }
5746 
5747 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5748  uint32_t Min = 0;
5749  Expr *MinExpr = AL.getArgAsExpr(0);
5750  if (!checkUInt32Argument(S, AL, MinExpr, Min))
5751  return;
5752 
5753  uint32_t Max = 0;
5754  if (AL.getNumArgs() == 2) {
5755  Expr *MaxExpr = AL.getArgAsExpr(1);
5756  if (!checkUInt32Argument(S, AL, MaxExpr, Max))
5757  return;
5758  }
5759 
5760  if (Min == 0 && Max != 0) {
5761  S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 0;
5762  return;
5763  }
5764  if (Max != 0 && Min > Max) {
5765  S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 1;
5766  return;
5767  }
5768 
5769  D->addAttr(::new (S.Context)
5770  AMDGPUWavesPerEUAttr(AL.getLoc(), S.Context, Min, Max,
5772 }
5773 
5774 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5775  uint32_t NumSGPR = 0;
5776  Expr *NumSGPRExpr = AL.getArgAsExpr(0);
5777  if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
5778  return;
5779 
5780  D->addAttr(::new (S.Context)
5781  AMDGPUNumSGPRAttr(AL.getLoc(), S.Context, NumSGPR,
5783 }
5784 
5785 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5786  uint32_t NumVGPR = 0;
5787  Expr *NumVGPRExpr = AL.getArgAsExpr(0);
5788  if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
5789  return;
5790 
5791  D->addAttr(::new (S.Context)
5792  AMDGPUNumVGPRAttr(AL.getLoc(), S.Context, NumVGPR,
5794 }
5795 
5796 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5797  const ParsedAttr &AL) {
5798  // If we try to apply it to a function pointer, don't warn, but don't
5799  // do anything, either. It doesn't matter anyway, because there's nothing
5800  // special about calling a force_align_arg_pointer function.
5801  const auto *VD = dyn_cast<ValueDecl>(D);
5802  if (VD && VD->getType()->isFunctionPointerType())
5803  return;
5804  // Also don't warn on function pointer typedefs.
5805  const auto *TD = dyn_cast<TypedefNameDecl>(D);
5806  if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5807  TD->getUnderlyingType()->isFunctionType()))
5808  return;
5809  // Attribute can only be applied to function types.
5810  if (!isa<FunctionDecl>(D)) {
5811  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5812  << AL << ExpectedFunction;
5813  return;
5814  }
5815 
5816  D->addAttr(::new (S.Context)
5817  X86ForceAlignArgPointerAttr(AL.getRange(), S.Context,
5819 }
5820 
5821 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
5822  uint32_t Version;
5823  Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
5824  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
5825  return;
5826 
5827  // TODO: Investigate what happens with the next major version of MSVC.
5828  if (Version != LangOptions::MSVC2015 / 100) {
5829  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5830  << AL << Version << VersionExpr->getSourceRange();
5831  return;
5832  }
5833 
5834  // The attribute expects a "major" version number like 19, but new versions of
5835  // MSVC have moved to updating the "minor", or less significant numbers, so we
5836  // have to multiply by 100 now.
5837  Version *= 100;
5838 
5839  D->addAttr(::new (S.Context)
5840  LayoutVersionAttr(AL.getRange(), S.Context, Version,
5842 }
5843 
5844 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5845  unsigned AttrSpellingListIndex) {
5846  if (D->hasAttr<DLLExportAttr>()) {
5847  Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
5848  return nullptr;
5849  }
5850 
5851  if (D->hasAttr<DLLImportAttr>())
5852  return nullptr;
5853 
5854  return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
5855 }
5856 
5857 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5858  unsigned AttrSpellingListIndex) {
5859  if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
5860  Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
5861  D->dropAttr<DLLImportAttr>();
5862  }
5863 
5864  if (D->hasAttr<DLLExportAttr>())
5865  return nullptr;
5866 
5867  return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
5868 }
5869 
5870 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
5871  if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5873  S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
5874  return;
5875  }
5876 
5877  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5878  if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
5880  // MinGW doesn't allow dllimport on inline functions.
5881  S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5882  << A;
5883  return;
5884  }
5885  }
5886 
5887  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5889  MD->getParent()->isLambda()) {
5890  S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
5891  return;
5892  }
5893  }
5894 
5895  unsigned Index = A.getAttributeSpellingListIndex();
5896  Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
5897  ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5898  : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
5899  if (NewAttr)
5900  D->addAttr(NewAttr);
5901 }
5902 
5903 MSInheritanceAttr *
5904 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
5905  unsigned AttrSpellingListIndex,
5906  MSInheritanceAttr::Spelling SemanticSpelling) {
5907  if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5908  if (IA->getSemanticSpelling() == SemanticSpelling)
5909  return nullptr;
5910  Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5911  << 1 /*previous declaration*/;
5912  Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5913  D->dropAttr<MSInheritanceAttr>();
5914  }
5915 
5916  auto *RD = cast<CXXRecordDecl>(D);
5917  if (RD->hasDefinition()) {
5918  if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5919  SemanticSpelling)) {
5920  return nullptr;
5921  }
5922  } else {
5923  if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5924  Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5925  << 1 /*partial specialization*/;
5926  return nullptr;
5927  }
5928  if (RD->getDescribedClassTemplate()) {
5929  Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5930  << 0 /*primary template*/;
5931  return nullptr;
5932  }
5933  }
5934 
5935  return ::new (Context)
5936  MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
5937 }
5938 
5939 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5940  // The capability attributes take a single string parameter for the name of
5941  // the capability they represent. The lockable attribute does not take any
5942  // parameters. However, semantically, both attributes represent the same
5943  // concept, and so they use the same semantic attribute. Eventually, the
5944  // lockable attribute will be removed.
5945  //
5946  // For backward compatibility, any capability which has no specified string
5947  // literal will be considered a "mutex."
5948  StringRef N("mutex");
5949  SourceLocation LiteralLoc;
5950  if (AL.getKind() == ParsedAttr::AT_Capability &&
5951  !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
5952  return;
5953 
5954  // Currently, there are only two names allowed for a capability: role and
5955  // mutex (case insensitive). Diagnose other capability names.
5956  if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5957  S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5958 
5959  D->addAttr(::new (S.Context) CapabilityAttr(AL.getRange(), S.Context, N,
5961 }
5962 
5963 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5964  SmallVector<Expr*, 1> Args;
5965  if (!checkLockFunAttrCommon(S, D, AL, Args))
5966  return;
5967 
5968  D->addAttr(::new (S.Context) AssertCapabilityAttr(AL.getRange(), S.Context,
5969  Args.data(), Args.size(),
5971 }
5972 
5973 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5974  const ParsedAttr &AL) {
5975  SmallVector<Expr*, 1> Args;
5976  if (!checkLockFunAttrCommon(S, D, AL, Args))
5977  return;
5978 
5979  D->addAttr(::new (S.Context) AcquireCapabilityAttr(AL.getRange(),
5980  S.Context,
5981  Args.data(), Args.size(),
5983 }
5984 
5985 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5986  const ParsedAttr &AL) {
5987  SmallVector<Expr*, 2> Args;
5988  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
5989  return;
5990 
5991  D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(AL.getRange(),
5992  S.Context,
5993  AL.getArgAsExpr(0),
5994  Args.data(),
5995  Args.size(),
5997 }
5998 
5999 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
6000  const ParsedAttr &AL) {
6001  // Check that all arguments are lockable objects.
6003  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
6004 
6005  D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
6006  AL.getRange(), S.Context, Args.data(), Args.size(),
6008 }
6009 
6010 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
6011  const ParsedAttr &AL) {
6012  if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6013  return;
6014 
6015  // check that all arguments are lockable objects
6016  SmallVector<Expr*, 1> Args;
6017  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
6018  if (Args.empty())
6019  return;
6020 
6021  RequiresCapabilityAttr *RCA = ::new (S.Context)
6022  RequiresCapabilityAttr(AL.getRange(), S.Context, Args.data(),
6023  Args.size(), AL.getAttributeSpellingListIndex());
6024 
6025  D->addAttr(RCA);
6026 }
6027 
6028 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6029  if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
6030  if (NSD->isAnonymousNamespace()) {
6031  S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
6032  // Do not want to attach the attribute to the namespace because that will
6033  // cause confusing diagnostic reports for uses of declarations within the
6034  // namespace.
6035  return;
6036  }
6037  }
6038 
6039  // Handle the cases where the attribute has a text message.
6040  StringRef Str, Replacement;
6041  if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
6042  !S.checkStringLiteralArgumentAttr(AL, 0, Str))
6043  return;
6044 
6045  // Only support a single optional message for Declspec and CXX11.
6046  if (AL.isDeclspecAttribute() || AL.isCXX11Attribute())
6047  checkAttributeAtMostNumArgs(S, AL, 1);
6048  else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
6049  !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
6050  return;
6051 
6052  if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
6053  S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
6054 
6055  D->addAttr(::new (S.Context)
6056  DeprecatedAttr(AL.getRange(), S.Context, Str, Replacement,
6058 }
6059 
6060 static bool isGlobalVar(const Decl *D) {
6061  if (const auto *S = dyn_cast<VarDecl>(D))
6062  return S->hasGlobalStorage();
6063  return false;
6064 }
6065 
6066 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6067  if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6068  return;
6069 
6070  std::vector<StringRef> Sanitizers;
6071 
6072  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
6073  StringRef SanitizerName;
6074  SourceLocation LiteralLoc;
6075 
6076  if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
6077  return;
6078 
6079  if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
6080  S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
6081  else if (isGlobalVar(D) && SanitizerName != "address")
6082  S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6083  << AL << ExpectedFunctionOrMethod;
6084  Sanitizers.push_back(SanitizerName);
6085  }
6086 
6087  D->addAttr(::new (S.Context) NoSanitizeAttr(
6088  AL.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
6090 }
6091 
6092 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
6093  const ParsedAttr &AL) {
6094  StringRef AttrName = AL.getName()->getName();
6095  normalizeName(AttrName);
6096  StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
6097  .Case("no_address_safety_analysis", "address")
6098  .Case("no_sanitize_address", "address")
6099  .Case("no_sanitize_thread", "thread")
6100  .Case("no_sanitize_memory", "memory");
6101  if (isGlobalVar(D) && SanitizerName != "address")
6102  S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6103  << AL << ExpectedFunction;
6104  D->addAttr(::new (S.Context)
6105  NoSanitizeAttr(AL.getRange(), S.Context, &SanitizerName, 1,
6107 }
6108 
6109 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6110  if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
6111  D->addAttr(Internal);
6112 }
6113 
6114 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6115  if (S.LangOpts.OpenCLVersion != 200)
6116  S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
6117  << AL << "2.0" << 0;
6118  else
6119  S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) << AL
6120  << "2.0";
6121 }
6122 
6123 /// Handles semantic checking for features that are common to all attributes,
6124 /// such as checking whether a parameter was properly specified, or the correct
6125 /// number of arguments were passed, etc.
6126 static bool handleCommonAttributeFeatures(Sema &S, Decl *D,
6127  const ParsedAttr &AL) {
6128  // Several attributes carry different semantics than the parsing requires, so
6129  // those are opted out of the common argument checks.
6130  //
6131  // We also bail on unknown and ignored attributes because those are handled
6132  // as part of the target-specific handling logic.
6134  return false;
6135  // Check whether the attribute requires specific language extensions to be
6136  // enabled.
6137  if (!AL.diagnoseLangOpts(S))
6138  return true;
6139  // Check whether the attribute appertains to the given subject.
6140  if (!AL.diagnoseAppertainsTo(S, D))
6141  return true;
6142  if (AL.hasCustomParsing())
6143  return false;
6144 
6145  if (AL.getMinArgs() == AL.getMaxArgs()) {
6146  // If there are no optional arguments, then checking for the argument count
6147  // is trivial.
6148  if (!checkAttributeNumArgs(S, AL, AL.getMinArgs()))
6149  return true;
6150  } else {
6151  // There are optional arguments, so checking is slightly more involved.
6152  if (AL.getMinArgs() &&
6154  return true;
6155  else if (!AL.hasVariadicArg() && AL.getMaxArgs() &&
6157  return true;
6158  }
6159 
6160  if (S.CheckAttrTarget(AL))
6161  return true;
6162 
6163  return false;
6164 }
6165 
6166 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6167  if (D->isInvalidDecl())
6168  return;
6169 
6170  // Check if there is only one access qualifier.
6171  if (D->hasAttr<OpenCLAccessAttr>()) {
6172  if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
6173  AL.getSemanticSpelling()) {
6174  S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
6175  << AL.getName()->getName() << AL.getRange();
6176  } else {
6177  S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
6178  << D->getSourceRange();
6179  D->setInvalidDecl(true);
6180  return;
6181  }
6182  }
6183 
6184  // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
6185  // image object can be read and written.
6186  // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
6187  // object. Using the read_write (or __read_write) qualifier with the pipe
6188  // qualifier is a compilation error.
6189  if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
6190  const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
6191  if (AL.getName()->getName().find("read_write") != StringRef::npos) {
6192  if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
6193  S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
6194  << AL << PDecl->getType() << DeclTy->isImageType();
6195  D->setInvalidDecl(true);
6196  return;
6197  }
6198  }
6199  }
6200 
6201  D->addAttr(::new (S.Context) OpenCLAccessAttr(
6203 }
6204 
6205 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
6206  if (!cast<VarDecl>(D)->hasGlobalStorage()) {
6207  S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
6208  << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
6209  return;
6210  }
6211 
6212  if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
6213  handleSimpleAttributeWithExclusions<AlwaysDestroyAttr, NoDestroyAttr>(S, D, A);
6214  else
6215  handleSimpleAttributeWithExclusions<NoDestroyAttr, AlwaysDestroyAttr>(S, D, A);
6216 }
6217 
6218 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6219  assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
6220  "uninitialized is only valid on automatic duration variables");
6221  unsigned Index = AL.getAttributeSpellingListIndex();
6222  D->addAttr(::new (S.Context)
6223  UninitializedAttr(AL.getLoc(), S.Context, Index));
6224 }
6225 
6226 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
6227  bool DiagnoseFailure) {
6228  QualType Ty = VD->getType();
6229  if (!Ty->isObjCRetainableType()) {
6230  if (DiagnoseFailure) {
6231  S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6232  << 0;
6233  }
6234  return false;
6235  }
6236 
6238 
6239  // Sema::inferObjCARCLifetime must run after processing decl attributes
6240  // (because __block lowers to an attribute), so if the lifetime hasn't been
6241  // explicitly specified, infer it locally now.
6242  if (LifetimeQual == Qualifiers::OCL_None)
6243  LifetimeQual = Ty->getObjCARCImplicitLifetime();
6244 
6245  // The attributes only really makes sense for __strong variables; ignore any
6246  // attempts to annotate a parameter with any other lifetime qualifier.
6247  if (LifetimeQual != Qualifiers::OCL_Strong) {
6248  if (DiagnoseFailure) {
6249  S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6250  << 1;
6251  }
6252  return false;
6253  }
6254 
6255  // Tampering with the type of a VarDecl here is a bit of a hack, but we need
6256  // to ensure that the variable is 'const' so that we can error on
6257  // modification, which can otherwise over-release.
6258  VD->setType(Ty.withConst());
6259  VD->setARCPseudoStrong(true);
6260  return true;
6261 }
6262 
6263 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
6264  const ParsedAttr &AL) {
6265  if (auto *VD = dyn_cast<VarDecl>(D)) {
6266  assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
6267  if (!VD->hasLocalStorage()) {
6268  S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6269  << 0;
6270  return;
6271  }
6272 
6273  if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
6274  return;
6275 
6276  handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6277  return;
6278  }
6279 
6280  // If D is a function-like declaration (method, block, or function), then we
6281  // make every parameter psuedo-strong.
6282  for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
6283  auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
6284  QualType Ty = PVD->getType();
6285 
6286  // If a user wrote a parameter with __strong explicitly, then assume they
6287  // want "real" strong semantics for that parameter. This works because if
6288  // the parameter was written with __strong, then the strong qualifier will
6289  // be non-local.
6292  continue;
6293 
6294  tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
6295  }
6296  handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6297 }
6298 
6299 //===----------------------------------------------------------------------===//
6300 // Top Level Sema Entry Points
6301 //===----------------------------------------------------------------------===//
6302 
6303 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
6304 /// the attribute applies to decls. If the attribute is a type attribute, just
6305 /// silently ignore it if a GNU attribute.
6306 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
6307  const ParsedAttr &AL,
6308  bool IncludeCXX11Attributes) {
6309  if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
6310  return;
6311 
6312  // Ignore C++11 attributes on declarator chunks: they appertain to the type
6313  // instead.
6314  if (AL.isCXX11Attribute() && !IncludeCXX11Attributes)
6315  return;
6316 
6317  // Unknown attributes are automatically warned on. Target-specific attributes
6318  // which do not apply to the current target architecture are treated as
6319  // though they were unknown attributes.
6320  if (AL.getKind() == ParsedAttr::UnknownAttribute ||
6322  S.Diag(AL.getLoc(),
6323  AL.isDeclspecAttribute()
6324  ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
6325  : (unsigned)diag::warn_unknown_attribute_ignored)
6326  << AL;
6327  return;
6328  }
6329 
6330  if (handleCommonAttributeFeatures(S, D, AL))
6331  return;
6332 
6333  switch (AL.getKind()) {
6334  default:
6335  if (!AL.isStmtAttr()) {
6336  // Type attributes are handled elsewhere; silently move on.
6337  assert(AL.isTypeAttr() && "Non-type attribute not handled");
6338  break;
6339  }
6340  S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
6341  << AL << D->getLocation();
6342  break;
6343  case ParsedAttr::AT_Interrupt:
6344  handleInterruptAttr(S, D, AL);
6345  break;
6346  case ParsedAttr::AT_X86ForceAlignArgPointer:
6347  handleX86ForceAlignArgPointerAttr(S, D, AL);
6348  break;
6349  case ParsedAttr::AT_DLLExport:
6350  case ParsedAttr::AT_DLLImport:
6351  handleDLLAttr(S, D, AL);
6352  break;
6353  case ParsedAttr::AT_Mips16:
6354  handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
6355  MipsInterruptAttr>(S, D, AL);
6356  break;
6357  case ParsedAttr::AT_NoMips16:
6358  handleSimpleAttribute<NoMips16Attr>(S, D, AL);
6359  break;
6360  case ParsedAttr::AT_MicroMips:
6361  handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, AL);
6362  break;
6363  case ParsedAttr::AT_NoMicroMips:
6364  handleSimpleAttribute<NoMicroMipsAttr>(S, D, AL);
6365  break;
6366  case ParsedAttr::AT_MipsLongCall:
6367  handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>(
6368  S, D, AL);
6369  break;
6370  case ParsedAttr::AT_MipsShortCall:
6371  handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>(
6372  S, D, AL);
6373  break;
6374  case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
6375  handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
6376  break;
6377  case ParsedAttr::AT_AMDGPUWavesPerEU:
6378  handleAMDGPUWavesPerEUAttr(S, D, AL);
6379  break;
6380  case ParsedAttr::AT_AMDGPUNumSGPR:
6381  handleAMDGPUNumSGPRAttr(S, D, AL);
6382  break;
6383  case ParsedAttr::AT_AMDGPUNumVGPR:
6384  handleAMDGPUNumVGPRAttr(S, D, AL);
6385  break;
6386  case ParsedAttr::AT_AVRSignal:
6387  handleAVRSignalAttr(S, D, AL);
6388  break;
6389  case ParsedAttr::AT_WebAssemblyImportModule:
6390  handleWebAssemblyImportModuleAttr(S, D, AL);
6391  break;
6392  case ParsedAttr::AT_WebAssemblyImportName:
6393  handleWebAssemblyImportNameAttr(S, D, AL);
6394  break;
6395  case ParsedAttr::AT_IBAction:
6396  handleSimpleAttribute<IBActionAttr>(S, D, AL);
6397  break;
6398  case ParsedAttr::AT_IBOutlet:
6399  handleIBOutlet(S, D, AL);
6400  break;
6401  case ParsedAttr::AT_IBOutletCollection:
6402  handleIBOutletCollection(S, D, AL);
6403  break;
6404  case ParsedAttr::AT_IFunc:
6405  handleIFuncAttr(S, D, AL);
6406  break;
6407  case ParsedAttr::AT_Alias:
6408  handleAliasAttr(S, D, AL);
6409  break;
6410  case ParsedAttr::AT_Aligned:
6411  handleAlignedAttr(S, D, AL);
6412  break;
6413  case ParsedAttr::AT_AlignValue:
6414  handleAlignValueAttr(S, D, AL);
6415  break;
6416  case ParsedAttr::AT_AllocSize:
6417  handleAllocSizeAttr(S, D, AL);
6418  break;
6419  case ParsedAttr::AT_AlwaysInline:
6420  handleAlwaysInlineAttr(S, D, AL);
6421  break;
6422  case ParsedAttr::AT_Artificial:
6423  handleSimpleAttribute<ArtificialAttr>(S, D, AL);
6424  break;
6425  case ParsedAttr::AT_AnalyzerNoReturn:
6426  handleAnalyzerNoReturnAttr(S, D, AL);
6427  break;
6428  case ParsedAttr::AT_TLSModel:
6429  handleTLSModelAttr(S, D, AL);
6430  break;
6431  case ParsedAttr::AT_Annotate:
6432  handleAnnotateAttr(S, D, AL);
6433  break;
6434  case ParsedAttr::AT_Availability:
6435  handleAvailabilityAttr(S, D, AL);
6436  break;
6437  case ParsedAttr::AT_CarriesDependency:
6438  handleDependencyAttr(S, scope, D, AL);
6439  break;
6440  case ParsedAttr::AT_CPUDispatch:
6441  case ParsedAttr::AT_CPUSpecific:
6442  handleCPUSpecificAttr(S, D, AL);
6443  break;
6444  case ParsedAttr::AT_Common:
6445  handleCommonAttr(S, D, AL);
6446  break;
6447  case ParsedAttr::AT_CUDAConstant:
6448  handleConstantAttr(S, D, AL);
6449  break;
6450  case ParsedAttr::AT_PassObjectSize:
6451  handlePassObjectSizeAttr(S, D, AL);
6452  break;
6453  case ParsedAttr::AT_Constructor:
6454  handleConstructorAttr(S, D, AL);
6455  break;
6456  case ParsedAttr::AT_CXX11NoReturn:
6457  handleSimpleAttribute<CXX11NoReturnAttr>(S, D, AL);
6458  break;
6459  case ParsedAttr::AT_Deprecated:
6460  handleDeprecatedAttr(S, D, AL);
6461  break;
6462  case ParsedAttr::AT_Destructor:
6463  handleDestructorAttr(S, D, AL);
6464  break;
6465  case ParsedAttr::AT_EnableIf:
6466  handleEnableIfAttr(S, D, AL);
6467  break;
6468  case ParsedAttr::AT_DiagnoseIf:
6469  handleDiagnoseIfAttr(S, D, AL);
6470  break;
6471  case ParsedAttr::AT_ExtVectorType:
6472  handleExtVectorTypeAttr(S, D, AL);
6473  break;
6474  case ParsedAttr::AT_ExternalSourceSymbol:
6475  handleExternalSourceSymbolAttr(S, D, AL);
6476  break;
6477  case ParsedAttr::AT_MinSize:
6478  handleMinSizeAttr(S, D, AL);
6479  break;
6480  case ParsedAttr::AT_OptimizeNone:
6481  handleOptimizeNoneAttr(S, D, AL);
6482  break;
6483  case ParsedAttr::AT_FlagEnum:
6484  handleSimpleAttribute<FlagEnumAttr>(S, D, AL);
6485  break;
6486  case ParsedAttr::AT_EnumExtensibility:
6487  handleEnumExtensibilityAttr(S, D, AL);
6488  break;
6489  case ParsedAttr::AT_Flatten:
6490  handleSimpleAttribute<FlattenAttr>(S, D, AL);
6491  break;
6492  case ParsedAttr::AT_Format:
6493  handleFormatAttr(S, D, AL);
6494  break;
6495  case ParsedAttr::AT_FormatArg:
6496  handleFormatArgAttr(S, D, AL);
6497  break;
6498  case ParsedAttr::AT_CUDAGlobal:
6499  handleGlobalAttr(S, D, AL);
6500  break;
6501  case ParsedAttr::AT_CUDADevice:
6502  handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6503  AL);
6504  break;
6505  case ParsedAttr::AT_CUDAHost:
6506  handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, AL);
6507  break;
6508  case ParsedAttr::AT_GNUInline:
6509  handleGNUInlineAttr(S, D, AL);
6510  break;
6511  case ParsedAttr::AT_CUDALaunchBounds:
6512  handleLaunchBoundsAttr(S, D, AL);
6513  break;
6514  case ParsedAttr::AT_Restrict:
6515  handleRestrictAttr(S, D, AL);
6516  break;
6517  case ParsedAttr::AT_LifetimeBound:
6518  handleSimpleAttribute<LifetimeBoundAttr>(S, D, AL);
6519  break;
6520  case ParsedAttr::AT_MayAlias:
6521  handleSimpleAttribute<MayAliasAttr>(S, D, AL);
6522  break;
6523  case ParsedAttr::AT_Mode:
6524  handleModeAttr(S, D, AL);
6525  break;
6526  case ParsedAttr::AT_NoAlias:
6527  handleSimpleAttribute<NoAliasAttr>(S, D, AL);
6528  break;
6529  case ParsedAttr::AT_NoCommon:
6530  handleSimpleAttribute<NoCommonAttr>(S, D, AL);
6531  break;
6532  case ParsedAttr::AT_NoSplitStack:
6533  handleSimpleAttribute<NoSplitStackAttr>(S, D, AL);
6534  break;
6535  case ParsedAttr::AT_NonNull:
6536  if (auto *PVD = dyn_cast<ParmVarDecl>(D))
6537  handleNonNullAttrParameter(S, PVD, AL);
6538  else
6539  handleNonNullAttr(S, D, AL);
6540  break;
6541  case ParsedAttr::AT_ReturnsNonNull:
6542  handleReturnsNonNullAttr(S, D, AL);
6543  break;
6544  case ParsedAttr::AT_NoEscape:
6545  handleNoEscapeAttr(S, D, AL);
6546  break;
6547  case ParsedAttr::AT_AssumeAligned:
6548  handleAssumeAlignedAttr(S, D, AL);
6549  break;
6550  case ParsedAttr::AT_AllocAlign:
6551  handleAllocAlignAttr(S, D, AL);
6552  break;
6553  case ParsedAttr::AT_Overloadable:
6554  handleSimpleAttribute<OverloadableAttr>(S, D, AL);
6555  break;
6556  case ParsedAttr::AT_Ownership:
6557  handleOwnershipAttr(S, D, AL);
6558  break;
6559  case ParsedAttr::AT_Cold:
6560  handleSimpleAttributeWithExclusions<ColdAttr, HotAttr>(S, D, AL);
6561  break;
6562  case ParsedAttr::AT_Hot:
6563  handleSimpleAttributeWithExclusions<HotAttr, ColdAttr>(S, D, AL);
6564  break;
6565  case ParsedAttr::AT_Naked:
6566  handleNakedAttr(S, D, AL);
6567  break;
6568  case ParsedAttr::AT_NoReturn:
6569  handleNoReturnAttr(S, D, AL);
6570  break;
6571  case ParsedAttr::AT_AnyX86NoCfCheck:
6572  handleNoCfCheckAttr(S, D, AL);
6573  break;
6574  case ParsedAttr::AT_NoThrow:
6575  handleSimpleAttribute<NoThrowAttr>(S, D, AL);
6576  break;
6577  case ParsedAttr::AT_CUDAShared:
6578  handleSharedAttr(S, D, AL);
6579  break;
6580  case ParsedAttr::AT_VecReturn:
6581  handleVecReturnAttr(S, D, AL);
6582  break;
6583  case ParsedAttr::AT_ObjCOwnership:
6584  handleObjCOwnershipAttr(S, D, AL);
6585  break;
6586  case ParsedAttr::AT_ObjCPreciseLifetime:
6587  handleObjCPreciseLifetimeAttr(S, D, AL);
6588  break;
6589  case ParsedAttr::AT_ObjCReturnsInnerPointer:
6590  handleObjCReturnsInnerPointerAttr(S, D, AL);
6591  break;
6592  case ParsedAttr::AT_ObjCRequiresSuper:
6593  handleObjCRequiresSuperAttr(S, D, AL);
6594  break;
6595  case ParsedAttr::AT_ObjCBridge:
6596  handleObjCBridgeAttr(S, D, AL);
6597  break;
6598  case ParsedAttr::AT_ObjCBridgeMutable:
6599  handleObjCBridgeMutableAttr(S, D, AL);
6600  break;
6601  case ParsedAttr::AT_ObjCBridgeRelated:
6602  handleObjCBridgeRelatedAttr(S, D, AL);
6603  break;
6604  case ParsedAttr::AT_ObjCDesignatedInitializer:
6605  handleObjCDesignatedInitializer(S, D, AL);
6606  break;
6607  case ParsedAttr::AT_ObjCRuntimeName:
6608  handleObjCRuntimeName(S, D, AL);
6609  break;
6610  case ParsedAttr::AT_ObjCRuntimeVisible:
6611  handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, AL);
6612  break;
6613  case ParsedAttr::AT_ObjCBoxable:
6614  handleObjCBoxable(S, D, AL);
6615  break;
6616  case ParsedAttr::AT_CFAuditedTransfer:
6617  handleSimpleAttributeWithExclusions<CFAuditedTransferAttr,
6618  CFUnknownTransferAttr>(S, D, AL);
6619  break;
6620  case ParsedAttr::AT_CFUnknownTransfer:
6621  handleSimpleAttributeWithExclusions<CFUnknownTransferAttr,
6622  CFAuditedTransferAttr>(S, D, AL);
6623  break;
6624  case ParsedAttr::AT_CFConsumed:
6625  case ParsedAttr::AT_NSConsumed:
6626  case ParsedAttr::AT_OSConsumed:
6627  S.AddXConsumedAttr(D, AL.getRange(), AL.getAttributeSpellingListIndex(),
6628  parsedAttrToRetainOwnershipKind(AL),
6629  /*IsTemplateInstantiation=*/false);
6630  break;
6631  case ParsedAttr::AT_NSConsumesSelf:
6632  handleSimpleAttribute<NSConsumesSelfAttr>(S, D, AL);
6633  break;
6634  case ParsedAttr::AT_OSConsumesThis:
6635  handleSimpleAttribute<OSConsumesThisAttr>(S, D, AL);
6636  break;
6637  case ParsedAttr::AT_OSReturnsRetainedOnZero:
6638  handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
6639  S, D, AL, isValidOSObjectOutParameter(D),
6640  diag::warn_ns_attribute_wrong_parameter_type,
6641  /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
6642  break;
6643  case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
6644  handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
6645  S, D, AL, isValidOSObjectOutParameter(D),
6646  diag::warn_ns_attribute_wrong_parameter_type,
6647  /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
6648  break;
6649  case ParsedAttr::AT_NSReturnsAutoreleased:
6650  case ParsedAttr::AT_NSReturnsNotRetained:
6651  case ParsedAttr::AT_NSReturnsRetained:
6652  case ParsedAttr::AT_CFReturnsNotRetained:
6653  case ParsedAttr::AT_CFReturnsRetained:
6654  case ParsedAttr::AT_OSReturnsNotRetained:
6655  case ParsedAttr::AT_OSReturnsRetained:
6656  handleXReturnsXRetainedAttr(S, D, AL);
6657  break;
6658  case ParsedAttr::AT_WorkGroupSizeHint:
6659  handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
6660  break;
6661  case ParsedAttr::AT_ReqdWorkGroupSize:
6662  handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
6663  break;
6664  case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
6665  handleSubGroupSize(S, D, AL);
6666  break;
6667  case ParsedAttr::AT_VecTypeHint:
6668  handleVecTypeHint(S, D, AL);
6669  break;
6670  case ParsedAttr::AT_RequireConstantInit:
6671  handleSimpleAttribute<RequireConstantInitAttr>(S, D, AL);
6672  break;
6673  case ParsedAttr::AT_InitPriority:
6674  handleInitPriorityAttr(S, D, AL);
6675  break;
6676  case ParsedAttr::AT_Packed:
6677  handlePackedAttr(S, D, AL);
6678  break;
6679  case ParsedAttr::AT_Section:
6680  handleSectionAttr(S, D, AL);
6681  break;
6682  case ParsedAttr::AT_SpeculativeLoadHardening:
6683  handleSimpleAttribute<SpeculativeLoadHardeningAttr>(S, D, AL);
6684  break;
6685  case ParsedAttr::AT_CodeSeg:
6686  handleCodeSegAttr(S, D, AL);
6687  break;
6688  case ParsedAttr::AT_Target:
6689  handleTargetAttr(S, D, AL);
6690  break;
6691  case ParsedAttr::AT_MinVectorWidth:
6692  handleMinVectorWidthAttr(S, D, AL);
6693  break;
6694  case ParsedAttr::AT_Unavailable:
6695  handleAttrWithMessage<UnavailableAttr>(S, D, AL);
6696  break;
6697  case ParsedAttr::AT_ArcWeakrefUnavailable:
6698  handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, AL);
6699  break;
6700  case ParsedAttr::AT_ObjCRootClass:
6701  handleSimpleAttribute<ObjCRootClassAttr>(S, D, AL);
6702  break;
6703  case ParsedAttr::AT_ObjCSubclassingRestricted:
6704  handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, AL);
6705  break;
6706  case ParsedAttr::AT_ObjCExplicitProtocolImpl:
6707  handleObjCSuppresProtocolAttr(S, D, AL);
6708  break;
6709  case ParsedAttr::AT_ObjCRequiresPropertyDefs:
6710  handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, AL);
6711  break;
6712  case ParsedAttr::AT_Unused:
6713  handleUnusedAttr(S, D, AL);
6714  break;
6715  case ParsedAttr::AT_ReturnsTwice:
6716  handleSimpleAttribute<ReturnsTwiceAttr>(S, D, AL);
6717  break;
6718  case ParsedAttr::AT_NotTailCalled:
6719  handleSimpleAttributeWithExclusions<NotTailCalledAttr, AlwaysInlineAttr>(
6720  S, D, AL);
6721  break;
6722  case ParsedAttr::AT_DisableTailCalls:
6723  handleSimpleAttributeWithExclusions<DisableTailCallsAttr, NakedAttr>(S, D,
6724  AL);
6725  break;
6726  case ParsedAttr::AT_Used:
6727  handleSimpleAttribute<UsedAttr>(S, D, AL);
6728  break;
6729  case ParsedAttr::AT_Visibility:
6730  handleVisibilityAttr(S, D, AL, false);
6731  break;
6732  case ParsedAttr::AT_TypeVisibility:
6733  handleVisibilityAttr(S, D, AL, true);
6734  break;
6735  case ParsedAttr::AT_WarnUnused:
6736  handleSimpleAttribute<WarnUnusedAttr>(S, D, AL);
6737  break;
6738  case ParsedAttr::AT_WarnUnusedResult:
6739  handleWarnUnusedResult(S, D, AL);
6740  break;
6741  case ParsedAttr::AT_Weak:
6742  handleSimpleAttribute<WeakAttr>(S, D, AL);
6743  break;
6744  case ParsedAttr::AT_WeakRef:
6745  handleWeakRefAttr(S, D, AL);
6746  break;
6747  case ParsedAttr::AT_WeakImport:
6748  handleWeakImportAttr(S, D, AL);
6749  break;
6750  case ParsedAttr::AT_TransparentUnion:
6751  handleTransparentUnionAttr(S, D, AL);
6752  break;
6753  case ParsedAttr::AT_ObjCException:
6754  handleSimpleAttribute<ObjCExceptionAttr>(S, D, AL);
6755  break;
6756  case ParsedAttr::AT_ObjCMethodFamily:
6757  handleObjCMethodFamilyAttr(S, D, AL);
6758  break;
6759  case ParsedAttr::AT_ObjCNSObject:
6760  handleObjCNSObject(S, D, AL);
6761  break;
6762  case ParsedAttr::AT_ObjCIndependentClass:
6763  handleObjCIndependentClass(S, D, AL);
6764  break;
6765  case ParsedAttr::AT_Blocks:
6766  handleBlocksAttr(S, D, AL);
6767  break;
6768  case ParsedAttr::AT_Sentinel:
6769  handleSentinelAttr(S, D, AL);
6770  break;
6771  case ParsedAttr::AT_Const:
6772  handleSimpleAttribute<ConstAttr>(S, D, AL);
6773  break;
6774  case ParsedAttr::AT_Pure:
6775  handleSimpleAttribute<PureAttr>(S, D, AL);
6776  break;
6777  case ParsedAttr::AT_Cleanup:
6778  handleCleanupAttr(S, D, AL);
6779  break;
6780  case ParsedAttr::AT_NoDebug:
6781  handleNoDebugAttr(S, D, AL);
6782  break;
6783  case ParsedAttr::AT_NoDuplicate:
6784  handleSimpleAttribute<NoDuplicateAttr>(S, D, AL);
6785  break;
6786  case ParsedAttr::AT_Convergent:
6787  handleSimpleAttribute<ConvergentAttr>(S, D, AL);
6788  break;
6789  case ParsedAttr::AT_NoInline:
6790  handleSimpleAttribute<NoInlineAttr>(S, D, AL);
6791  break;
6792  case ParsedAttr::AT_NoInstrumentFunction: // Interacts with -pg.
6793  handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, AL);
6794  break;
6795  case ParsedAttr::AT_NoStackProtector:
6796  // Interacts with -fstack-protector options.
6797  handleSimpleAttribute<NoStackProtectorAttr>(S, D, AL);
6798  break;
6799  case ParsedAttr::AT_StdCall:
6800  case ParsedAttr::AT_CDecl:
6801  case ParsedAttr::AT_FastCall:
6802  case ParsedAttr::AT_ThisCall:
6803  case ParsedAttr::AT_Pascal:
6804  case ParsedAttr::AT_RegCall:
6805  case ParsedAttr::AT_SwiftCall:
6806  case ParsedAttr::AT_VectorCall:
6807  case ParsedAttr::AT_MSABI:
6808  case ParsedAttr::AT_SysVABI:
6809  case ParsedAttr::AT_Pcs:
6810  case ParsedAttr::AT_IntelOclBicc:
6811  case ParsedAttr::AT_PreserveMost:
6812  case ParsedAttr::AT_PreserveAll:
6813  case ParsedAttr::AT_AArch64VectorPcs:
6814  handleCallConvAttr(S, D, AL);
6815  break;
6816  case ParsedAttr::AT_Suppress:
6817  handleSuppressAttr(S, D, AL);
6818  break;
6819  case ParsedAttr::AT_OpenCLKernel:
6820  handleSimpleAttribute<OpenCLKernelAttr>(S, D, AL);
6821  break;
6822  case ParsedAttr::AT_OpenCLAccess:
6823  handleOpenCLAccessAttr(S, D, AL);
6824  break;
6825  case ParsedAttr::AT_OpenCLNoSVM:
6826  handleOpenCLNoSVMAttr(S, D, AL);
6827  break;
6828  case ParsedAttr::AT_SwiftContext:
6829  handleParameterABIAttr(S, D, AL, ParameterABI::SwiftContext);
6830  break;
6831  case ParsedAttr::AT_SwiftErrorResult:
6832  handleParameterABIAttr(S, D, AL, ParameterABI::SwiftErrorResult);
6833  break;
6834  case ParsedAttr::AT_SwiftIndirectResult:
6835  handleParameterABIAttr(S, D, AL, ParameterABI::SwiftIndirectResult);
6836  break;
6837  case ParsedAttr::AT_InternalLinkage:
6838  handleInternalLinkageAttr(S, D, AL);
6839  break;
6840  case ParsedAttr::AT_ExcludeFromExplicitInstantiation:
6841  handleSimpleAttribute<ExcludeFromExplicitInstantiationAttr>(S, D, AL);
6842  break;
6843  case ParsedAttr::AT_LTOVisibilityPublic:
6844  handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, AL);
6845  break;
6846 
6847  // Microsoft attributes:
6848  case ParsedAttr::AT_EmptyBases:
6849  handleSimpleAttribute<EmptyBasesAttr>(S, D, AL);
6850  break;
6851  case ParsedAttr::AT_LayoutVersion:
6852  handleLayoutVersion(S, D, AL);
6853  break;
6854  case ParsedAttr::AT_TrivialABI:
6855  handleSimpleAttribute<TrivialABIAttr>(S, D, AL);
6856  break;
6857  case ParsedAttr::AT_MSNoVTable:
6858  handleSimpleAttribute<MSNoVTableAttr>(S, D, AL);
6859  break;
6860  case ParsedAttr::AT_MSStruct:
6861  handleSimpleAttribute<MSStructAttr>(S, D, AL);
6862  break;
6863  case ParsedAttr::AT_Uuid:
6864  handleUuidAttr(S, D, AL);
6865  break;
6866  case ParsedAttr::AT_MSInheritance:
6867  handleMSInheritanceAttr(S, D, AL);
6868  break;
6869  case ParsedAttr::AT_SelectAny:
6870  handleSimpleAttribute<SelectAnyAttr>(S, D, AL);
6871  break;
6872  case ParsedAttr::AT_Thread:
6873  handleDeclspecThreadAttr(S, D, AL);
6874  break;
6875 
6876  case ParsedAttr::AT_AbiTag:
6877  handleAbiTagAttr(S, D, AL);
6878  break;
6879 
6880  // Thread safety attributes:
6881  case ParsedAttr::AT_AssertExclusiveLock:
6882  handleAssertExclusiveLockAttr(S, D, AL);
6883  break;
6884  case ParsedAttr::AT_AssertSharedLock:
6885  handleAssertSharedLockAttr(S, D, AL);
6886  break;
6887  case ParsedAttr::AT_GuardedVar:
6888  handleSimpleAttribute<GuardedVarAttr>(S, D, AL);
6889  break;
6890  case ParsedAttr::AT_PtGuardedVar:
6891  handlePtGuardedVarAttr(S, D, AL);
6892  break;
6893  case ParsedAttr::AT_ScopedLockable:
6894  handleSimpleAttribute<ScopedLockableAttr>(S, D, AL);
6895  break;
6896  case ParsedAttr::AT_NoSanitize:
6897  handleNoSanitizeAttr(S, D, AL);
6898  break;
6899  case ParsedAttr::AT_NoSanitizeSpecific:
6900  handleNoSanitizeSpecificAttr(S, D, AL);
6901  break;
6902  case ParsedAttr::AT_NoThreadSafetyAnalysis:
6903  handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, AL);
6904  break;
6905  case ParsedAttr::AT_GuardedBy:
6906  handleGuardedByAttr(S, D, AL);
6907  break;
6908  case ParsedAttr::AT_PtGuardedBy:
6909  handlePtGuardedByAttr(S, D, AL);
6910  break;
6911  case ParsedAttr::AT_ExclusiveTrylockFunction:
6912  handleExclusiveTrylockFunctionAttr(S, D, AL);
6913  break;
6914  case ParsedAttr::AT_LockReturned:
6915  handleLockReturnedAttr(S, D, AL);
6916  break;
6917  case ParsedAttr::AT_LocksExcluded:
6918  handleLocksExcludedAttr(S, D, AL);
6919  break;
6920  case ParsedAttr::AT_SharedTrylockFunction:
6921  handleSharedTrylockFunctionAttr(S, D, AL);
6922  break;
6923  case ParsedAttr::AT_AcquiredBefore:
6924  handleAcquiredBeforeAttr(S, D, AL);
6925  break;
6926  case ParsedAttr::AT_AcquiredAfter:
6927  handleAcquiredAfterAttr(S, D, AL);
6928  break;
6929 
6930  // Capability analysis attributes.
6931  case ParsedAttr::AT_Capability:
6932  case ParsedAttr::AT_Lockable:
6933  handleCapabilityAttr(S, D, AL);
6934  break;
6935  case ParsedAttr::AT_RequiresCapability:
6936  handleRequiresCapabilityAttr(S, D, AL);
6937  break;
6938 
6939  case ParsedAttr::AT_AssertCapability:
6940  handleAssertCapabilityAttr(S, D, AL);
6941  break;
6942  case ParsedAttr::AT_AcquireCapability:
6943  handleAcquireCapabilityAttr(S, D, AL);
6944  break;
6945  case ParsedAttr::AT_ReleaseCapability:
6946  handleReleaseCapabilityAttr(S, D, AL);
6947  break;
6948  case ParsedAttr::AT_TryAcquireCapability:
6949  handleTryAcquireCapabilityAttr(S, D, AL);
6950  break;
6951 
6952  // Consumed analysis attributes.
6953  case ParsedAttr::AT_Consumable:
6954  handleConsumableAttr(S, D, AL);
6955  break;
6956  case ParsedAttr::AT_ConsumableAutoCast:
6957  handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, AL);
6958  break;
6959  case ParsedAttr::AT_ConsumableSetOnRead:
6960  handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, AL);
6961  break;
6962  case ParsedAttr::AT_CallableWhen:
6963  handleCallableWhenAttr(S, D, AL);
6964  break;
6965  case ParsedAttr::AT_ParamTypestate:
6966  handleParamTypestateAttr(S, D, AL);
6967  break;
6968  case ParsedAttr::AT_ReturnTypestate:
6969  handleReturnTypestateAttr(S, D, AL);
6970  break;
6971  case ParsedAttr::AT_SetTypestate:
6972  handleSetTypestateAttr(S, D, AL);
6973  break;
6974  case ParsedAttr::AT_TestTypestate:
6975  handleTestTypestateAttr(S, D, AL);
6976  break;
6977 
6978  // Type safety attributes.
6979  case ParsedAttr::AT_ArgumentWithTypeTag:
6980  handleArgumentWithTypeTagAttr(S, D, AL);
6981  break;
6982  case ParsedAttr::AT_TypeTagForDatatype:
6983  handleTypeTagForDatatypeAttr(S, D, AL);
6984  break;
6985  case ParsedAttr::AT_AnyX86NoCallerSavedRegisters:
6986  handleSimpleAttribute<AnyX86NoCallerSavedRegistersAttr>(S, D, AL);
6987  break;
6988  case ParsedAttr::AT_RenderScriptKernel:
6989  handleSimpleAttribute<RenderScriptKernelAttr>(S, D, AL);
6990  break;
6991  // XRay attributes.
6992  case ParsedAttr::AT_XRayInstrument:
6993  handleSimpleAttribute<XRayInstrumentAttr>(S, D, AL);
6994  break;
6995  case ParsedAttr::AT_XRayLogArgs:
6996  handleXRayLogArgsAttr(S, D, AL);
6997  break;
6998 
6999  // Move semantics attribute.
7000  case ParsedAttr::AT_Reinitializes:
7001  handleSimpleAttribute<ReinitializesAttr>(S, D, AL);
7002  break;
7003 
7004  case ParsedAttr::AT_AlwaysDestroy:
7005  case ParsedAttr::AT_NoDestroy:
7006  handleDestroyAttr(S, D, AL);
7007  break;
7008 
7009  case ParsedAttr::AT_Uninitialized:
7010  handleUninitializedAttr(S, D, AL);
7011  break;
7012 
7013  case ParsedAttr::AT_ObjCExternallyRetained:
7014  handleObjCExternallyRetainedAttr(S, D, AL);
7015  break;
7016  }
7017 }
7018 
7019 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
7020 /// attribute list to the specified decl, ignoring any type attributes.
7021 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
7022  const ParsedAttributesView &AttrList,
7023  bool IncludeCXX11Attributes) {
7024  if (AttrList.empty())
7025  return;
7026 
7027  for (const ParsedAttr &AL : AttrList)
7028  ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes);
7029 
7030  // FIXME: We should be able to handle these cases in TableGen.
7031  // GCC accepts
7032  // static int a9 __attribute__((weakref));
7033  // but that looks really pointless. We reject it.
7034  if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
7035  Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
7036  << cast<NamedDecl>(D);
7037  D->dropAttr<WeakRefAttr>();
7038  return;
7039  }
7040 
7041  // FIXME: We should be able to handle this in TableGen as well. It would be
7042  // good to have a way to specify "these attributes must appear as a group",
7043  // for these. Additionally, it would be good to have a way to specify "these
7044  // attribute must never appear as a group" for attributes like cold and hot.
7045  if (!D->hasAttr<OpenCLKernelAttr>()) {
7046  // These attributes cannot be applied to a non-kernel function.
7047  if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
7048  // FIXME: This emits a different error message than
7049  // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
7050  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7051  D->setInvalidDecl();
7052  } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
7053  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7054  D->setInvalidDecl();
7055  } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
7056  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7057  D->setInvalidDecl();
7058  } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
7059  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7060  D->setInvalidDecl();
7061  } else if (!D->hasAttr<CUDAGlobalAttr>()) {
7062  if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
7063  Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7064  << A << ExpectedKernelFunction;
7065  D->setInvalidDecl();
7066  } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
7067  Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7068  << A << ExpectedKernelFunction;
7069  D->setInvalidDecl();
7070  } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
7071  Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7072  << A << ExpectedKernelFunction;
7073  D->setInvalidDecl();
7074  } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
7075  Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7076  << A << ExpectedKernelFunction;
7077  D->setInvalidDecl();
7078  }
7079  }
7080  }
7081 
7082  // Do this check after processing D's attributes because the attribute
7083  // objc_method_family can change whether the given method is in the init
7084  // family, and it can be applied after objc_designated_initializer. This is a
7085  // bit of a hack, but we need it to be compatible with versions of clang that
7086  // processed the attribute list in the wrong order.
7087  if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
7088  cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
7089  Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
7090  D->dropAttr<ObjCDesignatedInitializerAttr>();
7091  }
7092 }
7093 
7094 // Helper for delayed processing TransparentUnion attribute.
7096  const ParsedAttributesView &AttrList) {
7097  for (const ParsedAttr &AL : AttrList)
7098  if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
7099  handleTransparentUnionAttr(*this, D, AL);
7100  break;
7101  }
7102 }
7103 
7104 // Annotation attributes are the only attributes allowed after an access
7105 // specifier.
7107  AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
7108  for (const ParsedAttr &AL : AttrList) {
7109  if (AL.getKind() == ParsedAttr::AT_Annotate) {
7110  ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute());
7111  } else {
7112  Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
7113  return true;
7114  }
7115  }
7116  return false;
7117 }
7118 
7119 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
7120 /// contains any decl attributes that we should warn about.
7121 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
7122  for (const ParsedAttr &AL : A) {
7123  // Only warn if the attribute is an unignored, non-type attribute.
7124  if (AL.isUsedAsTypeAttr() || AL.isInvalid())
7125  continue;
7127  continue;
7128 
7129  if (AL.getKind() == ParsedAttr::UnknownAttribute) {
7130  S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
7131  << AL << AL.getRange();
7132  } else {
7133  S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
7134  << AL.getRange();
7135  }
7136  }
7137 }
7138 
7139 /// checkUnusedDeclAttributes - Given a declarator which is not being
7140 /// used to build a declaration, complain about any decl attributes
7141 /// which might be lying around on it.
7143  ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
7144  ::checkUnusedDeclAttributes(*this, D.getAttributes());
7145  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
7146  ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
7147 }
7148 
7149 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
7150 /// \#pragma weak needs a non-definition decl and source may not have one.
7152  SourceLocation Loc) {
7153  assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
7154  NamedDecl *NewD = nullptr;
7155  if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
7156  FunctionDecl *NewFD;
7157  // FIXME: Missing call to CheckFunctionDeclaration().
7158  // FIXME: Mangling?
7159  // FIXME: Is the qualifier info correct?
7160  // FIXME: Is the DeclContext correct?
7161  NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
7162  Loc, Loc, DeclarationName(II),
7163  FD->getType(), FD->getTypeSourceInfo(),
7164  SC_None, false/*isInlineSpecified*/,
7165  FD->hasPrototype(),
7166  false/*isConstexprSpecified*/);
7167  NewD = NewFD;
7168 
7169  if (FD->getQualifier())
7170  NewFD->setQualifierInfo(FD->getQualifierLoc());
7171 
7172  // Fake up parameter variables; they are declared as if this were
7173  // a typedef.
7174  QualType FDTy = FD->getType();
7175  if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
7177  for (const auto &AI : FT->param_types()) {
7178  ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
7179  Param->setScopeInfo(0, Params.size());
7180  Params.push_back(Param);
7181  }
7182  NewFD->setParams(Params);
7183  }
7184  } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
7185  NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
7186  VD->getInnerLocStart(), VD->getLocation(), II,
7187  VD->getType(), VD->getTypeSourceInfo(),
7188  VD->getStorageClass());
7189  if (VD->getQualifier())
7190  cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
7191  }
7192  return NewD;
7193 }
7194 
7195 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
7196 /// applied to it, possibly with an alias.
7197 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
7198  if (W.getUsed()) return; // only do this once
7199  W.setUsed(true);
7200  if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
7201  IdentifierInfo *NDId = ND->getIdentifier();
7202  NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
7203  NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
7204  W.getLocation()));
7205  NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
7206  WeakTopLevelDecl.push_back(NewD);
7207  // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
7208  // to insert Decl at TU scope, sorry.
7209  DeclContext *SavedContext = CurContext;
7210  CurContext = Context.getTranslationUnitDecl();
7211  NewD->setDeclContext(CurContext);
7212  NewD->setLexicalDeclContext(CurContext);
7213  PushOnScopeChains(NewD, S);
7214  CurContext = SavedContext;
7215  } else { // just add weak to existing
7216  ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
7217  }
7218 }
7219 
7220 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
7221  // It's valid to "forward-declare" #pragma weak, in which case we
7222  // have to do this.
7223  LoadExternalWeakUndeclaredIdentifiers();
7224  if (!WeakUndeclaredIdentifiers.empty()) {
7225  NamedDecl *ND = nullptr;
7226  if (auto *VD = dyn_cast<VarDecl>(D))
7227  if (VD->isExternC())
7228  ND = VD;
7229  if (auto *FD = dyn_cast<FunctionDecl>(D))
7230  if (FD->isExternC())
7231  ND = FD;
7232  if (ND) {
7233  if (IdentifierInfo *Id = ND->getIdentifier()) {
7234  auto I = WeakUndeclaredIdentifiers.find(Id);
7235  if (I != WeakUndeclaredIdentifiers.end()) {
7236  WeakInfo W = I->second;
7237  DeclApplyPragmaWeak(S, ND, W);
7238  WeakUndeclaredIdentifiers[Id] = W;
7239  }
7240  }
7241  }
7242  }
7243 }
7244 
7245 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
7246 /// it, apply them to D. This is a bit tricky because PD can have attributes
7247 /// specified in many different places, and we need to find and apply them all.
7248 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
7249  // Apply decl attributes from the DeclSpec if present.
7250  if (!PD.getDeclSpec().getAttributes().empty())
7251  ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes());
7252 
7253  // Walk the declarator structure, applying decl attributes that were in a type
7254  // position to the decl itself. This handles cases like:
7255  // int *__attr__(x)** D;
7256  // when X is a decl attribute.
7257  for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
7258  ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
7259  /*IncludeCXX11Attributes=*/false);
7260 
7261  // Finally, apply any attributes on the decl itself.
7262  ProcessDeclAttributeList(S, D, PD.getAttributes());
7263 
7264  // Apply additional attributes specified by '#pragma clang attribute'.
7265  AddPragmaAttributes(S, D);
7266 }
7267 
7268 /// Is the given declaration allowed to use a forbidden type?
7269 /// If so, it'll still be annotated with an attribute that makes it
7270 /// illegal to actually use.
7271 static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
7272  const DelayedDiagnostic &diag,
7273  UnavailableAttr::ImplicitReason &reason) {
7274  // Private ivars are always okay. Unfortunately, people don't
7275  // always properly make their ivars private, even in system headers.
7276  // Plus we need to make fields okay, too.
7277  if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
7278  !isa<FunctionDecl>(D))
7279  return false;
7280 
7281  // Silently accept unsupported uses of __weak in both user and system
7282  // declarations when it's been disabled, for ease of integration with
7283  // -fno-objc-arc files. We do have to take some care against attempts
7284  // to define such things; for now, we've only done that for ivars
7285  // and properties.
7286  if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
7287  if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
7288  diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
7289  reason = UnavailableAttr::IR_ForbiddenWeak;
7290  return true;
7291  }
7292  }
7293 
7294  // Allow all sorts of things in system headers.
7296  // Currently, all the failures dealt with this way are due to ARC
7297  // restrictions.
7298  reason = UnavailableAttr::IR_ARCForbiddenType;
7299  return true;
7300  }
7301 
7302  return false;
7303 }
7304 
7305 /// Handle a delayed forbidden-type diagnostic.
7306 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
7307  Decl *D) {
7308  auto Reason = UnavailableAttr::IR_None;
7309  if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
7310  assert(Reason && "didn't set reason?");
7311  D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
7312  return;
7313  }
7314  if (S.getLangOpts().ObjCAutoRefCount)
7315  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
7316  // FIXME: we may want to suppress diagnostics for all
7317  // kind of forbidden type messages on unavailable functions.
7318  if (FD->hasAttr<UnavailableAttr>() &&
7320  diag::err_arc_array_param_no_ownership) {
7321  DD.Triggered = true;
7322  return;
7323  }
7324  }
7325 
7326  S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
7328  DD.Triggered = true;
7329 }
7330 
7331 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
7332  const Decl *D) {
7333  // Check each AvailabilityAttr to find the one for this platform.
7334  for (const auto *A : D->attrs()) {
7335  if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
7336  // FIXME: this is copied from CheckAvailability. We should try to
7337  // de-duplicate.
7338 
7339  // Check if this is an App Extension "platform", and if so chop off
7340  // the suffix for matching with the actual platform.
7341  StringRef ActualPlatform = Avail->getPlatform()->getName();
7342  StringRef RealizedPlatform = ActualPlatform;
7343  if (Context.getLangOpts().AppExt) {
7344  size_t suffix = RealizedPlatform.rfind("_app_extension");
7345  if (suffix != StringRef::npos)
7346  RealizedPlatform = RealizedPlatform.slice(0, suffix);
7347  }
7348 
7349  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
7350 
7351  // Match the platform name.
7352  if (RealizedPlatform == TargetPlatform)
7353  return Avail;
7354  }
7355  }
7356  return nullptr;
7357 }
7358 
7359 /// The diagnostic we should emit for \c D, and the declaration that
7360 /// originated it, or \c AR_Available.
7361 ///
7362 /// \param D The declaration to check.
7363 /// \param Message If non-null, this will be populated with the message from
7364 /// the availability attribute that is selected.
7365 /// \param ClassReceiver If we're checking the the method of a class message
7366 /// send, the class. Otherwise nullptr.
7367 static std::pair<AvailabilityResult, const NamedDecl *>
7368 ShouldDiagnoseAvailabilityOfDecl(Sema &S, const NamedDecl *D,
7369  std::string *Message,
7370  ObjCInterfaceDecl *ClassReceiver) {
7371  AvailabilityResult Result = D->getAvailability(Message);
7372 
7373  // For typedefs, if the typedef declaration appears available look
7374  // to the underlying type to see if it is more restrictive.
7375  while (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
7376  if (Result == AR_Available) {
7377  if (const auto *TT = TD->getUnderlyingType()->getAs<TagType>()) {
7378  D = TT->getDecl();
7379  Result = D->getAvailability(Message);
7380  continue;
7381  }
7382  }
7383  break;
7384  }
7385 
7386  // Forward class declarations get their attributes from their definition.
7387  if (const auto *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
7388  if (IDecl->getDefinition()) {
7389  D = IDecl->getDefinition();
7390  Result = D->getAvailability(Message);
7391  }
7392  }
7393 
7394  if (const auto *ECD = dyn_cast<EnumConstantDecl>(D))
7395  if (Result == AR_Available) {
7396  const DeclContext *DC = ECD->getDeclContext();
7397  if (const auto *TheEnumDecl = dyn_cast<EnumDecl>(DC)) {
7398  Result = TheEnumDecl->getAvailability(Message);
7399  D = TheEnumDecl;
7400  }
7401  }
7402 
7403  // For +new, infer availability from -init.
7404  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
7405  if (S.NSAPIObj && ClassReceiver) {
7406  ObjCMethodDecl *Init = ClassReceiver->lookupInstanceMethod(
7407  S.NSAPIObj->getInitSelector());
7408  if (Init && Result == AR_Available && MD->isClassMethod() &&
7409  MD->getSelector() == S.NSAPIObj->getNewSelector() &&
7410  MD->definedInNSObject(S.getASTContext())) {
7411  Result = Init->getAvailability(Message);
7412  D = Init;
7413  }
7414  }
7415  }
7416 
7417  return {Result, D};
7418 }
7419 
7420 
7421 /// whether we should emit a diagnostic for \c K and \c DeclVersion in
7422 /// the context of \c Ctx. For example, we should emit an unavailable diagnostic
7423 /// in a deprecated context, but not the other way around.
7424 static bool
7425 ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
7426  VersionTuple DeclVersion, Decl *Ctx,
7427  const NamedDecl *OffendingDecl) {
7428  assert(K != AR_Available && "Expected an unavailable declaration here!");
7429 
7430  // Checks if we should emit the availability diagnostic in the context of C.
7431  auto CheckContext = [&](const Decl *C) {
7432  if (K == AR_NotYetIntroduced) {
7433  if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
7434  if (AA->getIntroduced() >= DeclVersion)
7435  return true;
7436  } else if (K == AR_Deprecated) {
7437  if (C->isDeprecated())
7438  return true;
7439  } else if (K == AR_Unavailable) {
7440  // It is perfectly fine to refer to an 'unavailable' Objective-C method
7441  // when it is referenced from within the @implementation itself. In this
7442  // context, we interpret unavailable as a form of access control.
7443  if (const auto *MD = dyn_cast<ObjCMethodDecl>(OffendingDecl)) {
7444  if (const auto *Impl = dyn_cast<ObjCImplDecl>(C)) {
7445  if (MD->getClassInterface() == Impl->getClassInterface())
7446  return true;
7447  }
7448  }
7449  }
7450 
7451  if (C->isUnavailable())
7452  return true;
7453  return false;
7454  };
7455 
7456  do {
7457  if (CheckContext(Ctx))
7458  return false;
7459 
7460  // An implementation implicitly has the availability of the interface.
7461  // Unless it is "+load" method.
7462  if (const auto *MethodD = dyn_cast<ObjCMethodDecl>(Ctx))
7463  if (MethodD->isClassMethod() &&
7464  MethodD->getSelector().getAsString() == "load")
7465  return true;
7466 
7467  if (const auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
7468  if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
7469  if (CheckContext(Interface))
7470  return false;
7471  }
7472  // A category implicitly has the availability of the interface.
7473  else if (const auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
7474  if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
7475  if (CheckContext(Interface))
7476  return false;
7477  } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
7478 
7479  return true;
7480 }
7481 
7482 static bool
7483 shouldDiagnoseAvailabilityByDefault(const ASTContext &Context,
7484  const VersionTuple &DeploymentVersion,
7485  const VersionTuple &DeclVersion) {
7486  const auto &Triple = Context.getTargetInfo().getTriple();
7487  VersionTuple ForceAvailabilityFromVersion;
7488  switch (Triple.getOS()) {
7489  case llvm::Triple::IOS:
7490  case llvm::Triple::TvOS:
7491  ForceAvailabilityFromVersion = VersionTuple(/*Major=*/11);
7492  break;
7493  case llvm::Triple::WatchOS:
7494  ForceAvailabilityFromVersion = VersionTuple(/*Major=*/4);
7495  break;
7496  case llvm::Triple::Darwin:
7497  case llvm::Triple::MacOSX:
7498  ForceAvailabilityFromVersion = VersionTuple(/*Major=*/10, /*Minor=*/13);
7499  break;
7500  default:
7501  // New targets should always warn about availability.
7502  return Triple.getVendor() == llvm::Triple::Apple;
7503  }
7504  return DeploymentVersion >= ForceAvailabilityFromVersion ||
7505  DeclVersion >= ForceAvailabilityFromVersion;
7506 }
7507 
7508 static NamedDecl *findEnclosingDeclToAnnotate(Decl *OrigCtx) {
7509  for (Decl *Ctx = OrigCtx; Ctx;
7510  Ctx = cast_or_null<Decl>(Ctx->getDeclContext())) {
7511  if (isa<TagDecl>(Ctx) || isa<FunctionDecl>(Ctx) || isa<ObjCMethodDecl>(Ctx))
7512  return cast<NamedDecl>(Ctx);
7513  if (auto *CD = dyn_cast<ObjCContainerDecl>(Ctx)) {
7514  if (auto *Imp = dyn_cast<ObjCImplDecl>(Ctx))
7515  return Imp->getClassInterface();
7516  return CD;
7517  }
7518  }
7519 
7520  return dyn_cast<NamedDecl>(OrigCtx);
7521 }
7522 
7523 namespace {
7524 
7525 struct AttributeInsertion {
7526  StringRef Prefix;
7527  SourceLocation Loc;
7528  StringRef Suffix;
7529 
7530  static AttributeInsertion createInsertionAfter(const NamedDecl *D) {
7531  return {" ", D->getEndLoc(), ""};
7532  }
7533  static AttributeInsertion createInsertionAfter(SourceLocation Loc) {
7534  return {" ", Loc, ""};
7535  }
7536  static AttributeInsertion createInsertionBefore(const NamedDecl *D) {
7537  return {"", D->getBeginLoc(), "\n"};
7538  }
7539 };
7540 
7541 } // end anonymous namespace
7542 
7543 /// Tries to parse a string as ObjC method name.
7544 ///
7545 /// \param Name The string to parse. Expected to originate from availability
7546 /// attribute argument.
7547 /// \param SlotNames The vector that will be populated with slot names. In case
7548 /// of unsuccessful parsing can contain invalid data.
7549 /// \returns A number of method parameters if parsing was successful, None
7550 /// otherwise.
7551 static Optional<unsigned>
7552 tryParseObjCMethodName(StringRef Name, SmallVectorImpl<StringRef> &SlotNames,
7553  const LangOptions &LangOpts) {
7554  // Accept replacements starting with - or + as valid ObjC method names.
7555  if (!Name.empty() && (Name.front() == '-' || Name.front() == '+'))
7556  Name = Name.drop_front(1);
7557  if (Name.empty())
7558  return None;
7559  Name.split(SlotNames, ':');
7560  unsigned NumParams;
7561  if (Name.back() == ':') {
7562  // Remove an empty string at the end that doesn't represent any slot.
7563  SlotNames.pop_back();
7564  NumParams = SlotNames.size();
7565  } else {
7566  if (SlotNames.size() != 1)
7567  // Not a valid method name, just a colon-separated string.
7568  return None;
7569  NumParams = 0;
7570  }
7571  // Verify all slot names are valid.
7572  bool AllowDollar = LangOpts.DollarIdents;
7573  for (StringRef S : SlotNames) {
7574  if (S.empty())
7575  continue;
7576  if (!isValidIdentifier(S, AllowDollar))
7577  return None;
7578  }
7579  return NumParams;
7580 }
7581 
7582 /// Returns a source location in which it's appropriate to insert a new
7583 /// attribute for the given declaration \D.
7585 createAttributeInsertion(const NamedDecl *D, const SourceManager &SM,
7586  const LangOptions &LangOpts) {
7587  if (isa<ObjCPropertyDecl>(D))
7588  return AttributeInsertion::createInsertionAfter(D);
7589  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
7590  if (MD->hasBody())
7591  return None;
7592  return AttributeInsertion::createInsertionAfter(D);
7593  }
7594  if (const auto *TD = dyn_cast<TagDecl>(D)) {
7595  SourceLocation Loc =
7596  Lexer::getLocForEndOfToken(TD->getInnerLocStart(), 0, SM, LangOpts);
7597  if (Loc.isInvalid())
7598  return None;
7599  // Insert after the 'struct'/whatever keyword.
7600  return AttributeInsertion::createInsertionAfter(Loc);
7601  }
7602  return AttributeInsertion::createInsertionBefore(D);
7603 }
7604 
7605 /// Actually emit an availability diagnostic for a reference to an unavailable
7606 /// decl.
7607 ///
7608 /// \param Ctx The context that the reference occurred in
7609 /// \param ReferringDecl The exact declaration that was referenced.
7610 /// \param OffendingDecl A related decl to \c ReferringDecl that has an
7611 /// availability attribute corresponding to \c K attached to it. Note that this
7612 /// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and
7613 /// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl
7614 /// and OffendingDecl is the EnumDecl.
7615 static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
7616  Decl *Ctx, const NamedDecl *ReferringDecl,
7617  const NamedDecl *OffendingDecl,
7618  StringRef Message,
7620  const ObjCInterfaceDecl *UnknownObjCClass,
7621  const ObjCPropertyDecl *ObjCProperty,
7622  bool ObjCPropertyAccess) {
7623  // Diagnostics for deprecated or unavailable.
7624  unsigned diag, diag_message, diag_fwdclass_message;
7625  unsigned diag_available_here = diag::note_availability_specified_here;
7626  SourceLocation NoteLocation = OffendingDecl->getLocation();
7627 
7628  // Matches 'diag::note_property_attribute' options.
7629  unsigned property_note_select;
7630 
7631  // Matches diag::note_availability_specified_here.
7632  unsigned available_here_select_kind;
7633 
7634  VersionTuple DeclVersion;
7635  if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl))
7636  DeclVersion = AA->getIntroduced();
7637 
7638  if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx,
7639  OffendingDecl))
7640  return;
7641 
7642  SourceLocation Loc = Locs.front();
7643 
7644  // The declaration can have multiple availability attributes, we are looking
7645  // at one of them.
7646  const AvailabilityAttr *A = getAttrForPlatform(S.Context, OffendingDecl);
7647  if (A && A->isInherited()) {
7648  for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl;
7649  Redecl = Redecl->getPreviousDecl()) {
7650  const AvailabilityAttr *AForRedecl =
7651  getAttrForPlatform(S.Context, Redecl);
7652  if (AForRedecl && !AForRedecl->isInherited()) {
7653  // If D is a declaration with inherited attributes, the note should
7654  // point to the declaration with actual attributes.
7655  NoteLocation = Redecl->getLocation();
7656  break;
7657  }
7658  }
7659  }
7660 
7661  switch (K) {
7662  case AR_NotYetIntroduced: {
7663  // We would like to emit the diagnostic even if -Wunguarded-availability is
7664  // not specified for deployment targets >= to iOS 11 or equivalent or
7665  // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
7666  // later.
7667  const AvailabilityAttr *AA =
7668  getAttrForPlatform(S.getASTContext(), OffendingDecl);
7669  VersionTuple Introduced = AA->getIntroduced();
7670 
7671  bool UseNewWarning = shouldDiagnoseAvailabilityByDefault(
7673  Introduced);
7674  unsigned Warning = UseNewWarning ? diag::warn_unguarded_availability_new
7675  : diag::warn_unguarded_availability;
7676 
7677  std::string PlatformName = AvailabilityAttr::getPrettyPlatformName(
7679 
7680  S.Diag(Loc, Warning) << OffendingDecl << PlatformName
7681  << Introduced.getAsString();
7682 
7683  S.Diag(OffendingDecl->getLocation(),
7684  diag::note_partial_availability_specified_here)
7685  << OffendingDecl << PlatformName << Introduced.getAsString()
7686  << S.Context.getTargetInfo().getPlatformMinVersion().getAsString();
7687 
7688  if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) {
7689  if (const auto *TD = dyn_cast<TagDecl>(Enclosing))
7690  if (TD->getDeclName().isEmpty()) {
7691  S.Diag(TD->getLocation(),
7692  diag::note_decl_unguarded_availability_silence)
7693  << /*Anonymous*/ 1 << TD->getKindName();
7694  return;
7695  }
7696  auto FixitNoteDiag =
7697  S.Diag(Enclosing->getLocation(),
7698  diag::note_decl_unguarded_availability_silence)
7699  << /*Named*/ 0 << Enclosing;
7700  // Don't offer a fixit for declarations with availability attributes.
7701  if (Enclosing->hasAttr<AvailabilityAttr>())
7702  return;
7703  if (!S.getPreprocessor().isMacroDefined("API_AVAILABLE"))
7704  return;
7705  Optional<AttributeInsertion> Insertion = createAttributeInsertion(
7706  Enclosing, S.getSourceManager(), S.getLangOpts());
7707  if (!Insertion)
7708  return;
7709  std::string PlatformName =
7710  AvailabilityAttr::getPlatformNameSourceSpelling(
7712  .lower();
7713  std::string Introduced =
7714  OffendingDecl->getVersionIntroduced().getAsString();
7715  FixitNoteDiag << FixItHint::CreateInsertion(
7716  Insertion->Loc,
7717  (llvm::Twine(Insertion->Prefix) + "API_AVAILABLE(" + PlatformName +
7718  "(" + Introduced + "))" + Insertion->Suffix)
7719  .str());
7720  }
7721  return;
7722  }
7723  case AR_Deprecated:
7724  diag = !ObjCPropertyAccess ? diag::warn_deprecated
7725  : diag::warn_property_method_deprecated;
7726  diag_message = diag::warn_deprecated_message;
7727  diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
7728  property_note_select = /* deprecated */ 0;
7729  available_here_select_kind = /* deprecated */ 2;
7730  if (const auto *AL = OffendingDecl->getAttr<DeprecatedAttr>())
7731  NoteLocation = AL->getLocation();
7732  break;
7733 
7734  case AR_Unavailable:
7735  diag = !ObjCPropertyAccess ? diag::err_unavailable
7736  : diag::err_property_method_unavailable;
7737  diag_message = diag::err_unavailable_message;
7738  diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
7739  property_note_select = /* unavailable */ 1;
7740  available_here_select_kind = /* unavailable */ 0;
7741 
7742  if (auto AL = OffendingDecl->getAttr<UnavailableAttr>()) {
7743  if (AL->isImplicit() && AL->getImplicitReason()) {
7744  // Most of these failures are due to extra restrictions in ARC;
7745  // reflect that in the primary diagnostic when applicable.
7746  auto flagARCError = [&] {
7747  if (S.getLangOpts().ObjCAutoRefCount &&
7749  OffendingDecl->getLocation()))
7750  diag = diag::err_unavailable_in_arc;
7751  };
7752 
7753  switch (AL->getImplicitReason()) {
7754  case UnavailableAttr::IR_None: break;
7755 
7756  case UnavailableAttr::IR_ARCForbiddenType:
7757  flagARCError();
7758  diag_available_here = diag::note_arc_forbidden_type;
7759  break;
7760 
7761  case UnavailableAttr::IR_ForbiddenWeak:
7762  if (S.getLangOpts().ObjCWeakRuntime)
7763  diag_available_here = diag::note_arc_weak_disabled;
7764  else
7765  diag_available_here = diag::note_arc_weak_no_runtime;
7766  break;
7767 
7768  case UnavailableAttr::IR_ARCForbiddenConversion:
7769  flagARCError();
7770  diag_available_here = diag::note_performs_forbidden_arc_conversion;
7771  break;
7772 
7773  case UnavailableAttr::IR_ARCInitReturnsUnrelated:
7774  flagARCError();
7775  diag_available_here = diag::note_arc_init_returns_unrelated;
7776  break;
7777 
7778  case UnavailableAttr::IR_ARCFieldWithOwnership:
7779  flagARCError();
7780  diag_available_here = diag::note_arc_field_with_ownership;
7781  break;
7782  }
7783  }
7784  }
7785  break;
7786 
7787  case AR_Available:
7788  llvm_unreachable("Warning for availability of available declaration?");
7789  }
7790 
7792  if (K == AR_Deprecated) {
7793  StringRef Replacement;
7794  if (auto AL = OffendingDecl->getAttr<DeprecatedAttr>())
7795  Replacement = AL->getReplacement();
7796  if (auto AL = getAttrForPlatform(S.Context, OffendingDecl))
7797  Replacement = AL->getReplacement();
7798 
7799  CharSourceRange UseRange;
7800  if (!Replacement.empty())
7801  UseRange =
7803  if (UseRange.isValid()) {
7804  if (const auto *MethodDecl = dyn_cast<ObjCMethodDecl>(ReferringDecl)) {
7805  Selector Sel = MethodDecl->getSelector();
7806  SmallVector<StringRef, 12> SelectorSlotNames;
7807  Optional<unsigned> NumParams = tryParseObjCMethodName(
7808  Replacement, SelectorSlotNames, S.getLangOpts());
7809  if (NumParams && NumParams.getValue() == Sel.getNumArgs()) {
7810  assert(SelectorSlotNames.size() == Locs.size());
7811  for (unsigned I = 0; I < Locs.size(); ++I) {
7812  if (!Sel.getNameForSlot(I).empty()) {
7814  Locs[I], S.getLocForEndOfToken(Locs[I]));
7815  FixIts.push_back(FixItHint::CreateReplacement(
7816  NameRange, SelectorSlotNames[I]));
7817  } else
7818  FixIts.push_back(
7819  FixItHint::CreateInsertion(Locs[I], SelectorSlotNames[I]));
7820  }
7821  } else
7822  FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
7823  } else
7824  FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
7825  }
7826  }
7827 
7828  if (!Message.empty()) {
7829  S.Diag(Loc, diag_message) << ReferringDecl << Message << FixIts;
7830  if (ObjCProperty)
7831  S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7832  << ObjCProperty->getDeclName() << property_note_select;
7833  } else if (!UnknownObjCClass) {
7834  S.Diag(Loc, diag) << ReferringDecl << FixIts;
7835  if (ObjCProperty)
7836  S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7837  << ObjCProperty->getDeclName() << property_note_select;
7838  } else {
7839  S.Diag(Loc, diag_fwdclass_message) << ReferringDecl << FixIts;
7840  S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
7841  }
7842 
7843  S.Diag(NoteLocation, diag_available_here)
7844  << OffendingDecl << available_here_select_kind;
7845 }
7846 
7847 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
7848  Decl *Ctx) {
7849  assert(DD.Kind == DelayedDiagnostic::Availability &&
7850  "Expected an availability diagnostic here");
7851 
7852  DD.Triggered = true;
7853  DoEmitAvailabilityWarning(
7857  DD.getObjCProperty(), false);
7858 }
7859 
7860 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7861  assert(DelayedDiagnostics.getCurrentPool());
7862  DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
7863  DelayedDiagnostics.popWithoutEmitting(state);
7864 
7865  // When delaying diagnostics to run in the context of a parsed
7866  // declaration, we only want to actually emit anything if parsing
7867  // succeeds.
7868  if (!decl) return;
7869 
7870  // We emit all the active diagnostics in this pool or any of its
7871  // parents. In general, we'll get one pool for the decl spec
7872  // and a child pool for each declarator; in a decl group like:
7873  // deprecated_typedef foo, *bar, baz();
7874  // only the declarator pops will be passed decls. This is correct;
7875  // we really do need to consider delayed diagnostics from the decl spec
7876  // for each of the different declarations.
7877  const DelayedDiagnosticPool *pool = &poppedPool;
7878  do {
7879  bool AnyAccessFailures = false;
7881  i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
7882  // This const_cast is a bit lame. Really, Triggered should be mutable.
7883  DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
7884  if (diag.Triggered)
7885  continue;
7886 
7887  switch (diag.Kind) {
7889  // Don't bother giving deprecation/unavailable diagnostics if
7890  // the decl is invalid.
7891  if (!decl->isInvalidDecl())
7892  handleDelayedAvailabilityCheck(*this, diag, decl);
7893  break;
7894 
7896  // Only produce one access control diagnostic for a structured binding
7897  // declaration: we don't need to tell the user that all the fields are
7898  // inaccessible one at a time.
7899  if (AnyAccessFailures && isa<DecompositionDecl>(decl))
7900  continue;
7901  HandleDelayedAccessCheck(diag, decl);
7902  if (diag.Triggered)
7903  AnyAccessFailures = true;
7904  break;
7905 
7907  handleDelayedForbiddenType(*this, diag, decl);
7908  break;
7909  }
7910  }
7911  } while ((pool = pool->getParent()));
7912 }
7913 
7914 /// Given a set of delayed diagnostics, re-emit them as if they had
7915 /// been delayed in the current context instead of in the given pool.
7916 /// Essentially, this just moves them to the current pool.
7918  DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
7919  assert(curPool && "re-emitting in undelayed context not supported");
7920  curPool->steal(pool);
7921 }
7922 
7923 static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR,
7924  const NamedDecl *ReferringDecl,
7925  const NamedDecl *OffendingDecl,
7926  StringRef Message,
7928  const ObjCInterfaceDecl *UnknownObjCClass,
7929  const ObjCPropertyDecl *ObjCProperty,
7930  bool ObjCPropertyAccess) {
7931  // Delay if we're currently parsing a declaration.
7935  AR, Locs, ReferringDecl, OffendingDecl, UnknownObjCClass,
7936  ObjCProperty, Message, ObjCPropertyAccess));
7937  return;
7938  }
7939 
7940  Decl *Ctx = cast<Decl>(S.getCurLexicalContext());
7941  DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl,
7942  Message, Locs, UnknownObjCClass, ObjCProperty,
7943  ObjCPropertyAccess);
7944 }
7945 
7946 namespace {
7947 
7948 /// Returns true if the given statement can be a body-like child of \p Parent.
7949 bool isBodyLikeChildStmt(const Stmt *S, const Stmt *Parent) {
7950  switch (Parent->getStmtClass()) {
7951  case Stmt::IfStmtClass:
7952  return cast<IfStmt>(Parent)->getThen() == S ||
7953  cast<IfStmt>(Parent)->getElse() == S;
7954  case Stmt::WhileStmtClass:
7955  return cast<WhileStmt>(Parent)->getBody() == S;
7956  case Stmt::DoStmtClass:
7957  return cast<DoStmt>(Parent)->getBody() == S;
7958  case Stmt::ForStmtClass:
7959  return cast<ForStmt>(Parent)->getBody() == S;
7960  case Stmt::CXXForRangeStmtClass:
7961  return cast<CXXForRangeStmt>(Parent)->getBody() == S;
7962  case Stmt::ObjCForCollectionStmtClass:
7963  return cast<ObjCForCollectionStmt>(Parent)->getBody() == S;
7964  case Stmt::CaseStmtClass:
7965  case Stmt::DefaultStmtClass:
7966  return cast<SwitchCase>(Parent)->getSubStmt() == S;
7967  default:
7968  return false;
7969  }
7970 }
7971 
7972 class StmtUSEFinder : public RecursiveASTVisitor<StmtUSEFinder> {
7973  const Stmt *Target;
7974 
7975 public:
7976  bool VisitStmt(Stmt *S) { return S != Target; }
7977 
7978  /// Returns true if the given statement is present in the given declaration.
7979  static bool isContained(const Stmt *Target, const Decl *D) {
7980  StmtUSEFinder Visitor;
7981  Visitor.Target = Target;
7982  return !Visitor.TraverseDecl(const_cast<Decl *>(D));
7983  }
7984 };
7985 
7986 /// Traverses the AST and finds the last statement that used a given
7987 /// declaration.
7988 class LastDeclUSEFinder : public RecursiveASTVisitor<LastDeclUSEFinder> {
7989  const Decl *D;
7990 
7991 public:
7992  bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7993  if (DRE->getDecl() == D)
7994  return false;
7995  return true;
7996  }
7997 
7998  static const Stmt *findLastStmtThatUsesDecl(const Decl *D,
7999  const CompoundStmt *Scope) {
8000  LastDeclUSEFinder Visitor;
8001  Visitor.D = D;
8002  for (auto I = Scope->body_rbegin(), E = Scope->body_rend(); I != E; ++I) {
8003  const Stmt *S = *I;
8004  if (!Visitor.TraverseStmt(const_cast<Stmt *>(S)))
8005  return S;
8006  }
8007  return nullptr;
8008  }
8009 };
8010 
8011 /// This class implements -Wunguarded-availability.
8012 ///
8013 /// This is done with a traversal of the AST of a function that makes reference
8014 /// to a partially available declaration. Whenever we encounter an \c if of the
8015 /// form: \c if(@available(...)), we use the version from the condition to visit
8016 /// the then statement.
8017 class DiagnoseUnguardedAvailability
8018  : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
8020 
8021  Sema &SemaRef;
8022  Decl *Ctx;
8023 
8024  /// Stack of potentially nested 'if (@available(...))'s.
8025  SmallVector<VersionTuple, 8> AvailabilityStack;
8027 
8028  void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range,
8029  ObjCInterfaceDecl *ClassReceiver = nullptr);
8030 
8031 public:
8032  DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
8033  : SemaRef(SemaRef), Ctx(Ctx) {
8034  AvailabilityStack.push_back(
8036  }
8037 
8038  bool TraverseDecl(Decl *D) {
8039  // Avoid visiting nested functions to prevent duplicate warnings.
8040  if (!D || isa<FunctionDecl>(D))
8041  return true;
8042  return Base::TraverseDecl(D);
8043  }
8044 
8045  bool TraverseStmt(Stmt *S) {
8046  if (!S)
8047  return true;
8048  StmtStack.push_back(S);
8049  bool Result = Base::TraverseStmt(S);
8050  StmtStack.pop_back();
8051  return Result;
8052  }
8053 
8054  void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
8055 
8056  bool TraverseIfStmt(IfStmt *If);
8057 
8058  bool TraverseLambdaExpr(LambdaExpr *E) { return true; }
8059 
8060  // for 'case X:' statements, don't bother looking at the 'X'; it can't lead
8061  // to any useful diagnostics.
8062  bool TraverseCaseStmt(CaseStmt *CS) { return TraverseStmt(CS->getSubStmt()); }
8063 
8064  bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) {
8065  if (PRE->isClassReceiver())
8066  DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation());
8067  return true;
8068  }
8069 
8070  bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
8071  if (ObjCMethodDecl *D = Msg->getMethodDecl()) {
8072  ObjCInterfaceDecl *ID = nullptr;
8073  QualType ReceiverTy = Msg->getClassReceiver();
8074  if (!ReceiverTy.isNull() && ReceiverTy->getAsObjCInterfaceType())
8075  ID = ReceiverTy->getAsObjCInterfaceType()->getInterface();
8076 
8077  DiagnoseDeclAvailability(
8078  D, SourceRange(Msg->getSelectorStartLoc(), Msg->getEndLoc()), ID);
8079  }
8080  return true;
8081  }
8082 
8083  bool VisitDeclRefExpr(DeclRefExpr *DRE) {
8084  DiagnoseDeclAvailability(DRE->getDecl(),
8085  SourceRange(DRE->getBeginLoc(), DRE->getEndLoc()));
8086  return true;
8087  }
8088 
8089  bool VisitMemberExpr(MemberExpr *ME) {
8090  DiagnoseDeclAvailability(ME->getMemberDecl(),
8091  SourceRange(ME->getBeginLoc(), ME->getEndLoc()));
8092  return true;
8093  }
8094 
8095  bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
8096  SemaRef.Diag(E->getBeginLoc(), diag::warn_at_available_unchecked_use)
8097  << (!SemaRef.getLangOpts().ObjC);
8098  return true;
8099  }
8100 
8101  bool VisitTypeLoc(TypeLoc Ty);
8102 };
8103 
8104 void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
8105  NamedDecl *D, SourceRange Range, ObjCInterfaceDecl *ReceiverClass) {
8106  AvailabilityResult Result;
8107  const NamedDecl *OffendingDecl;
8108  std::tie(Result, OffendingDecl) =
8109  ShouldDiagnoseAvailabilityOfDecl(SemaRef, D, nullptr, ReceiverClass);
8110  if (Result != AR_Available) {
8111  // All other diagnostic kinds have already been handled in
8112  // DiagnoseAvailabilityOfDecl.
8113  if (Result != AR_NotYetIntroduced)
8114  return;
8115 
8116  const AvailabilityAttr *AA =
8117  getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl);
8118  VersionTuple Introduced = AA->getIntroduced();
8119 
8120  if (AvailabilityStack.back() >= Introduced)
8121  return;
8122 
8123  // If the context of this function is less available than D, we should not
8124  // emit a diagnostic.
8125  if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx,
8126  OffendingDecl))
8127  return;
8128 
8129  // We would like to emit the diagnostic even if -Wunguarded-availability is
8130  // not specified for deployment targets >= to iOS 11 or equivalent or
8131  // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
8132  // later.
8133  unsigned DiagKind =
8134  shouldDiagnoseAvailabilityByDefault(
8135  SemaRef.Context,
8136  SemaRef.Context.getTargetInfo().getPlatformMinVersion(), Introduced)
8137  ? diag::warn_unguarded_availability_new
8138  : diag::warn_unguarded_availability;
8139 
8140  std::string PlatformName = AvailabilityAttr::getPrettyPlatformName(
8141  SemaRef.getASTContext().getTargetInfo().getPlatformName());
8142 
8143  SemaRef.Diag(Range.getBegin(), DiagKind)
8144  << Range << D << PlatformName << Introduced.getAsString();
8145 
8146  SemaRef.Diag(OffendingDecl->getLocation(),
8147  diag::note_partial_availability_specified_here)
8148  << OffendingDecl << PlatformName << Introduced.getAsString()
8149  << SemaRef.Context.getTargetInfo()
8150  .getPlatformMinVersion()
8151  .getAsString();
8152 
8153  auto FixitDiag =
8154  SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
8155  << Range << D
8156  << (SemaRef.getLangOpts().ObjC ? /*@available*/ 0
8157  : /*__builtin_available*/ 1);
8158 
8159  // Find the statement which should be enclosed in the if @available check.
8160  if (StmtStack.empty())
8161  return;
8162  const Stmt *StmtOfUse = StmtStack.back();
8163  const CompoundStmt *Scope = nullptr;
8164  for (const Stmt *S : llvm::reverse(StmtStack)) {
8165  if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
8166  Scope = CS;
8167  break;
8168  }
8169  if (isBodyLikeChildStmt(StmtOfUse, S)) {
8170  // The declaration won't be seen outside of the statement, so we don't
8171  // have to wrap the uses of any declared variables in if (@available).
8172  // Therefore we can avoid setting Scope here.
8173  break;
8174  }
8175  StmtOfUse = S;
8176  }
8177  const Stmt *LastStmtOfUse = nullptr;
8178  if (isa<DeclStmt>(StmtOfUse) && Scope) {
8179  for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) {
8180  if (StmtUSEFinder::isContained(StmtStack.back(), D)) {
8181  LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope);
8182  break;
8183  }
8184  }
8185  }
8186 
8187  const SourceManager &SM = SemaRef.getSourceManager();
8188  SourceLocation IfInsertionLoc =
8189  SM.getExpansionLoc(StmtOfUse->getBeginLoc());
8190  SourceLocation StmtEndLoc =
8191  SM.getExpansionRange(
8192  (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getEndLoc())
8193  .getEnd();
8194  if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc))
8195  return;
8196 
8197  StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM);
8198  const char *ExtraIndentation = " ";
8199  std::string FixItString;
8200  llvm::raw_string_ostream FixItOS(FixItString);
8201  FixItOS << "if (" << (SemaRef.getLangOpts().ObjC ? "@available"
8202  : "__builtin_available")
8203  << "("
8204  << AvailabilityAttr::getPlatformNameSourceSpelling(
8205  SemaRef.getASTContext().getTargetInfo().getPlatformName())
8206  << " " << Introduced.getAsString() << ", *)) {\n"
8207  << Indentation << ExtraIndentation;
8208  FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str());
8209  SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken(
8210  StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(),
8211  /*SkipTrailingWhitespaceAndNewLine=*/false);
8212  if (ElseInsertionLoc.isInvalid())
8213  ElseInsertionLoc =
8214  Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts());
8215  FixItOS.str().clear();
8216  FixItOS << "\n"
8217  << Indentation << "} else {\n"
8218  << Indentation << ExtraIndentation
8219  << "// Fallback on earlier versions\n"
8220  << Indentation << "}";
8221  FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str());
8222  }
8223 }
8224 
8225 bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
8226  const Type *TyPtr = Ty.getTypePtr();
8227  SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
8228 
8229  if (Range.isInvalid())
8230  return true;
8231 
8232  if (const auto *TT = dyn_cast<TagType>(TyPtr)) {
8233  TagDecl *TD = TT->getDecl();
8234  DiagnoseDeclAvailability(TD, Range);
8235 
8236  } else if (const auto *TD = dyn_cast<TypedefType>(TyPtr)) {
8237  TypedefNameDecl *D = TD->getDecl();
8238  DiagnoseDeclAvailability(D, Range);
8239 
8240  } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
8241  if (NamedDecl *D = ObjCO->getInterface())
8242  DiagnoseDeclAvailability(D, Range);
8243  }
8244 
8245  return true;
8246 }
8247 
8248 bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
8249  VersionTuple CondVersion;
8250  if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
8251  CondVersion = E->getVersion();
8252 
8253  // If we're using the '*' case here or if this check is redundant, then we
8254  // use the enclosing version to check both branches.
8255  if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
8256  return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse());
8257  } else {
8258  // This isn't an availability checking 'if', we can just continue.
8259  return Base::TraverseIfStmt(If);
8260  }
8261 
8262  AvailabilityStack.push_back(CondVersion);
8263  bool ShouldContinue = TraverseStmt(If->getThen());
8264  AvailabilityStack.pop_back();
8265 
8266  return ShouldContinue && TraverseStmt(If->getElse());
8267 }
8268 
8269 } // end anonymous namespace
8270 
8272  Stmt *Body = nullptr;
8273 
8274  if (auto *FD = D->getAsFunction()) {
8275  // FIXME: We only examine the pattern decl for availability violations now,
8276  // but we should also examine instantiated templates.
8277  if (FD->isTemplateInstantiation())
8278  return;
8279 
8280  Body = FD->getBody();
8281  } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
8282  Body = MD->getBody();
8283  else if (auto *BD = dyn_cast<BlockDecl>(D))
8284  Body = BD->getBody();
8285 
8286  assert(Body && "Need a body here!");
8287 
8288  DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);
8289 }
8290 
8293  const ObjCInterfaceDecl *UnknownObjCClass,
8294  bool ObjCPropertyAccess,
8295  bool AvoidPartialAvailabilityChecks,
8296  ObjCInterfaceDecl *ClassReceiver) {
8297  std::string Message;
8298  AvailabilityResult Result;
8299  const NamedDecl* OffendingDecl;
8300  // See if this declaration is unavailable, deprecated, or partial.
8301  std::tie(Result, OffendingDecl) =
8302  ShouldDiagnoseAvailabilityOfDecl(*this, D, &Message, ClassReceiver);
8303  if (Result == AR_Available)
8304  return;
8305 
8306  if (Result == AR_NotYetIntroduced) {
8307  if (AvoidPartialAvailabilityChecks)
8308  return;
8309 
8310  // We need to know the @available context in the current function to
8311  // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that
8312  // when we're done parsing the current function.
8313  if (getCurFunctionOrMethodDecl()) {
8314  getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
8315  return;
8316  } else if (getCurBlock() || getCurLambda()) {
8317  getCurFunction()->HasPotentialAvailabilityViolations = true;
8318  return;
8319  }
8320  }
8321 
8322  const ObjCPropertyDecl *ObjCPDecl = nullptr;
8323  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
8324  if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
8325  AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
8326  if (PDeclResult == Result)
8327  ObjCPDecl = PD;
8328  }
8329  }
8330 
8331  EmitAvailabilityWarning(*this, Result, D, OffendingDecl, Message, Locs,
8332  UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess);
8333 }
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:577
static std::enable_if< std::is_base_of< Attr, AttrInfo >::value, SourceLocation >::type getAttrLoc(const AttrInfo &AL)
A helper function to provide Attribute Location for the Attr types AND the ParsedAttr.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Defines the clang::ASTContext interface.
unsigned getRegParmMax() const
Definition: TargetInfo.h:1137
static bool hasFunctionProto(const Decl *D)
hasFunctionProto - Return true if the given decl has a argument information.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:465
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1583
bool diagnoseAppertainsTo(class Sema &S, const Decl *D) const
Definition: ParsedAttr.cpp:208
Represents a function declaration or definition.
Definition: Decl.h:1738
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
ExtVectorDeclsType ExtVectorDecls
ExtVectorDecls - This is a list all the extended vector types.
Definition: Sema.h:561
VersionTuple getPlatformMinVersion() const
Retrieve the minimum desired version of the platform, to which the program should be compiled...
Definition: TargetInfo.h:1217
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
Smart pointer class that efficiently represents Objective-C method names.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2537
QualType getPointeeType() const
Definition: Type.h:2550
A (possibly-)qualified type.
Definition: Type.h:638
ASTConsumer & Consumer
Definition: Sema.h:325
bool isBlockPointerType() const
Definition: Type.h:6304
static void handleSimpleAttribute(Sema &S, Decl *D, SourceRange SR, unsigned SpellingIndex)
Applies the given attribute to the Decl without performing any additional semantic checking...
base_class_range bases()
Definition: DeclCXX.h:823
bool isMemberPointerType() const
Definition: Type.h:6327
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2778
bool isDeclspecAttribute() const
Definition: ParsedAttr.h:403
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:2902
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2179
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:3054
static QualType getFunctionOrMethodResultType(const Decl *D)
Stmt - This represents one statement.
Definition: Stmt.h:66
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3355
IfStmt - This represents an if/then/else.
Definition: Stmt.h:1687
void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex, bool IsPackExpansion)
AddAlignedAttr - Adds an aligned attribute to a particular declaration.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:955
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1020
Defines the SourceManager interface.
QualType getThisType() const
Returns the type of the this pointer.
Definition: DeclCXX.cpp:2184
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1066
void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr, unsigned SpellingListIndex)
AddAllocAlignAttr - Adds an alloc_align attribute to a particular declaration.
static InitializedEntity InitializeParameter(ASTContext &Context, const ParmVarDecl *Parm)
Create the initialization entity for a parameter.
const ObjCObjectType * getAsObjCInterfaceType() const
Definition: Type.cpp:1582
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1308
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes=true)
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:410
CommonAttr * mergeCommonAttr(Decl *D, const ParsedAttr &AL)
bool isExtVectorType() const
Definition: Type.h:6385
void PopParsingDeclaration(ParsingDeclState state, Decl *decl)
Defines the C++ template declaration subclasses.
IdentifierInfo * Ident
Definition: ParsedAttr.h:97
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration, or NULL if there is no previous declaration.
Definition: DeclBase.h:953
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6245
Expr * getArgAsExpr(unsigned Arg) const
Definition: ParsedAttr.h:460
The base class of the type hierarchy.
Definition: Type.h:1407
bool getMustBeNull() const
Definition: ParsedAttr.h:519
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:414
QualType withConst() const
Definition: Type.h:810
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:690
A container of type source information.
Definition: Decl.h:87
bool isCARCBridgableType() const
Determine whether the given type T is a "bridgeable" C type.
Definition: Type.cpp:3955
bool hasParsedType() const
Definition: ParsedAttr.h:391
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
unsigned getCharWidth() const
Definition: TargetInfo.h:371
virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const
Determines whether a given calling convention is valid for the target.
Definition: TargetInfo.h:1247
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:227
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2409
IdentifierInfo * getAlias() const
Definition: Weak.h:34
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
Definition: ASTContext.h:1188
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3169
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:540
void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name, unsigned SpellingListIndex, bool InInstantiation=false)
AddModeAttr - Adds a mode attribute to a particular declaration.
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:470
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2091
Represents a variable declaration or definition.
Definition: Decl.h:813
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1765
QualType getReturnType() const
Definition: Decl.h:2302
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6748
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:6679
ObjCInterfaceDecl * getClassReceiver() const
Definition: ExprObjC.h:734
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
bool isCXX11Attribute() const
Definition: ParsedAttr.h:406
bool isInvalidDecl() const
Definition: DeclBase.h:542
Stmt * getThen()
Definition: Stmt.h:1774
Not a TLS variable.
Definition: Decl.h:830
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type...
Definition: SemaDecl.cpp:277
bool hasDefinition() const
Definition: DeclCXX.h:776
Represents a parameter to a function.
Definition: Decl.h:1550
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:877
Defines the clang::Expr interface and subclasses for C++ expressions.
SourceLocation Loc
Definition: ParsedAttr.h:96
const Type * getTypePtr() const
Definition: TypeLoc.h:135
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g., it is a floating-point type or a vector thereof.
Definition: Type.cpp:1930
const ObjCPropertyDecl * getObjCProperty() const
const NamedDecl * getAvailabilityReferringDecl() const
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type. ...
Definition: Decl.cpp:3202
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:57
MSInheritanceAttr::Spelling calculateInheritanceModel() const
Calculate what the inheritance model would be for this class.
Represents a struct/union/class.
Definition: Decl.h:3593
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:349
const ParsedType & getMatchingCType() const
Definition: ParsedAttr.h:507
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:298
One of these records is kept for each identifier that is lexed.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:860
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1024
unsigned getAttributeSpellingListIndex() const
Get an index into the attribute spelling list defined in Attr.td.
Definition: ParsedAttr.cpp:157
static StringRef getIndentationForLine(SourceLocation Loc, const SourceManager &SM)
Returns the leading whitespace for line that corresponds to the given location Loc.
Definition: Lexer.cpp:1064
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ObjCMethodDecl * lookupInstanceMethod(Selector Sel) const
Lookup an instance method for a given selector.
Definition: DeclObjC.h:1847
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:155
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:7519
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1187
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum, const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis=false)
Check if IdxExpr is a valid parameter index for a function or instance method D.
bool isCharType() const
Definition: Type.cpp:1787
field_range fields() const
Definition: Decl.h:3784
NamedDecl * DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc)
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:288
bool isObjCIdType() const
Definition: Type.h:6422
Represents a member of a struct/union/class.
Definition: Decl.h:2579
unsigned getSourceIndex() const
Get the parameter index as it would normally be encoded for attributes at the source level of represe...
Definition: Attr.h:277
bool isGlobalVar(Expr *E)
Definition: Transforms.cpp:197
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str)
bool isReferenceType() const
Definition: Type.h:6308
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:406
Represents an access specifier followed by colon &#39;:&#39;.
Definition: DeclCXX.h:132
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:739
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr, uint32_t &Val, unsigned Idx=UINT_MAX, bool StrictlyUnsigned=false)
If Expr is a valid integer constant, get the value of the integer expression and return success or fa...
i32 captured_struct **param SharedsTy A type which contains references the shared variables *param Shareds Context with the list of shared variables from the p *TaskFunction *param Data Additional data for task generation like final * state
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, SourceRange Range, TypeVisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex)
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6644
Describes a module or submodule.
Definition: Module.h:65
IdentifierTable & Idents
Definition: ASTContext.h:566
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition: ParsedAttr.h:448
void setARCPseudoStrong(bool PS)
Definition: Decl.h:1361
const NamedDecl * getAvailabilityOffendingDecl() const
bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value)
virtual std::string isValidSectionSpecifier(StringRef SR) const
An optional hook that targets can implement to perform semantic checking on attribute((section("foo")...
Definition: TargetInfo.h:997
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment...
Represents the results of name lookup.
Definition: Lookup.h:47
PtrTy get() const
Definition: Ownership.h:174
void checkUnusedDeclAttributes(Declarator &D)
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:2731
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, unsigned AttrSpellingListIndex)
Attribute merging methods. Return true if a new attribute was added.
TagKind getTagKind() const
Definition: Decl.h:3243
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD=nullptr)
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing, variable initialization, and function return values.
Definition: SemaExpr.cpp:7789
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2067
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2175
Visibility getVisibility() const
Determine the visibility of this type.
Definition: Type.h:2301
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:753
bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str)
bool existsInTarget(const TargetInfo &Target) const
Definition: ParsedAttr.cpp:236
void steal(DelayedDiagnosticPool &pool)
Steal the diagnostics from the given pool.
bool isClassReceiver() const
Definition: ExprObjC.h:740
FormatAttr * mergeFormatAttr(Decl *D, SourceRange Range, IdentifierInfo *Format, int FormatIdx, int FirstArg, unsigned AttrSpellingListIndex)
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1196
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2595
unsigned getMinArgs() const
Definition: ParsedAttr.cpp:198
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
field_iterator field_begin() const
Definition: Decl.cpp:4145
CaseStmt - Represent a case statement.
Definition: Stmt.h:1394
bool hasVariadicArg() const
Definition: ParsedAttr.cpp:250
Represents information about a change in availability for an entity, which is part of the encoding of...
Definition: ParsedAttr.h:44
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1649
Preprocessor & PP
Definition: Sema.h:323
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:1918
const LangOptions & getLangOpts() const
Definition: Sema.h:1231
bool isGNUScope() const
Definition: ParsedAttr.h:386
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:167
#define UINT_MAX
Definition: limits.h:72
virtual unsigned getRegisterWidth() const
Return the "preferred" register width on this target.
Definition: TargetInfo.h:638
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Represents an ObjC class declaration.
Definition: DeclObjC.h:1172
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface...
Definition: Type.h:5773
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1765
MinSizeAttr * mergeMinSizeAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex)
bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceAttr::Spelling SemanticSpelling)
VersionTuple Version
The version number at which the change occurred.
Definition: ParsedAttr.h:49
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified=false, bool hasWrittenPrototype=true, bool isConstexprSpecified=false)
Definition: Decl.h:1875
const LangOptions & LangOpts
Definition: Sema.h:322
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
bool hasCustomParsing() const
Definition: ParsedAttr.cpp:204
static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx)
This object can be modified without requiring retains or releases.
Definition: Type.h:162
param_iterator param_begin()
Definition: Decl.h:2274
Represents the this expression in C++.
Definition: ExprCXX.h:976
void setInvalid(bool b=true) const
Definition: ParsedAttr.h:423
static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr, int &Val, unsigned Idx=UINT_MAX)
Wrapper around checkUInt32Argument, with an extra check to be sure that the result will fit into a re...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1595
AvailabilityResult
Captures the result of checking the availability of a declaration.
Definition: DeclBase.h:73
NodeId Parent
Definition: ASTDiff.cpp:192
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:218
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2014
llvm::StringRef getParameterABISpelling(ParameterABI kind)
bool canBeWeakImported(bool &IsDefinition) const
Determines whether this symbol can be weak-imported, e.g., whether it would be well-formed to add the...
Definition: DeclBase.cpp:655
bool hasAttr() const
Definition: DeclBase.h:531
static bool checkAttributeAtLeastNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num)
Check if the attribute has at least as many args as Num.
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W)
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:278
static Attr * handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1241
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1613
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3687
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:589
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:481
static bool checkAttributeNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num)
Check if the attribute has exactly as many args as Num.
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, unsigned AttrSpellingListIndex, MSInheritanceAttr::Spelling SemanticSpelling)
static const Sema::SemaDiagnosticBuilder & appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr)
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:569
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1541
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl&#39;s underlying type to extract a FunctionType when possible. ...
Definition: DeclBase.cpp:961
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
Captures information about a #pragma weak directive.
Definition: Weak.h:25
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
Exposes information about the current target.
Definition: TargetInfo.h:54
const ObjCInterfaceDecl * getUnknownObjCClass() const
void CheckAlignasUnderalignment(Decl *D)
static bool isCFStringType(QualType T, ASTContext &Ctx)
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:190
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:214
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2342
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
virtual bool hasProtectedVisibility() const
Does this target support "protected" visibility?
Definition: TargetInfo.h:984
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:637
This represents one expression.
Definition: Expr.h:106
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition: Lexer.cpp:771
Represents a character-granular source range.
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2689
int Id
Definition: ASTDiff.cpp:191
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
Kind getKind() const
Definition: ParsedAttr.h:443
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1036
static bool hasDeclarator(const Decl *D)
Return true if the given decl has a declarator that should have been processed by Sema::GetTypeForDec...
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:1614
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition: Lexer.cpp:1263
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to...
Definition: Type.cpp:1598
This file defines the classes used to store parsed information about declaration-specifiers and decla...
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6811
bool isObjCRetainableType() const
Definition: Type.cpp:3921
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:1983
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:1400
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
const AvailabilityChange & getAvailabilityObsoleted() const
Definition: ParsedAttr.h:482
Defines the clang::Preprocessor interface.
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:745
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
field_iterator field_end() const
Definition: Decl.h:3787
ObjCLifetime getObjCLifetime() const
Definition: Type.h:326
bool isFileContext() const
Definition: DeclBase.h:1818
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
DeclContext * getDeclContext()
Definition: DeclBase.h:427
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:769
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:108
unsigned short getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1151
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.h:2440
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
bool isValid() const
Determine whether this availability change is valid.
Definition: ParsedAttr.h:55
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1844
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:2695
bool isInvalid() const
QualType getType() const
Definition: Expr.h:128
void ProcessPragmaWeak(Scope *S, Decl *D)
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1752
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:904
static bool isNSStringType(QualType T, ASTContext &Ctx)
bool isInvalid() const
Definition: Ownership.h:170
Preprocessor & getPreprocessor() const
Definition: Sema.h:1237
Represents a GCC generic vector type.
Definition: Type.h:3168
unsigned getNumArgs() const
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:95
Expr * getCond()
Definition: Stmt.h:1762
ValueDecl * getDecl()
Definition: Expr.h:1114
VisibilityAttr * mergeVisibilityAttr(Decl *D, SourceRange Range, VisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex)
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:703
const SourceManager & SM
Definition: Format.cpp:1490
SourceLocation getLocation() const
Definition: Weak.h:35
void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex)
AddAlignValueAttr - Adds an align_value attribute to a particular declaration.
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:295
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:236
AttrVec & getAttrs()
Definition: DeclBase.h:479
bool hasAttrs() const
Definition: DeclBase.h:473
static CharSourceRange getCharRange(SourceRange R)
bool getLayoutCompatible() const
Definition: ParsedAttr.h:513
This is a scope that corresponds to the parameters within a function prototype for a function declara...
Definition: Scope.h:88
bool isVoidPointerType() const
Definition: Type.cpp:469
SourceLocation getEllipsisLoc() const
Definition: ParsedAttr.h:441
unsigned getSemanticSpelling() const
If the parsed attribute has a semantic equivalent, and it would have a semantic Spelling enumeration ...
Definition: ParsedAttr.cpp:246
void AddParameterABIAttr(SourceRange AttrRange, Decl *D, ParameterABI ABI, unsigned SpellingListIndex)
RecordDecl * getDecl() const
Definition: Type.h:4380
static bool checkAttributeAtMostNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num)
Check if the attribute has at most as many args as Num.
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
ArrayRef< SourceLocation > getAvailabilitySelectorLocs() const
unsigned getASTIndex() const
Get the parameter index as it would normally be encoded at the AST level of representation: zero-orig...
Definition: Attr.h:288
A parameter attribute which changes the argument-passing ABI rule for the parameter.
Definition: Attr.h:184
static bool isFunctionOrMethodOrBlock(const Decl *D)
Return true if the given decl has function type (function or function-typed variable) or an Objective...
CanQualType OverloadTy
Definition: ASTContext.h:1045
There is no lifetime qualification on this type.
Definition: Type.h:158
The "struct" keyword.
Definition: Type.h:5033
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:169
Kind
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:6365
not a target-specific vector type
Definition: Type.h:3172
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:157
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2558
LLVM_READONLY bool isValidIdentifier(StringRef S, bool AllowDollar=false)
Return true if this is a valid ASCII identifier.
Definition: CharInfo.h:185
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:218
ASTContext & getASTContext() const
Definition: Sema.h:1238
StringRef getPlatformName() const
Retrieve the name of the platform as it is used in the availability attribute.
Definition: TargetInfo.h:1213
unsigned getForbiddenTypeDiagnostic() const
The diagnostic ID to emit.
VersionTuple getVersionIntroduced() const
Retrieve the version of the target platform in which this declaration was introduced.
Definition: DeclBase.cpp:641
Encodes a location in the source.
unsigned getForbiddenTypeArgument() const
QualType getReturnType() const
Definition: Type.h:3613
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4396
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6188
const ParsedType & getTypeArg() const
Definition: ParsedAttr.h:525
void setUsed(bool Used=true)
Definition: Weak.h:36
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:292
DeclarationName getName() const
getName - Returns the embedded declaration name.
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3064
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:376
void AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex, RetainOwnershipKind K, bool IsTemplateInstantiation)
Stmt * getElse()
Definition: Stmt.h:1783
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:823
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:117
reverse_body_iterator body_rend()
Definition: Stmt.h:1315
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs. ...
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1759
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2041
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:688
bool hasProcessingCache() const
Definition: ParsedAttr.h:425
bool isUsedAsTypeAttr() const
Definition: ParsedAttr.h:437
SectionAttr * mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, unsigned AttrSpellingListIndex)
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2285
SourceLocation getLocation() const
Definition: Attr.h:94
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
void push_back(const T &LocalValue)
CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID)
Creates a CUDADiagBuilder that emits the diagnostic if the current context is "used as host code"...
Definition: SemaCUDA.cpp:723
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:149
bool isObjCObjectPointerType() const
Definition: Type.h:6393
bool isAnyPointerType() const
Definition: Type.h:6300
bool isArgExpr(unsigned Arg) const
Definition: ParsedAttr.h:456
bool diagnoseLangOpts(class Sema &S) const
Definition: ParsedAttr.cpp:224
AvailabilityResult getAvailabilityResult() const
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:729
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1303
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident, unsigned AttrSpellingListIndex)
bool isVectorType() const
Definition: Type.h:6381
Assigning into this object requires a lifetime extension.
Definition: Type.h:175
ParameterABI
Kinds of parameter ABI.
Definition: Specifiers.h:309
CUDAFunctionTarget CurrentCUDATarget()
Gets the CUDA target for the current context.
Definition: Sema.h:10173
SourceRange getRange() const
Definition: ParsedAttr.h:380
UuidAttr * mergeUuidAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex, StringRef Uuid)
DLLImportAttr * mergeDLLImportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex)
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:215
StringRef getName() const
Return the actual identifier string.
void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE, unsigned SpellingListIndex)
AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular declaration.
bool isMacroDefined(StringRef Id)
Definition: Preprocessor.h:916
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current target.
void setProcessingCache(unsigned value) const
Definition: ParsedAttr.h:432
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2916
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9125
bool isPipeType() const
Definition: Type.h:6477
static DelayedDiagnostic makeAvailability(AvailabilityResult AR, ArrayRef< SourceLocation > Locs, const NamedDecl *ReferringDecl, const NamedDecl *OffendingDecl, const ObjCInterfaceDecl *UnknownObjCClass, const ObjCPropertyDecl *ObjCProperty, StringRef Msg, bool ObjCPropertyAccess)
bool isStmtAttr() const
Definition: ParsedAttr.cpp:234
static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK)
Returns true if the given operator is implicitly static in a record context.
Definition: DeclCXX.h:2073
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
Don&#39;t merge availability attributes at all.
Definition: Sema.h:2446
void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1262
QualType getForbiddenTypeOperand() const
virtual char CPUSpecificManglingCharacter(StringRef Name) const
Definition: TargetInfo.h:1122
static unsigned getNumAttributeArgs(const ParsedAttr &AL)
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:399
void redelayDiagnostics(sema::DelayedDiagnosticPool &pool)
SourceRange getSourceRange(const SourceRange &Range)
Returns the SourceRange of a SourceRange.
Definition: FixIt.h:34
static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL)
Diagnose mutually exclusive attributes when present on a given declaration.
attr_range attrs() const
Definition: DeclBase.h:490
const AvailabilityChange & getAvailabilityIntroduced() const
Definition: ParsedAttr.h:472
A runtime availability query.
Definition: ExprObjC.h:1636
SmallVectorImpl< DelayedDiagnostic >::const_iterator pool_iterator
bool isPackExpansion() const
Definition: ParsedAttr.h:440
The name of a declaration.
StmtClass getStmtClass() const
Definition: Stmt.h:1029
bool isMicrosoftAttribute() const
Definition: ParsedAttr.h:404
SourceLocation getLoc() const
Definition: ParsedAttr.h:379
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2166
bool isBooleanType() const
Definition: Type.h:6657
SourceLocation getStrictLoc() const
Definition: ParsedAttr.h:487
bool isTypeAttr() const
Definition: ParsedAttr.cpp:232
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
IdentifierInfo * getName() const
Definition: ParsedAttr.h:378
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:3401
NamedDecl * getCurFunctionOrMethodDecl()
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we&#39;re in...
Definition: Sema.cpp:1216
SanitizerMask parseSanitizerValue(StringRef Value, bool AllowGroups)
Parse a single value from a -fsanitize= or -fno-sanitize= value list.
Definition: Sanitizers.cpp:19
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:2017
const AvailabilityChange & getAvailabilityDeprecated() const
Definition: ParsedAttr.h:477
param_iterator param_end()
Definition: Decl.h:2275
llvm::APInt getValue() const
Definition: Expr.h:1292
LLVM_READONLY bool isHexDigit(unsigned char c)
Return true if this character is an ASCII hex digit: [0-9a-fA-F].
Definition: CharInfo.h:124
static bool checkAttributeNumArgsImpl(Sema &S, const ParsedAttr &AL, unsigned Num, unsigned Diag, Compare Comp)
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr)
QualType getClassReceiver() const
Returns the type of a class message send, or NULL if the message is not a class message.
Definition: ExprObjC.h:1226
Represents a pointer to an Objective C object.
Definition: Type.h:5794
Pointer to a block type.
Definition: Type.h:2639
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4370
SourceLocation getBeginLoc() const
Definition: ExprObjC.h:1652
bool empty() const
Definition: Type.h:414
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
bool getUsed()
Definition: Weak.h:37
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6578
static bool isFunctionOrMethod(const Decl *D)
isFunctionOrMethod - Return true if the given decl has function type (function or function-typed vari...
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1771
T * getAttr() const
Definition: DeclBase.h:527
bool isImageType() const
Definition: Type.h:6470
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:716
DeclContext * getCurLexicalContext() const
Definition: Sema.h:10739
virtual bool isValidCPUName(StringRef Name) const
brief Determine whether this TargetInfo supports the given CPU name.
Definition: TargetInfo.h:1039
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2673
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1730
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2269
SourceLocation getEnd() const
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:92
CharSourceRange getExpansionRange(SourceLocation Loc) const
Given a SourceLocation object, return the range of tokens covered by the expansion in the ultimate fi...
const DelayedDiagnosticPool * getParent() const
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
Represents a base class of a C++ class.
Definition: DeclCXX.h:192
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2596
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2070
SourceManager & getSourceManager()
Definition: ASTContext.h:662
bool isObjCObjectType() const
Definition: Type.h:6397
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2031
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2356
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:1361
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:513
unsigned getMaxArgs() const
Definition: ParsedAttr.cpp:200
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13954
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
Reading or writing from this object requires a barrier call.
Definition: Type.h:172
bool isInvalid() const
Definition: ParsedAttr.h:422
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1009
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2687
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
static bool isInstanceMethod(const Decl *D)
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
Compatible - the types are compatible according to the standard.
Definition: Sema.h:9523
static unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
bool isValid() const
SourceLocation getSelectorStartLoc() const
Definition: ExprObjC.h:1366
bool isVoidType() const
Definition: Type.h:6544
reverse_body_iterator body_rbegin()
Definition: Stmt.h:1311
A diagnostic message which has been conditionally emitted pending the complete parsing of the current...
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1143
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6099
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1854
static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y)
Check whether the two versions match.
Definition: ObjCMT.cpp:1071
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates)...
Definition: Expr.h:214
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:3877
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:129
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2391
void addAttr(Attr *A)
Definition: DeclBase.cpp:840
static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D)
SourceManager & getSourceManager() const
Definition: Sema.h:1236
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:276
const Expr * getMessageExpr() const
Definition: ParsedAttr.h:497
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1566
Defines the clang::TargetInfo interface.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
__DEVICE__ int max(int __a, int __b)
CanQualType IntTy
Definition: ASTContext.h:1025
QualType getRealTypeForBitwidth(unsigned DestWidth) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2079
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1600
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1041
bool isUnion() const
Definition: Decl.h:3252
NamedDecl * getMostRecentDecl()
Definition: Decl.h:446
static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx)
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex)
bool isPointerType() const
Definition: Type.h:6296
DLLExportAttr * mergeDLLExportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex)
bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument ArgNum of Attr is a ASCII string literal.
SourceLocation getReceiverLocation() const
Definition: ExprObjC.h:728
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:66
class clang::Sema::DelayedDiagnostics DelayedDiagnostics
A collection of diagnostics which were delayed.
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2231
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluted - Return true if this expression might be usable in a constant expr...
QualType getType() const
Definition: Decl.h:648
bool isFloatingType() const
Definition: Type.cpp:1921
void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, Expr *MinBlocks, unsigned SpellingListIndex)
AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular declaration. ...
bool isArgIdent(unsigned Arg) const
Definition: ParsedAttr.h:464
A trivial tuple used to represent a source range.
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:299
ASTContext & Context
Definition: Sema.h:324
This represents a decl that may have a name.
Definition: Decl.h:249
void dropAttr()
Definition: DeclBase.h:502
Automatic storage duration (most local variables).
Definition: Specifiers.h:279
static bool isFunctionOrMethodVariadic(const Decl *D)
Describes an entity that is being initialized.
bool isFunctionPointerType() const
Definition: Type.h:6320
void setHasDesignatedInitializers()
Indicate that this interface decl contains at least one initializer marked with the &#39;objc_designated_...
Definition: DeclObjC.cpp:1515
StringRef getAvailabilityMessage() const
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3055
void setType(QualType newType)
Definition: Decl.h:649
SourceLocation getBegin() const
SourceLocation getUnavailableLoc() const
Definition: ParsedAttr.h:492
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:730
const LangOptions & getLangOpts() const
Definition: ASTContext.h:707
bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type)
AttributeDeclKind
These constants match the enumerated choices of warn_attribute_wrong_decl_type and err_attribute_wron...
Definition: ParsedAttr.h:965
RetainOwnershipKind
Definition: Sema.h:8577
This class handles loading and caching of source files into memory.
static const ParmVarDecl * getFunctionOrMethodParam(const Decl *D, unsigned Idx)
IdentifierLoc * getArgAsIdent(unsigned Arg) const
Definition: ParsedAttr.h:468
CodeSegAttr * mergeCodeSegAttr(Decl *D, SourceRange Range, StringRef Name, unsigned AttrSpellingListIndex)
bool isObjCNSObjectType() const
Definition: Type.cpp:3902
Attr - This represents one attribute.
Definition: Attr.h:44
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:762
SourceLocation getLocation() const
Definition: DeclBase.h:418
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3189
This parameter (which must have pointer type) is a Swift indirect result parameter.
virtual unsigned getUnwindWordWidth() const
Definition: TargetInfo.h:635
virtual bool validateCPUSpecificCPUDispatch(StringRef Name) const
Definition: TargetInfo.h:1117
IdentifierInfo * getScopeName() const
Definition: ParsedAttr.h:383
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type...
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth, signed/unsigned.
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1261
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition: Decl.cpp:1738
unsigned getProcessingCache() const
Definition: ParsedAttr.h:427
const Expr * getReplacementExpr() const
Definition: ParsedAttr.h:502
Stmt * getSubStmt()
Definition: Stmt.h:1513