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