Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Sema/SemaDeclAttr.cpp
Line
Count
Source (jump to first uncovered line)
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"
15
#include "clang/AST/ASTMutationListener.h"
16
#include "clang/AST/CXXInheritance.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"
23
#include "clang/AST/RecursiveASTVisitor.h"
24
#include "clang/AST/Type.h"
25
#include "clang/Basic/CharInfo.h"
26
#include "clang/Basic/Cuda.h"
27
#include "clang/Basic/DarwinSDKInfo.h"
28
#include "clang/Basic/HLSLRuntime.h"
29
#include "clang/Basic/LangOptions.h"
30
#include "clang/Basic/SourceLocation.h"
31
#include "clang/Basic/SourceManager.h"
32
#include "clang/Basic/TargetBuiltins.h"
33
#include "clang/Basic/TargetInfo.h"
34
#include "clang/Lex/Preprocessor.h"
35
#include "clang/Sema/DeclSpec.h"
36
#include "clang/Sema/DelayedDiagnostic.h"
37
#include "clang/Sema/Initialization.h"
38
#include "clang/Sema/Lookup.h"
39
#include "clang/Sema/ParsedAttr.h"
40
#include "clang/Sema/Scope.h"
41
#include "clang/Sema/ScopeInfo.h"
42
#include "clang/Sema/SemaInternal.h"
43
#include "llvm/ADT/STLExtras.h"
44
#include "llvm/ADT/StringExtras.h"
45
#include "llvm/IR/Assumptions.h"
46
#include "llvm/MC/MCSectionMachO.h"
47
#include "llvm/Support/Error.h"
48
#include "llvm/Support/MathExtras.h"
49
#include "llvm/Support/raw_ostream.h"
50
#include <optional>
51
52
using namespace clang;
53
using namespace sema;
54
55
namespace AttributeLangSupport {
56
  enum LANG {
57
    C,
58
    Cpp,
59
    ObjC
60
  };
61
} // end namespace AttributeLangSupport
62
63
//===----------------------------------------------------------------------===//
64
//  Helper functions
65
//===----------------------------------------------------------------------===//
66
67
/// isFunctionOrMethod - Return true if the given decl has function
68
/// type (function or function-typed variable) or an Objective-C
69
/// method.
70
0
static bool isFunctionOrMethod(const Decl *D) {
71
0
  return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
72
0
}
73
74
/// Return true if the given decl has function type (function or
75
/// function-typed variable) or an Objective-C method or a block.
76
0
static bool isFunctionOrMethodOrBlock(const Decl *D) {
77
0
  return isFunctionOrMethod(D) || isa<BlockDecl>(D);
78
0
}
79
80
/// Return true if the given decl has a declarator that should have
81
/// been processed by Sema::GetTypeForDeclarator.
82
0
static bool hasDeclarator(const Decl *D) {
83
  // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
84
0
  return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
85
0
         isa<ObjCPropertyDecl>(D);
86
0
}
87
88
/// hasFunctionProto - Return true if the given decl has a argument
89
/// information. This decl should have already passed
90
/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
91
0
static bool hasFunctionProto(const Decl *D) {
92
0
  if (const FunctionType *FnTy = D->getFunctionType())
93
0
    return isa<FunctionProtoType>(FnTy);
94
0
  return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
95
0
}
96
97
/// getFunctionOrMethodNumParams - Return number of function or method
98
/// parameters. It is an error to call this on a K&R function (use
99
/// hasFunctionProto first).
100
0
static unsigned getFunctionOrMethodNumParams(const Decl *D) {
101
0
  if (const FunctionType *FnTy = D->getFunctionType())
102
0
    return cast<FunctionProtoType>(FnTy)->getNumParams();
103
0
  if (const auto *BD = dyn_cast<BlockDecl>(D))
104
0
    return BD->getNumParams();
105
0
  return cast<ObjCMethodDecl>(D)->param_size();
106
0
}
107
108
static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D,
109
0
                                                   unsigned Idx) {
110
0
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
111
0
    return FD->getParamDecl(Idx);
112
0
  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
113
0
    return MD->getParamDecl(Idx);
114
0
  if (const auto *BD = dyn_cast<BlockDecl>(D))
115
0
    return BD->getParamDecl(Idx);
116
0
  return nullptr;
117
0
}
118
119
0
static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
120
0
  if (const FunctionType *FnTy = D->getFunctionType())
121
0
    return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
122
0
  if (const auto *BD = dyn_cast<BlockDecl>(D))
123
0
    return BD->getParamDecl(Idx)->getType();
124
125
0
  return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
126
0
}
127
128
0
static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
129
0
  if (auto *PVD = getFunctionOrMethodParam(D, Idx))
130
0
    return PVD->getSourceRange();
131
0
  return SourceRange();
132
0
}
133
134
0
static QualType getFunctionOrMethodResultType(const Decl *D) {
135
0
  if (const FunctionType *FnTy = D->getFunctionType())
136
0
    return FnTy->getReturnType();
137
0
  return cast<ObjCMethodDecl>(D)->getReturnType();
138
0
}
139
140
0
static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
141
0
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
142
0
    return FD->getReturnTypeSourceRange();
143
0
  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
144
0
    return MD->getReturnTypeSourceRange();
145
0
  return SourceRange();
146
0
}
147
148
0
static bool isFunctionOrMethodVariadic(const Decl *D) {
149
0
  if (const FunctionType *FnTy = D->getFunctionType())
150
0
    return cast<FunctionProtoType>(FnTy)->isVariadic();
151
0
  if (const auto *BD = dyn_cast<BlockDecl>(D))
152
0
    return BD->isVariadic();
153
0
  return cast<ObjCMethodDecl>(D)->isVariadic();
154
0
}
155
156
0
static bool isInstanceMethod(const Decl *D) {
157
0
  if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
158
0
    return MethodDecl->isInstance();
159
0
  return false;
160
0
}
161
162
static inline bool isNSStringType(QualType T, ASTContext &Ctx,
163
0
                                  bool AllowNSAttributedString = false) {
164
0
  const auto *PT = T->getAs<ObjCObjectPointerType>();
165
0
  if (!PT)
166
0
    return false;
167
168
0
  ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
169
0
  if (!Cls)
170
0
    return false;
171
172
0
  IdentifierInfo* ClsName = Cls->getIdentifier();
173
174
0
  if (AllowNSAttributedString &&
175
0
      ClsName == &Ctx.Idents.get("NSAttributedString"))
176
0
    return true;
177
  // FIXME: Should we walk the chain of classes?
178
0
  return ClsName == &Ctx.Idents.get("NSString") ||
179
0
         ClsName == &Ctx.Idents.get("NSMutableString");
180
0
}
181
182
0
static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
183
0
  const auto *PT = T->getAs<PointerType>();
184
0
  if (!PT)
185
0
    return false;
186
187
0
  const auto *RT = PT->getPointeeType()->getAs<RecordType>();
188
0
  if (!RT)
189
0
    return false;
190
191
0
  const RecordDecl *RD = RT->getDecl();
192
0
  if (RD->getTagKind() != TagTypeKind::Struct)
193
0
    return false;
194
195
0
  return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
196
0
}
197
198
0
static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
199
  // FIXME: Include the type in the argument list.
200
0
  return AL.getNumArgs() + AL.hasParsedType();
201
0
}
202
203
/// A helper function to provide Attribute Location for the Attr types
204
/// AND the ParsedAttr.
205
template <typename AttrInfo>
206
static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
207
0
getAttrLoc(const AttrInfo &AL) {
208
0
  return AL.getLocation();
209
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:_ZL10getAttrLocIN5clang27AMDGPUFlatWorkGroupSizeAttrEENSt3__19enable_ifIXsr3stdE12is_base_of_vINS0_4AttrET_EENS0_14SourceLocationEE4typeERKS5_
Unexecuted instantiation: SemaDeclAttr.cpp:_ZL10getAttrLocIN5clang20AMDGPUWavesPerEUAttrEENSt3__19enable_ifIXsr3stdE12is_base_of_vINS0_4AttrET_EENS0_14SourceLocationEE4typeERKS5_
Unexecuted instantiation: SemaDeclAttr.cpp:_ZL10getAttrLocIN5clang14AllocAlignAttrEENSt3__19enable_ifIXsr3stdE12is_base_of_vINS0_4AttrET_EENS0_14SourceLocationEE4typeERKS5_
210
0
static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
211
212
/// If Expr is a valid integer constant, get the value of the integer
213
/// expression and return success or failure. May output an error.
214
///
215
/// Negative argument is implicitly converted to unsigned, unless
216
/// \p StrictlyUnsigned is true.
217
template <typename AttrInfo>
218
static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
219
                                uint32_t &Val, unsigned Idx = UINT_MAX,
220
0
                                bool StrictlyUnsigned = false) {
221
0
  std::optional<llvm::APSInt> I = llvm::APSInt(32);
222
0
  if (Expr->isTypeDependent() ||
223
0
      !(I = Expr->getIntegerConstantExpr(S.Context))) {
224
0
    if (Idx != UINT_MAX)
225
0
      S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
226
0
          << &AI << Idx << AANT_ArgumentIntegerConstant
227
0
          << Expr->getSourceRange();
228
0
    else
229
0
      S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
230
0
          << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
231
0
    return false;
232
0
  }
233
234
0
  if (!I->isIntN(32)) {
235
0
    S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
236
0
        << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
237
0
    return false;
238
0
  }
239
240
0
  if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
241
0
    S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
242
0
        << &AI << /*non-negative*/ 1;
243
0
    return false;
244
0
  }
245
246
0
  Val = (uint32_t)I->getZExtValue();
247
0
  return true;
248
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkUInt32Argument<clang::AMDGPUFlatWorkGroupSizeAttr>(clang::Sema&, clang::AMDGPUFlatWorkGroupSizeAttr const&, clang::Expr const*, unsigned int&, unsigned int, bool)
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkUInt32Argument<clang::AMDGPUWavesPerEUAttr>(clang::Sema&, clang::AMDGPUWavesPerEUAttr const&, clang::Expr const*, unsigned int&, unsigned int, bool)
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkUInt32Argument<clang::ParsedAttr>(clang::Sema&, clang::ParsedAttr const&, clang::Expr const*, unsigned int&, unsigned int, bool)
249
250
/// Wrapper around checkUInt32Argument, with an extra check to be sure
251
/// that the result will fit into a regular (signed) int. All args have the same
252
/// purpose as they do in checkUInt32Argument.
253
template <typename AttrInfo>
254
static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
255
0
                                     int &Val, unsigned Idx = UINT_MAX) {
256
0
  uint32_t UVal;
257
0
  if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
258
0
    return false;
259
260
0
  if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
261
0
    llvm::APSInt I(32); // for toString
262
0
    I = UVal;
263
0
    S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
264
0
        << toString(I, 10, false) << 32 << /* Unsigned */ 0;
265
0
    return false;
266
0
  }
267
268
0
  Val = UVal;
269
0
  return true;
270
0
}
271
272
/// Diagnose mutually exclusive attributes when present on a given
273
/// declaration. Returns true if diagnosed.
274
template <typename AttrTy>
275
0
static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
276
0
  if (const auto *A = D->getAttr<AttrTy>()) {
277
0
    S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
278
0
        << AL << A
279
0
        << (AL.isRegularKeywordAttribute() || A->isRegularKeywordAttribute());
280
0
    S.Diag(A->getLocation(), diag::note_conflicting_attribute);
281
0
    return true;
282
0
  }
283
0
  return false;
284
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkAttrMutualExclusion<clang::Mips16Attr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkAttrMutualExclusion<clang::CPUSpecificAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkAttrMutualExclusion<clang::CPUDispatchAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkAttrMutualExclusion<clang::NoRandomizeLayoutAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkAttrMutualExclusion<clang::RandomizeLayoutAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkAttrMutualExclusion<clang::TargetClonesAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkAttrMutualExclusion<clang::PointerAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkAttrMutualExclusion<clang::OwnerAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
285
286
template <typename AttrTy>
287
static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
288
  if (const auto *A = D->getAttr<AttrTy>()) {
289
    S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible)
290
        << &AL << A
291
        << (AL.isRegularKeywordAttribute() || A->isRegularKeywordAttribute());
292
    S.Diag(A->getLocation(), diag::note_conflicting_attribute);
293
    return true;
294
  }
295
  return false;
296
}
297
298
/// Check if IdxExpr is a valid parameter index for a function or
299
/// instance method D.  May output an error.
300
///
301
/// \returns true if IdxExpr is a valid index.
302
template <typename AttrInfo>
303
static bool checkFunctionOrMethodParameterIndex(
304
    Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
305
0
    const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
306
0
  assert(isFunctionOrMethodOrBlock(D));
307
308
  // In C++ the implicit 'this' function parameter also counts.
309
  // Parameters are counted from one.
310
0
  bool HP = hasFunctionProto(D);
311
0
  bool HasImplicitThisParam = isInstanceMethod(D);
312
0
  bool IV = HP && isFunctionOrMethodVariadic(D);
313
0
  unsigned NumParams =
314
0
      (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
315
316
0
  std::optional<llvm::APSInt> IdxInt;
317
0
  if (IdxExpr->isTypeDependent() ||
318
0
      !(IdxInt = IdxExpr->getIntegerConstantExpr(S.Context))) {
319
0
    S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
320
0
        << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
321
0
        << IdxExpr->getSourceRange();
322
0
    return false;
323
0
  }
324
325
0
  unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX);
326
0
  if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
327
0
    S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
328
0
        << &AI << AttrArgNum << IdxExpr->getSourceRange();
329
0
    return false;
330
0
  }
331
0
  if (HasImplicitThisParam && !CanIndexImplicitThis) {
332
0
    if (IdxSource == 1) {
333
0
      S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
334
0
          << &AI << IdxExpr->getSourceRange();
335
0
      return false;
336
0
    }
337
0
  }
338
339
0
  Idx = ParamIdx(IdxSource, D);
340
0
  return true;
341
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkFunctionOrMethodParameterIndex<clang::ParsedAttr>(clang::Sema&, clang::Decl const*, clang::ParsedAttr const&, unsigned int, clang::Expr const*, clang::ParamIdx&, bool)
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkFunctionOrMethodParameterIndex<clang::AllocAlignAttr>(clang::Sema&, clang::Decl const*, clang::AllocAlignAttr const&, unsigned int, clang::Expr const*, clang::ParamIdx&, bool)
342
343
/// Check if the argument \p E is a ASCII string literal. If not emit an error
344
/// and return false, otherwise set \p Str to the value of the string literal
345
/// and return true.
346
bool Sema::checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
347
                                          const Expr *E, StringRef &Str,
348
0
                                          SourceLocation *ArgLocation) {
349
0
  const auto *Literal = dyn_cast<StringLiteral>(E->IgnoreParenCasts());
350
0
  if (ArgLocation)
351
0
    *ArgLocation = E->getBeginLoc();
352
353
0
  if (!Literal || (!Literal->isUnevaluated() && !Literal->isOrdinary())) {
354
0
    Diag(E->getBeginLoc(), diag::err_attribute_argument_type)
355
0
        << CI << AANT_ArgumentString;
356
0
    return false;
357
0
  }
358
359
0
  Str = Literal->getString();
360
0
  return true;
361
0
}
362
363
/// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
364
/// If not emit an error and return false. If the argument is an identifier it
365
/// will emit an error with a fixit hint and treat it as if it was a string
366
/// literal.
367
bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
368
                                          StringRef &Str,
369
0
                                          SourceLocation *ArgLocation) {
370
  // Look for identifiers. If we have one emit a hint to fix it to a literal.
371
0
  if (AL.isArgIdent(ArgNum)) {
372
0
    IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
373
0
    Diag(Loc->Loc, diag::err_attribute_argument_type)
374
0
        << AL << AANT_ArgumentString
375
0
        << FixItHint::CreateInsertion(Loc->Loc, "\"")
376
0
        << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
377
0
    Str = Loc->Ident->getName();
378
0
    if (ArgLocation)
379
0
      *ArgLocation = Loc->Loc;
380
0
    return true;
381
0
  }
382
383
  // Now check for an actual string literal.
384
0
  Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
385
0
  const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
386
0
  if (ArgLocation)
387
0
    *ArgLocation = ArgExpr->getBeginLoc();
388
389
0
  if (!Literal || (!Literal->isUnevaluated() && !Literal->isOrdinary())) {
390
0
    Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
391
0
        << AL << AANT_ArgumentString;
392
0
    return false;
393
0
  }
394
0
  Str = Literal->getString();
395
0
  return checkStringLiteralArgumentAttr(AL, ArgExpr, Str, ArgLocation);
396
0
}
397
398
/// Applies the given attribute to the Decl without performing any
399
/// additional semantic checking.
400
template <typename AttrType>
401
static void handleSimpleAttribute(Sema &S, Decl *D,
402
0
                                  const AttributeCommonInfo &CI) {
403
0
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
404
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::AVRInterruptAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::ReadOnlyPlacementAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::AVRSignalAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::BPFPreserveStaticOffsetAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::SYCLKernelAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::SYCLSpecialClassAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::MaybeUndefAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::AnyX86NoCfCheckAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::NoThrowAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::OSReturnsRetainedOnZeroAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::OSReturnsRetainedOnNonZeroAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::NSReturnsAutoreleasedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::CFReturnsNotRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::NSReturnsNotRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::CFReturnsRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::NSReturnsRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::OSReturnsRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::OSReturnsNotRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::ObjCDirectAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::ObjCDirectMembersAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::AvailableOnlyInDefaultEvalMethodAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::HLSLSV_GroupIndexAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::AlwaysDestroyAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::NoDestroyAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::ObjCExternallyRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::MIGServerRoutineAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::MSAllocatorAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::ArmLocallyStreamingAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::UsingIfExistsAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::OSConsumedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::NSConsumedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttribute<clang::CFConsumedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
405
406
template <typename... DiagnosticArgs>
407
static const Sema::SemaDiagnosticBuilder&
408
0
appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) {
409
0
  return Bldr;
410
0
}
411
412
template <typename T, typename... DiagnosticArgs>
413
static const Sema::SemaDiagnosticBuilder&
414
appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg,
415
0
                  DiagnosticArgs &&... ExtraArgs) {
416
0
  return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
417
0
                           std::forward<DiagnosticArgs>(ExtraArgs)...);
418
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:clang::Sema::SemaDiagnosticBuilder const& appendDiagnostics<clang::ParsedAttr const&, int, clang::SourceRange>(clang::Sema::SemaDiagnosticBuilder const&, clang::ParsedAttr const&, int&&, clang::SourceRange&&)
Unexecuted instantiation: SemaDeclAttr.cpp:clang::Sema::SemaDiagnosticBuilder const& appendDiagnostics<int, clang::SourceRange>(clang::Sema::SemaDiagnosticBuilder const&, int&&, clang::SourceRange&&)
Unexecuted instantiation: SemaDeclAttr.cpp:clang::Sema::SemaDiagnosticBuilder const& appendDiagnostics<clang::SourceRange>(clang::Sema::SemaDiagnosticBuilder const&, clang::SourceRange&&)
Unexecuted instantiation: SemaDeclAttr.cpp:clang::Sema::SemaDiagnosticBuilder const& appendDiagnostics<clang::SourceRange, char const (&) [12], int>(clang::Sema::SemaDiagnosticBuilder const&, clang::SourceRange&&, char const (&) [12], int&&)
Unexecuted instantiation: SemaDeclAttr.cpp:clang::Sema::SemaDiagnosticBuilder const& appendDiagnostics<char const (&) [12], int>(clang::Sema::SemaDiagnosticBuilder const&, char const (&) [12], int&&)
Unexecuted instantiation: SemaDeclAttr.cpp:clang::Sema::SemaDiagnosticBuilder const& appendDiagnostics<int>(clang::Sema::SemaDiagnosticBuilder const&, int&&)
419
420
/// Add an attribute @c AttrType to declaration @c D, provided that
421
/// @c PassesCheck is true.
422
/// Otherwise, emit diagnostic @c DiagID, passing in all parameters
423
/// specified in @c ExtraArgs.
424
template <typename AttrType, typename... DiagnosticArgs>
425
static void handleSimpleAttributeOrDiagnose(Sema &S, Decl *D,
426
                                            const AttributeCommonInfo &CI,
427
                                            bool PassesCheck, unsigned DiagID,
428
0
                                            DiagnosticArgs &&... ExtraArgs) {
429
0
  if (!PassesCheck) {
430
0
    Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
431
0
    appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
432
0
    return;
433
0
  }
434
0
  handleSimpleAttribute<AttrType>(S, D, CI);
435
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttributeOrDiagnose<clang::OSReturnsRetainedOnZeroAttr, clang::ParsedAttr const&, int, clang::SourceRange>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, bool, unsigned int, clang::ParsedAttr const&, int&&, clang::SourceRange&&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttributeOrDiagnose<clang::OSReturnsRetainedOnNonZeroAttr, clang::ParsedAttr const&, int, clang::SourceRange>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, bool, unsigned int, clang::ParsedAttr const&, int&&, clang::SourceRange&&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttributeOrDiagnose<clang::OSConsumedAttr, clang::SourceRange, char const (&) [12], int>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, bool, unsigned int, clang::SourceRange&&, char const (&) [12], int&&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttributeOrDiagnose<clang::NSConsumedAttr, clang::SourceRange, char const (&) [12], int>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, bool, unsigned int, clang::SourceRange&&, char const (&) [12], int&&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleSimpleAttributeOrDiagnose<clang::CFConsumedAttr, clang::SourceRange, char const (&) [12], int>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, bool, unsigned int, clang::SourceRange&&, char const (&) [12], int&&)
436
437
/// Check if the passed-in expression is of type int or bool.
438
0
static bool isIntOrBool(Expr *Exp) {
439
0
  QualType QT = Exp->getType();
440
0
  return QT->isBooleanType() || QT->isIntegerType();
441
0
}
442
443
444
// Check to see if the type is a smart pointer of some kind.  We assume
445
// it's a smart pointer if it defines both operator-> and operator*.
446
0
static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
447
0
  auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
448
0
                                          OverloadedOperatorKind Op) {
449
0
    DeclContextLookupResult Result =
450
0
        Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op));
451
0
    return !Result.empty();
452
0
  };
453
454
0
  const RecordDecl *Record = RT->getDecl();
455
0
  bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
456
0
  bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
457
0
  if (foundStarOperator && foundArrowOperator)
458
0
    return true;
459
460
0
  const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
461
0
  if (!CXXRecord)
462
0
    return false;
463
464
0
  for (const auto &BaseSpecifier : CXXRecord->bases()) {
465
0
    if (!foundStarOperator)
466
0
      foundStarOperator = IsOverloadedOperatorPresent(
467
0
          BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
468
0
    if (!foundArrowOperator)
469
0
      foundArrowOperator = IsOverloadedOperatorPresent(
470
0
          BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
471
0
  }
472
473
0
  if (foundStarOperator && foundArrowOperator)
474
0
    return true;
475
476
0
  return false;
477
0
}
478
479
/// Check if passed in Decl is a pointer type.
480
/// Note that this function may produce an error message.
481
/// \return true if the Decl is a pointer type; false otherwise
482
static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
483
0
                                       const ParsedAttr &AL) {
484
0
  const auto *VD = cast<ValueDecl>(D);
485
0
  QualType QT = VD->getType();
486
0
  if (QT->isAnyPointerType())
487
0
    return true;
488
489
0
  if (const auto *RT = QT->getAs<RecordType>()) {
490
    // If it's an incomplete type, it could be a smart pointer; skip it.
491
    // (We don't want to force template instantiation if we can avoid it,
492
    // since that would alter the order in which templates are instantiated.)
493
0
    if (RT->isIncompleteType())
494
0
      return true;
495
496
0
    if (threadSafetyCheckIsSmartPointer(S, RT))
497
0
      return true;
498
0
  }
499
500
0
  S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
501
0
  return false;
502
0
}
503
504
/// Checks that the passed in QualType either is of RecordType or points
505
/// to RecordType. Returns the relevant RecordType, null if it does not exit.
506
0
static const RecordType *getRecordType(QualType QT) {
507
0
  if (const auto *RT = QT->getAs<RecordType>())
508
0
    return RT;
509
510
  // Now check if we point to record type.
511
0
  if (const auto *PT = QT->getAs<PointerType>())
512
0
    return PT->getPointeeType()->getAs<RecordType>();
513
514
0
  return nullptr;
515
0
}
516
517
template <typename AttrType>
518
0
static bool checkRecordDeclForAttr(const RecordDecl *RD) {
519
  // Check if the record itself has the attribute.
520
0
  if (RD->hasAttr<AttrType>())
521
0
    return true;
522
523
  // Else check if any base classes have the attribute.
524
0
  if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
525
0
    if (!CRD->forallBases([](const CXXRecordDecl *Base) {
526
0
          return !Base->hasAttr<AttrType>();
527
0
        }))
Unexecuted instantiation: SemaDeclAttr.cpp:checkRecordDeclForAttr<clang::CapabilityAttr>(clang::RecordDecl const*)::{lambda(clang::CXXRecordDecl const*)#1}::operator()(clang::CXXRecordDecl const*) const
Unexecuted instantiation: SemaDeclAttr.cpp:checkRecordDeclForAttr<clang::ScopedLockableAttr>(clang::RecordDecl const*)::{lambda(clang::CXXRecordDecl const*)#1}::operator()(clang::CXXRecordDecl const*) const
528
0
      return true;
529
0
  }
530
0
  return false;
531
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkRecordDeclForAttr<clang::CapabilityAttr>(clang::RecordDecl const*)
Unexecuted instantiation: SemaDeclAttr.cpp:bool checkRecordDeclForAttr<clang::ScopedLockableAttr>(clang::RecordDecl const*)
532
533
0
static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
534
0
  const RecordType *RT = getRecordType(Ty);
535
536
0
  if (!RT)
537
0
    return false;
538
539
  // Don't check for the capability if the class hasn't been defined yet.
540
0
  if (RT->isIncompleteType())
541
0
    return true;
542
543
  // Allow smart pointers to be used as capability objects.
544
  // FIXME -- Check the type that the smart pointer points to.
545
0
  if (threadSafetyCheckIsSmartPointer(S, RT))
546
0
    return true;
547
548
0
  return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
549
0
}
550
551
0
static bool checkTypedefTypeForCapability(QualType Ty) {
552
0
  const auto *TD = Ty->getAs<TypedefType>();
553
0
  if (!TD)
554
0
    return false;
555
556
0
  TypedefNameDecl *TN = TD->getDecl();
557
0
  if (!TN)
558
0
    return false;
559
560
0
  return TN->hasAttr<CapabilityAttr>();
561
0
}
562
563
0
static bool typeHasCapability(Sema &S, QualType Ty) {
564
0
  if (checkTypedefTypeForCapability(Ty))
565
0
    return true;
566
567
0
  if (checkRecordTypeForCapability(S, Ty))
568
0
    return true;
569
570
0
  return false;
571
0
}
572
573
0
static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
574
  // Capability expressions are simple expressions involving the boolean logic
575
  // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
576
  // a DeclRefExpr is found, its type should be checked to determine whether it
577
  // is a capability or not.
578
579
0
  if (const auto *E = dyn_cast<CastExpr>(Ex))
580
0
    return isCapabilityExpr(S, E->getSubExpr());
581
0
  else if (const auto *E = dyn_cast<ParenExpr>(Ex))
582
0
    return isCapabilityExpr(S, E->getSubExpr());
583
0
  else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
584
0
    if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
585
0
        E->getOpcode() == UO_Deref)
586
0
      return isCapabilityExpr(S, E->getSubExpr());
587
0
    return false;
588
0
  } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
589
0
    if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
590
0
      return isCapabilityExpr(S, E->getLHS()) &&
591
0
             isCapabilityExpr(S, E->getRHS());
592
0
    return false;
593
0
  }
594
595
0
  return typeHasCapability(S, Ex->getType());
596
0
}
597
598
/// Checks that all attribute arguments, starting from Sidx, resolve to
599
/// a capability object.
600
/// \param Sidx The attribute argument index to start checking with.
601
/// \param ParamIdxOk Whether an argument can be indexing into a function
602
/// parameter list.
603
static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
604
                                           const ParsedAttr &AL,
605
                                           SmallVectorImpl<Expr *> &Args,
606
                                           unsigned Sidx = 0,
607
0
                                           bool ParamIdxOk = false) {
608
0
  if (Sidx == AL.getNumArgs()) {
609
    // If we don't have any capability arguments, the attribute implicitly
610
    // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
611
    // a non-static method, and that the class is a (scoped) capability.
612
0
    const auto *MD = dyn_cast<const CXXMethodDecl>(D);
613
0
    if (MD && !MD->isStatic()) {
614
0
      const CXXRecordDecl *RD = MD->getParent();
615
      // FIXME -- need to check this again on template instantiation
616
0
      if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
617
0
          !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
618
0
        S.Diag(AL.getLoc(),
619
0
               diag::warn_thread_attribute_not_on_capability_member)
620
0
            << AL << MD->getParent();
621
0
    } else {
622
0
      S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
623
0
          << AL;
624
0
    }
625
0
  }
626
627
0
  for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
628
0
    Expr *ArgExp = AL.getArgAsExpr(Idx);
629
630
0
    if (ArgExp->isTypeDependent()) {
631
      // FIXME -- need to check this again on template instantiation
632
0
      Args.push_back(ArgExp);
633
0
      continue;
634
0
    }
635
636
0
    if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
637
0
      if (StrLit->getLength() == 0 ||
638
0
          (StrLit->isOrdinary() && StrLit->getString() == StringRef("*"))) {
639
        // Pass empty strings to the analyzer without warnings.
640
        // Treat "*" as the universal lock.
641
0
        Args.push_back(ArgExp);
642
0
        continue;
643
0
      }
644
645
      // We allow constant strings to be used as a placeholder for expressions
646
      // that are not valid C++ syntax, but warn that they are ignored.
647
0
      S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
648
0
      Args.push_back(ArgExp);
649
0
      continue;
650
0
    }
651
652
0
    QualType ArgTy = ArgExp->getType();
653
654
    // A pointer to member expression of the form  &MyClass::mu is treated
655
    // specially -- we need to look at the type of the member.
656
0
    if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
657
0
      if (UOp->getOpcode() == UO_AddrOf)
658
0
        if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
659
0
          if (DRE->getDecl()->isCXXInstanceMember())
660
0
            ArgTy = DRE->getDecl()->getType();
661
662
    // First see if we can just cast to record type, or pointer to record type.
663
0
    const RecordType *RT = getRecordType(ArgTy);
664
665
    // Now check if we index into a record type function param.
666
0
    if(!RT && ParamIdxOk) {
667
0
      const auto *FD = dyn_cast<FunctionDecl>(D);
668
0
      const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
669
0
      if(FD && IL) {
670
0
        unsigned int NumParams = FD->getNumParams();
671
0
        llvm::APInt ArgValue = IL->getValue();
672
0
        uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
673
0
        uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
674
0
        if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
675
0
          S.Diag(AL.getLoc(),
676
0
                 diag::err_attribute_argument_out_of_bounds_extra_info)
677
0
              << AL << Idx + 1 << NumParams;
678
0
          continue;
679
0
        }
680
0
        ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
681
0
      }
682
0
    }
683
684
    // If the type does not have a capability, see if the components of the
685
    // expression have capabilities. This allows for writing C code where the
686
    // capability may be on the type, and the expression is a capability
687
    // boolean logic expression. Eg) requires_capability(A || B && !C)
688
0
    if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
689
0
      S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
690
0
          << AL << ArgTy;
691
692
0
    Args.push_back(ArgExp);
693
0
  }
694
0
}
695
696
//===----------------------------------------------------------------------===//
697
// Attribute Implementations
698
//===----------------------------------------------------------------------===//
699
700
0
static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
701
0
  if (!threadSafetyCheckIsPointer(S, D, AL))
702
0
    return;
703
704
0
  D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL));
705
0
}
706
707
static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
708
0
                                     Expr *&Arg) {
709
0
  SmallVector<Expr *, 1> Args;
710
  // check that all arguments are lockable objects
711
0
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
712
0
  unsigned Size = Args.size();
713
0
  if (Size != 1)
714
0
    return false;
715
716
0
  Arg = Args[0];
717
718
0
  return true;
719
0
}
720
721
0
static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
722
0
  Expr *Arg = nullptr;
723
0
  if (!checkGuardedByAttrCommon(S, D, AL, Arg))
724
0
    return;
725
726
0
  D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg));
727
0
}
728
729
0
static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
730
0
  Expr *Arg = nullptr;
731
0
  if (!checkGuardedByAttrCommon(S, D, AL, Arg))
732
0
    return;
733
734
0
  if (!threadSafetyCheckIsPointer(S, D, AL))
735
0
    return;
736
737
0
  D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg));
738
0
}
739
740
static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
741
0
                                        SmallVectorImpl<Expr *> &Args) {
742
0
  if (!AL.checkAtLeastNumArgs(S, 1))
743
0
    return false;
744
745
  // Check that this attribute only applies to lockable types.
746
0
  QualType QT = cast<ValueDecl>(D)->getType();
747
0
  if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
748
0
    S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
749
0
    return false;
750
0
  }
751
752
  // Check that all arguments are lockable objects.
753
0
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
754
0
  if (Args.empty())
755
0
    return false;
756
757
0
  return true;
758
0
}
759
760
0
static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
761
0
  SmallVector<Expr *, 1> Args;
762
0
  if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
763
0
    return;
764
765
0
  Expr **StartArg = &Args[0];
766
0
  D->addAttr(::new (S.Context)
767
0
                 AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
768
0
}
769
770
0
static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
771
0
  SmallVector<Expr *, 1> Args;
772
0
  if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
773
0
    return;
774
775
0
  Expr **StartArg = &Args[0];
776
0
  D->addAttr(::new (S.Context)
777
0
                 AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
778
0
}
779
780
static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
781
0
                                   SmallVectorImpl<Expr *> &Args) {
782
  // zero or more arguments ok
783
  // check that all arguments are lockable objects
784
0
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
785
786
0
  return true;
787
0
}
788
789
0
static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
790
0
  SmallVector<Expr *, 1> Args;
791
0
  if (!checkLockFunAttrCommon(S, D, AL, Args))
792
0
    return;
793
794
0
  unsigned Size = Args.size();
795
0
  Expr **StartArg = Size == 0 ? nullptr : &Args[0];
796
0
  D->addAttr(::new (S.Context)
797
0
                 AssertSharedLockAttr(S.Context, AL, StartArg, Size));
798
0
}
799
800
static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
801
0
                                          const ParsedAttr &AL) {
802
0
  SmallVector<Expr *, 1> Args;
803
0
  if (!checkLockFunAttrCommon(S, D, AL, Args))
804
0
    return;
805
806
0
  unsigned Size = Args.size();
807
0
  Expr **StartArg = Size == 0 ? nullptr : &Args[0];
808
0
  D->addAttr(::new (S.Context)
809
0
                 AssertExclusiveLockAttr(S.Context, AL, StartArg, Size));
810
0
}
811
812
/// Checks to be sure that the given parameter number is in bounds, and
813
/// is an integral type. Will emit appropriate diagnostics if this returns
814
/// false.
815
///
816
/// AttrArgNo is used to actually retrieve the argument, so it's base-0.
817
template <typename AttrInfo>
818
static bool checkParamIsIntegerType(Sema &S, const Decl *D, const AttrInfo &AI,
819
0
                                    unsigned AttrArgNo) {
820
0
  assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
821
0
  Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
822
0
  ParamIdx Idx;
823
0
  if (!checkFunctionOrMethodParameterIndex(S, D, AI, AttrArgNo + 1, AttrArg,
824
0
                                           Idx))
825
0
    return false;
826
827
0
  QualType ParamTy = getFunctionOrMethodParamType(D, Idx.getASTIndex());
828
0
  if (!ParamTy->isIntegerType() && !ParamTy->isCharType()) {
829
0
    SourceLocation SrcLoc = AttrArg->getBeginLoc();
830
0
    S.Diag(SrcLoc, diag::err_attribute_integers_only)
831
0
        << AI << getFunctionOrMethodParamRange(D, Idx.getASTIndex());
832
0
    return false;
833
0
  }
834
0
  return true;
835
0
}
836
837
0
static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
838
0
  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
839
0
    return;
840
841
0
  assert(isFunctionOrMethod(D) && hasFunctionProto(D));
842
843
0
  QualType RetTy = getFunctionOrMethodResultType(D);
844
0
  if (!RetTy->isPointerType()) {
845
0
    S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
846
0
    return;
847
0
  }
848
849
0
  const Expr *SizeExpr = AL.getArgAsExpr(0);
850
0
  int SizeArgNoVal;
851
  // Parameter indices are 1-indexed, hence Index=1
852
0
  if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1))
853
0
    return;
854
0
  if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/0))
855
0
    return;
856
0
  ParamIdx SizeArgNo(SizeArgNoVal, D);
857
858
0
  ParamIdx NumberArgNo;
859
0
  if (AL.getNumArgs() == 2) {
860
0
    const Expr *NumberExpr = AL.getArgAsExpr(1);
861
0
    int Val;
862
    // Parameter indices are 1-based, hence Index=2
863
0
    if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2))
864
0
      return;
865
0
    if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/1))
866
0
      return;
867
0
    NumberArgNo = ParamIdx(Val, D);
868
0
  }
869
870
0
  D->addAttr(::new (S.Context)
871
0
                 AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
872
0
}
873
874
static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
875
0
                                      SmallVectorImpl<Expr *> &Args) {
876
0
  if (!AL.checkAtLeastNumArgs(S, 1))
877
0
    return false;
878
879
0
  if (!isIntOrBool(AL.getArgAsExpr(0))) {
880
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
881
0
        << AL << 1 << AANT_ArgumentIntOrBool;
882
0
    return false;
883
0
  }
884
885
  // check that all arguments are lockable objects
886
0
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
887
888
0
  return true;
889
0
}
890
891
static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
892
0
                                            const ParsedAttr &AL) {
893
0
  SmallVector<Expr*, 2> Args;
894
0
  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
895
0
    return;
896
897
0
  D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
898
0
      S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
899
0
}
900
901
static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
902
0
                                               const ParsedAttr &AL) {
903
0
  SmallVector<Expr*, 2> Args;
904
0
  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
905
0
    return;
906
907
0
  D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
908
0
      S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
909
0
}
910
911
0
static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
912
  // check that the argument is lockable object
913
0
  SmallVector<Expr*, 1> Args;
914
0
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
915
0
  unsigned Size = Args.size();
916
0
  if (Size == 0)
917
0
    return;
918
919
0
  D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
920
0
}
921
922
0
static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
923
0
  if (!AL.checkAtLeastNumArgs(S, 1))
924
0
    return;
925
926
  // check that all arguments are lockable objects
927
0
  SmallVector<Expr*, 1> Args;
928
0
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
929
0
  unsigned Size = Args.size();
930
0
  if (Size == 0)
931
0
    return;
932
0
  Expr **StartArg = &Args[0];
933
934
0
  D->addAttr(::new (S.Context)
935
0
                 LocksExcludedAttr(S.Context, AL, StartArg, Size));
936
0
}
937
938
static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
939
0
                                       Expr *&Cond, StringRef &Msg) {
940
0
  Cond = AL.getArgAsExpr(0);
941
0
  if (!Cond->isTypeDependent()) {
942
0
    ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
943
0
    if (Converted.isInvalid())
944
0
      return false;
945
0
    Cond = Converted.get();
946
0
  }
947
948
0
  if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
949
0
    return false;
950
951
0
  if (Msg.empty())
952
0
    Msg = "<no message provided>";
953
954
0
  SmallVector<PartialDiagnosticAt, 8> Diags;
955
0
  if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
956
0
      !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
957
0
                                                Diags)) {
958
0
    S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
959
0
    for (const PartialDiagnosticAt &PDiag : Diags)
960
0
      S.Diag(PDiag.first, PDiag.second);
961
0
    return false;
962
0
  }
963
0
  return true;
964
0
}
965
966
0
static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
967
0
  S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
968
969
0
  Expr *Cond;
970
0
  StringRef Msg;
971
0
  if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
972
0
    D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
973
0
}
974
975
0
static void handleErrorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
976
0
  StringRef NewUserDiagnostic;
977
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, NewUserDiagnostic))
978
0
    return;
979
0
  if (ErrorAttr *EA = S.mergeErrorAttr(D, AL, NewUserDiagnostic))
980
0
    D->addAttr(EA);
981
0
}
982
983
namespace {
984
/// Determines if a given Expr references any of the given function's
985
/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
986
class ArgumentDependenceChecker
987
    : public RecursiveASTVisitor<ArgumentDependenceChecker> {
988
#ifndef NDEBUG
989
  const CXXRecordDecl *ClassType;
990
#endif
991
  llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
992
  bool Result;
993
994
public:
995
0
  ArgumentDependenceChecker(const FunctionDecl *FD) {
996
0
#ifndef NDEBUG
997
0
    if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
998
0
      ClassType = MD->getParent();
999
0
    else
1000
0
      ClassType = nullptr;
1001
0
#endif
1002
0
    Parms.insert(FD->param_begin(), FD->param_end());
1003
0
  }
1004
1005
0
  bool referencesArgs(Expr *E) {
1006
0
    Result = false;
1007
0
    TraverseStmt(E);
1008
0
    return Result;
1009
0
  }
1010
1011
0
  bool VisitCXXThisExpr(CXXThisExpr *E) {
1012
0
    assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1013
0
           "`this` doesn't refer to the enclosing class?");
1014
0
    Result = true;
1015
0
    return false;
1016
0
  }
1017
1018
0
  bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1019
0
    if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1020
0
      if (Parms.count(PVD)) {
1021
0
        Result = true;
1022
0
        return false;
1023
0
      }
1024
0
    return true;
1025
0
  }
1026
};
1027
}
1028
1029
static void handleDiagnoseAsBuiltinAttr(Sema &S, Decl *D,
1030
0
                                        const ParsedAttr &AL) {
1031
0
  const auto *DeclFD = cast<FunctionDecl>(D);
1032
1033
0
  if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclFD))
1034
0
    if (!MethodDecl->isStatic()) {
1035
0
      S.Diag(AL.getLoc(), diag::err_attribute_no_member_function) << AL;
1036
0
      return;
1037
0
    }
1038
1039
0
  auto DiagnoseType = [&](unsigned Index, AttributeArgumentNType T) {
1040
0
    SourceLocation Loc = [&]() {
1041
0
      auto Union = AL.getArg(Index - 1);
1042
0
      if (Union.is<Expr *>())
1043
0
        return Union.get<Expr *>()->getBeginLoc();
1044
0
      return Union.get<IdentifierLoc *>()->Loc;
1045
0
    }();
1046
1047
0
    S.Diag(Loc, diag::err_attribute_argument_n_type) << AL << Index << T;
1048
0
  };
1049
1050
0
  FunctionDecl *AttrFD = [&]() -> FunctionDecl * {
1051
0
    if (!AL.isArgExpr(0))
1052
0
      return nullptr;
1053
0
    auto *F = dyn_cast_if_present<DeclRefExpr>(AL.getArgAsExpr(0));
1054
0
    if (!F)
1055
0
      return nullptr;
1056
0
    return dyn_cast_if_present<FunctionDecl>(F->getFoundDecl());
1057
0
  }();
1058
1059
0
  if (!AttrFD || !AttrFD->getBuiltinID(true)) {
1060
0
    DiagnoseType(1, AANT_ArgumentBuiltinFunction);
1061
0
    return;
1062
0
  }
1063
1064
0
  if (AttrFD->getNumParams() != AL.getNumArgs() - 1) {
1065
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments_for)
1066
0
        << AL << AttrFD << AttrFD->getNumParams();
1067
0
    return;
1068
0
  }
1069
1070
0
  SmallVector<unsigned, 8> Indices;
1071
1072
0
  for (unsigned I = 1; I < AL.getNumArgs(); ++I) {
1073
0
    if (!AL.isArgExpr(I)) {
1074
0
      DiagnoseType(I + 1, AANT_ArgumentIntegerConstant);
1075
0
      return;
1076
0
    }
1077
1078
0
    const Expr *IndexExpr = AL.getArgAsExpr(I);
1079
0
    uint32_t Index;
1080
1081
0
    if (!checkUInt32Argument(S, AL, IndexExpr, Index, I + 1, false))
1082
0
      return;
1083
1084
0
    if (Index > DeclFD->getNumParams()) {
1085
0
      S.Diag(AL.getLoc(), diag::err_attribute_bounds_for_function)
1086
0
          << AL << Index << DeclFD << DeclFD->getNumParams();
1087
0
      return;
1088
0
    }
1089
1090
0
    QualType T1 = AttrFD->getParamDecl(I - 1)->getType();
1091
0
    QualType T2 = DeclFD->getParamDecl(Index - 1)->getType();
1092
1093
0
    if (T1.getCanonicalType().getUnqualifiedType() !=
1094
0
        T2.getCanonicalType().getUnqualifiedType()) {
1095
0
      S.Diag(IndexExpr->getBeginLoc(), diag::err_attribute_parameter_types)
1096
0
          << AL << Index << DeclFD << T2 << I << AttrFD << T1;
1097
0
      return;
1098
0
    }
1099
1100
0
    Indices.push_back(Index - 1);
1101
0
  }
1102
1103
0
  D->addAttr(::new (S.Context) DiagnoseAsBuiltinAttr(
1104
0
      S.Context, AL, AttrFD, Indices.data(), Indices.size()));
1105
0
}
1106
1107
0
static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1108
0
  S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
1109
1110
0
  Expr *Cond;
1111
0
  StringRef Msg;
1112
0
  if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1113
0
    return;
1114
1115
0
  StringRef DiagTypeStr;
1116
0
  if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
1117
0
    return;
1118
1119
0
  DiagnoseIfAttr::DiagnosticType DiagType;
1120
0
  if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1121
0
    S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1122
0
           diag::err_diagnose_if_invalid_diagnostic_type);
1123
0
    return;
1124
0
  }
1125
1126
0
  bool ArgDependent = false;
1127
0
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
1128
0
    ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1129
0
  D->addAttr(::new (S.Context) DiagnoseIfAttr(
1130
0
      S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D)));
1131
0
}
1132
1133
0
static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1134
0
  static constexpr const StringRef kWildcard = "*";
1135
1136
0
  llvm::SmallVector<StringRef, 16> Names;
1137
0
  bool HasWildcard = false;
1138
1139
0
  const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) {
1140
0
    if (Name == kWildcard)
1141
0
      HasWildcard = true;
1142
0
    Names.push_back(Name);
1143
0
  };
1144
1145
  // Add previously defined attributes.
1146
0
  if (const auto *NBA = D->getAttr<NoBuiltinAttr>())
1147
0
    for (StringRef BuiltinName : NBA->builtinNames())
1148
0
      AddBuiltinName(BuiltinName);
1149
1150
  // Add current attributes.
1151
0
  if (AL.getNumArgs() == 0)
1152
0
    AddBuiltinName(kWildcard);
1153
0
  else
1154
0
    for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
1155
0
      StringRef BuiltinName;
1156
0
      SourceLocation LiteralLoc;
1157
0
      if (!S.checkStringLiteralArgumentAttr(AL, I, BuiltinName, &LiteralLoc))
1158
0
        return;
1159
1160
0
      if (Builtin::Context::isBuiltinFunc(BuiltinName))
1161
0
        AddBuiltinName(BuiltinName);
1162
0
      else
1163
0
        S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name)
1164
0
            << BuiltinName << AL;
1165
0
    }
1166
1167
  // Repeating the same attribute is fine.
1168
0
  llvm::sort(Names);
1169
0
  Names.erase(std::unique(Names.begin(), Names.end()), Names.end());
1170
1171
  // Empty no_builtin must be on its own.
1172
0
  if (HasWildcard && Names.size() > 1)
1173
0
    S.Diag(D->getLocation(),
1174
0
           diag::err_attribute_no_builtin_wildcard_or_builtin_name)
1175
0
        << AL;
1176
1177
0
  if (D->hasAttr<NoBuiltinAttr>())
1178
0
    D->dropAttr<NoBuiltinAttr>();
1179
0
  D->addAttr(::new (S.Context)
1180
0
                 NoBuiltinAttr(S.Context, AL, Names.data(), Names.size()));
1181
0
}
1182
1183
0
static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1184
0
  if (D->hasAttr<PassObjectSizeAttr>()) {
1185
0
    S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1186
0
    return;
1187
0
  }
1188
1189
0
  Expr *E = AL.getArgAsExpr(0);
1190
0
  uint32_t Type;
1191
0
  if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1192
0
    return;
1193
1194
  // pass_object_size's argument is passed in as the second argument of
1195
  // __builtin_object_size. So, it has the same constraints as that second
1196
  // argument; namely, it must be in the range [0, 3].
1197
0
  if (Type > 3) {
1198
0
    S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
1199
0
        << AL << 0 << 3 << E->getSourceRange();
1200
0
    return;
1201
0
  }
1202
1203
  // pass_object_size is only supported on constant pointer parameters; as a
1204
  // kindness to users, we allow the parameter to be non-const for declarations.
1205
  // At this point, we have no clue if `D` belongs to a function declaration or
1206
  // definition, so we defer the constness check until later.
1207
0
  if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1208
0
    S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1209
0
    return;
1210
0
  }
1211
1212
0
  D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
1213
0
}
1214
1215
0
static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1216
0
  ConsumableAttr::ConsumedState DefaultState;
1217
1218
0
  if (AL.isArgIdent(0)) {
1219
0
    IdentifierLoc *IL = AL.getArgAsIdent(0);
1220
0
    if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1221
0
                                                   DefaultState)) {
1222
0
      S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1223
0
                                                               << IL->Ident;
1224
0
      return;
1225
0
    }
1226
0
  } else {
1227
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1228
0
        << AL << AANT_ArgumentIdentifier;
1229
0
    return;
1230
0
  }
1231
1232
0
  D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
1233
0
}
1234
1235
static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1236
0
                                    const ParsedAttr &AL) {
1237
0
  QualType ThisType = MD->getFunctionObjectParameterType();
1238
1239
0
  if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1240
0
    if (!RD->hasAttr<ConsumableAttr>()) {
1241
0
      S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD;
1242
1243
0
      return false;
1244
0
    }
1245
0
  }
1246
1247
0
  return true;
1248
0
}
1249
1250
0
static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1251
0
  if (!AL.checkAtLeastNumArgs(S, 1))
1252
0
    return;
1253
1254
0
  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1255
0
    return;
1256
1257
0
  SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1258
0
  for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1259
0
    CallableWhenAttr::ConsumedState CallableState;
1260
1261
0
    StringRef StateString;
1262
0
    SourceLocation Loc;
1263
0
    if (AL.isArgIdent(ArgIndex)) {
1264
0
      IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1265
0
      StateString = Ident->Ident->getName();
1266
0
      Loc = Ident->Loc;
1267
0
    } else {
1268
0
      if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1269
0
        return;
1270
0
    }
1271
1272
0
    if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1273
0
                                                     CallableState)) {
1274
0
      S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1275
0
      return;
1276
0
    }
1277
1278
0
    States.push_back(CallableState);
1279
0
  }
1280
1281
0
  D->addAttr(::new (S.Context)
1282
0
                 CallableWhenAttr(S.Context, AL, States.data(), States.size()));
1283
0
}
1284
1285
0
static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1286
0
  ParamTypestateAttr::ConsumedState ParamState;
1287
1288
0
  if (AL.isArgIdent(0)) {
1289
0
    IdentifierLoc *Ident = AL.getArgAsIdent(0);
1290
0
    StringRef StateString = Ident->Ident->getName();
1291
1292
0
    if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1293
0
                                                       ParamState)) {
1294
0
      S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1295
0
          << AL << StateString;
1296
0
      return;
1297
0
    }
1298
0
  } else {
1299
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1300
0
        << AL << AANT_ArgumentIdentifier;
1301
0
    return;
1302
0
  }
1303
1304
  // FIXME: This check is currently being done in the analysis.  It can be
1305
  //        enabled here only after the parser propagates attributes at
1306
  //        template specialization definition, not declaration.
1307
  //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1308
  //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1309
  //
1310
  //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1311
  //    S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1312
  //      ReturnType.getAsString();
1313
  //    return;
1314
  //}
1315
1316
0
  D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
1317
0
}
1318
1319
0
static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1320
0
  ReturnTypestateAttr::ConsumedState ReturnState;
1321
1322
0
  if (AL.isArgIdent(0)) {
1323
0
    IdentifierLoc *IL = AL.getArgAsIdent(0);
1324
0
    if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1325
0
                                                        ReturnState)) {
1326
0
      S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1327
0
                                                               << IL->Ident;
1328
0
      return;
1329
0
    }
1330
0
  } else {
1331
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1332
0
        << AL << AANT_ArgumentIdentifier;
1333
0
    return;
1334
0
  }
1335
1336
  // FIXME: This check is currently being done in the analysis.  It can be
1337
  //        enabled here only after the parser propagates attributes at
1338
  //        template specialization definition, not declaration.
1339
  // QualType ReturnType;
1340
  //
1341
  // if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1342
  //  ReturnType = Param->getType();
1343
  //
1344
  //} else if (const CXXConstructorDecl *Constructor =
1345
  //             dyn_cast<CXXConstructorDecl>(D)) {
1346
  //  ReturnType = Constructor->getFunctionObjectParameterType();
1347
  //
1348
  //} else {
1349
  //
1350
  //  ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1351
  //}
1352
  //
1353
  // const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1354
  //
1355
  // if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1356
  //    S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1357
  //      ReturnType.getAsString();
1358
  //    return;
1359
  //}
1360
1361
0
  D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
1362
0
}
1363
1364
0
static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1365
0
  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1366
0
    return;
1367
1368
0
  SetTypestateAttr::ConsumedState NewState;
1369
0
  if (AL.isArgIdent(0)) {
1370
0
    IdentifierLoc *Ident = AL.getArgAsIdent(0);
1371
0
    StringRef Param = Ident->Ident->getName();
1372
0
    if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1373
0
      S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1374
0
                                                                  << Param;
1375
0
      return;
1376
0
    }
1377
0
  } else {
1378
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1379
0
        << AL << AANT_ArgumentIdentifier;
1380
0
    return;
1381
0
  }
1382
1383
0
  D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
1384
0
}
1385
1386
0
static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1387
0
  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1388
0
    return;
1389
1390
0
  TestTypestateAttr::ConsumedState TestState;
1391
0
  if (AL.isArgIdent(0)) {
1392
0
    IdentifierLoc *Ident = AL.getArgAsIdent(0);
1393
0
    StringRef Param = Ident->Ident->getName();
1394
0
    if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1395
0
      S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1396
0
                                                                  << Param;
1397
0
      return;
1398
0
    }
1399
0
  } else {
1400
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1401
0
        << AL << AANT_ArgumentIdentifier;
1402
0
    return;
1403
0
  }
1404
1405
0
  D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
1406
0
}
1407
1408
0
static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1409
  // Remember this typedef decl, we will need it later for diagnostics.
1410
0
  S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1411
0
}
1412
1413
0
static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1414
0
  if (auto *TD = dyn_cast<TagDecl>(D))
1415
0
    TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1416
0
  else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1417
0
    bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1418
0
                                !FD->getType()->isIncompleteType() &&
1419
0
                                FD->isBitField() &&
1420
0
                                S.Context.getTypeAlign(FD->getType()) <= 8);
1421
1422
0
    if (S.getASTContext().getTargetInfo().getTriple().isPS()) {
1423
0
      if (BitfieldByteAligned)
1424
        // The PS4/PS5 targets need to maintain ABI backwards compatibility.
1425
0
        S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1426
0
            << AL << FD->getType();
1427
0
      else
1428
0
        FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1429
0
    } else {
1430
      // Report warning about changed offset in the newer compiler versions.
1431
0
      if (BitfieldByteAligned)
1432
0
        S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1433
1434
0
      FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1435
0
    }
1436
1437
0
  } else
1438
0
    S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1439
0
}
1440
1441
0
static void handlePreferredName(Sema &S, Decl *D, const ParsedAttr &AL) {
1442
0
  auto *RD = cast<CXXRecordDecl>(D);
1443
0
  ClassTemplateDecl *CTD = RD->getDescribedClassTemplate();
1444
0
  assert(CTD && "attribute does not appertain to this declaration");
1445
1446
0
  ParsedType PT = AL.getTypeArg();
1447
0
  TypeSourceInfo *TSI = nullptr;
1448
0
  QualType T = S.GetTypeFromParser(PT, &TSI);
1449
0
  if (!TSI)
1450
0
    TSI = S.Context.getTrivialTypeSourceInfo(T, AL.getLoc());
1451
1452
0
  if (!T.hasQualifiers() && T->isTypedefNameType()) {
1453
    // Find the template name, if this type names a template specialization.
1454
0
    const TemplateDecl *Template = nullptr;
1455
0
    if (const auto *CTSD = dyn_cast_if_present<ClassTemplateSpecializationDecl>(
1456
0
            T->getAsCXXRecordDecl())) {
1457
0
      Template = CTSD->getSpecializedTemplate();
1458
0
    } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
1459
0
      while (TST && TST->isTypeAlias())
1460
0
        TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1461
0
      if (TST)
1462
0
        Template = TST->getTemplateName().getAsTemplateDecl();
1463
0
    }
1464
1465
0
    if (Template && declaresSameEntity(Template, CTD)) {
1466
0
      D->addAttr(::new (S.Context) PreferredNameAttr(S.Context, AL, TSI));
1467
0
      return;
1468
0
    }
1469
0
  }
1470
1471
0
  S.Diag(AL.getLoc(), diag::err_attribute_preferred_name_arg_invalid)
1472
0
      << T << CTD;
1473
0
  if (const auto *TT = T->getAs<TypedefType>())
1474
0
    S.Diag(TT->getDecl()->getLocation(), diag::note_entity_declared_at)
1475
0
        << TT->getDecl();
1476
0
}
1477
1478
0
static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1479
  // The IBOutlet/IBOutletCollection attributes only apply to instance
1480
  // variables or properties of Objective-C classes.  The outlet must also
1481
  // have an object reference type.
1482
0
  if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1483
0
    if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1484
0
      S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1485
0
          << AL << VD->getType() << 0;
1486
0
      return false;
1487
0
    }
1488
0
  }
1489
0
  else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1490
0
    if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1491
0
      S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1492
0
          << AL << PD->getType() << 1;
1493
0
      return false;
1494
0
    }
1495
0
  }
1496
0
  else {
1497
0
    S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1498
0
    return false;
1499
0
  }
1500
1501
0
  return true;
1502
0
}
1503
1504
0
static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1505
0
  if (!checkIBOutletCommon(S, D, AL))
1506
0
    return;
1507
1508
0
  D->addAttr(::new (S.Context) IBOutletAttr(S.Context, AL));
1509
0
}
1510
1511
0
static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1512
1513
  // The iboutletcollection attribute can have zero or one arguments.
1514
0
  if (AL.getNumArgs() > 1) {
1515
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1516
0
    return;
1517
0
  }
1518
1519
0
  if (!checkIBOutletCommon(S, D, AL))
1520
0
    return;
1521
1522
0
  ParsedType PT;
1523
1524
0
  if (AL.hasParsedType())
1525
0
    PT = AL.getTypeArg();
1526
0
  else {
1527
0
    PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1528
0
                       S.getScopeForContext(D->getDeclContext()->getParent()));
1529
0
    if (!PT) {
1530
0
      S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1531
0
      return;
1532
0
    }
1533
0
  }
1534
1535
0
  TypeSourceInfo *QTLoc = nullptr;
1536
0
  QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1537
0
  if (!QTLoc)
1538
0
    QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1539
1540
  // Diagnose use of non-object type in iboutletcollection attribute.
1541
  // FIXME. Gnu attribute extension ignores use of builtin types in
1542
  // attributes. So, __attribute__((iboutletcollection(char))) will be
1543
  // treated as __attribute__((iboutletcollection())).
1544
0
  if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1545
0
    S.Diag(AL.getLoc(),
1546
0
           QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1547
0
                               : diag::err_iboutletcollection_type) << QT;
1548
0
    return;
1549
0
  }
1550
1551
0
  D->addAttr(::new (S.Context) IBOutletCollectionAttr(S.Context, AL, QTLoc));
1552
0
}
1553
1554
0
bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1555
0
  if (RefOkay) {
1556
0
    if (T->isReferenceType())
1557
0
      return true;
1558
0
  } else {
1559
0
    T = T.getNonReferenceType();
1560
0
  }
1561
1562
  // The nonnull attribute, and other similar attributes, can be applied to a
1563
  // transparent union that contains a pointer type.
1564
0
  if (const RecordType *UT = T->getAsUnionType()) {
1565
0
    if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1566
0
      RecordDecl *UD = UT->getDecl();
1567
0
      for (const auto *I : UD->fields()) {
1568
0
        QualType QT = I->getType();
1569
0
        if (QT->isAnyPointerType() || QT->isBlockPointerType())
1570
0
          return true;
1571
0
      }
1572
0
    }
1573
0
  }
1574
1575
0
  return T->isAnyPointerType() || T->isBlockPointerType();
1576
0
}
1577
1578
static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1579
                                SourceRange AttrParmRange,
1580
                                SourceRange TypeRange,
1581
0
                                bool isReturnValue = false) {
1582
0
  if (!S.isValidPointerAttrType(T)) {
1583
0
    if (isReturnValue)
1584
0
      S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1585
0
          << AL << AttrParmRange << TypeRange;
1586
0
    else
1587
0
      S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1588
0
          << AL << AttrParmRange << TypeRange << 0;
1589
0
    return false;
1590
0
  }
1591
0
  return true;
1592
0
}
1593
1594
0
static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1595
0
  SmallVector<ParamIdx, 8> NonNullArgs;
1596
0
  for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1597
0
    Expr *Ex = AL.getArgAsExpr(I);
1598
0
    ParamIdx Idx;
1599
0
    if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1600
0
      return;
1601
1602
    // Is the function argument a pointer type?
1603
0
    if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1604
0
        !attrNonNullArgCheck(
1605
0
            S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1606
0
            Ex->getSourceRange(),
1607
0
            getFunctionOrMethodParamRange(D, Idx.getASTIndex())))
1608
0
      continue;
1609
1610
0
    NonNullArgs.push_back(Idx);
1611
0
  }
1612
1613
  // If no arguments were specified to __attribute__((nonnull)) then all pointer
1614
  // arguments have a nonnull attribute; warn if there aren't any. Skip this
1615
  // check if the attribute came from a macro expansion or a template
1616
  // instantiation.
1617
0
  if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1618
0
      !S.inTemplateInstantiation()) {
1619
0
    bool AnyPointers = isFunctionOrMethodVariadic(D);
1620
0
    for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1621
0
         I != E && !AnyPointers; ++I) {
1622
0
      QualType T = getFunctionOrMethodParamType(D, I);
1623
0
      if (T->isDependentType() || S.isValidPointerAttrType(T))
1624
0
        AnyPointers = true;
1625
0
    }
1626
1627
0
    if (!AnyPointers)
1628
0
      S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1629
0
  }
1630
1631
0
  ParamIdx *Start = NonNullArgs.data();
1632
0
  unsigned Size = NonNullArgs.size();
1633
0
  llvm::array_pod_sort(Start, Start + Size);
1634
0
  D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
1635
0
}
1636
1637
static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1638
0
                                       const ParsedAttr &AL) {
1639
0
  if (AL.getNumArgs() > 0) {
1640
0
    if (D->getFunctionType()) {
1641
0
      handleNonNullAttr(S, D, AL);
1642
0
    } else {
1643
0
      S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1644
0
        << D->getSourceRange();
1645
0
    }
1646
0
    return;
1647
0
  }
1648
1649
  // Is the argument a pointer type?
1650
0
  if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1651
0
                           D->getSourceRange()))
1652
0
    return;
1653
1654
0
  D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
1655
0
}
1656
1657
0
static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1658
0
  QualType ResultType = getFunctionOrMethodResultType(D);
1659
0
  SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1660
0
  if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1661
0
                           /* isReturnValue */ true))
1662
0
    return;
1663
1664
0
  D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
1665
0
}
1666
1667
0
static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1668
0
  if (D->isInvalidDecl())
1669
0
    return;
1670
1671
  // noescape only applies to pointer types.
1672
0
  QualType T = cast<ParmVarDecl>(D)->getType();
1673
0
  if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1674
0
    S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1675
0
        << AL << AL.getRange() << 0;
1676
0
    return;
1677
0
  }
1678
1679
0
  D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL));
1680
0
}
1681
1682
0
static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1683
0
  Expr *E = AL.getArgAsExpr(0),
1684
0
       *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1685
0
  S.AddAssumeAlignedAttr(D, AL, E, OE);
1686
0
}
1687
1688
0
static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1689
0
  S.AddAllocAlignAttr(D, AL, AL.getArgAsExpr(0));
1690
0
}
1691
1692
void Sema::AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
1693
0
                                Expr *OE) {
1694
0
  QualType ResultType = getFunctionOrMethodResultType(D);
1695
0
  SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1696
1697
0
  AssumeAlignedAttr TmpAttr(Context, CI, E, OE);
1698
0
  SourceLocation AttrLoc = TmpAttr.getLocation();
1699
1700
0
  if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1701
0
    Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1702
0
        << &TmpAttr << TmpAttr.getRange() << SR;
1703
0
    return;
1704
0
  }
1705
1706
0
  if (!E->isValueDependent()) {
1707
0
    std::optional<llvm::APSInt> I = llvm::APSInt(64);
1708
0
    if (!(I = E->getIntegerConstantExpr(Context))) {
1709
0
      if (OE)
1710
0
        Diag(AttrLoc, diag::err_attribute_argument_n_type)
1711
0
          << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1712
0
          << E->getSourceRange();
1713
0
      else
1714
0
        Diag(AttrLoc, diag::err_attribute_argument_type)
1715
0
          << &TmpAttr << AANT_ArgumentIntegerConstant
1716
0
          << E->getSourceRange();
1717
0
      return;
1718
0
    }
1719
1720
0
    if (!I->isPowerOf2()) {
1721
0
      Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1722
0
        << E->getSourceRange();
1723
0
      return;
1724
0
    }
1725
1726
0
    if (*I > Sema::MaximumAlignment)
1727
0
      Diag(CI.getLoc(), diag::warn_assume_aligned_too_great)
1728
0
          << CI.getRange() << Sema::MaximumAlignment;
1729
0
  }
1730
1731
0
  if (OE && !OE->isValueDependent() && !OE->isIntegerConstantExpr(Context)) {
1732
0
    Diag(AttrLoc, diag::err_attribute_argument_n_type)
1733
0
        << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1734
0
        << OE->getSourceRange();
1735
0
    return;
1736
0
  }
1737
1738
0
  D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
1739
0
}
1740
1741
void Sema::AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
1742
0
                             Expr *ParamExpr) {
1743
0
  QualType ResultType = getFunctionOrMethodResultType(D);
1744
1745
0
  AllocAlignAttr TmpAttr(Context, CI, ParamIdx());
1746
0
  SourceLocation AttrLoc = CI.getLoc();
1747
1748
0
  if (!ResultType->isDependentType() &&
1749
0
      !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1750
0
    Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1751
0
        << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
1752
0
    return;
1753
0
  }
1754
1755
0
  ParamIdx Idx;
1756
0
  const auto *FuncDecl = cast<FunctionDecl>(D);
1757
0
  if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1758
0
                                           /*AttrArgNum=*/1, ParamExpr, Idx))
1759
0
    return;
1760
1761
0
  QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1762
0
  if (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
1763
0
      !Ty->isAlignValT()) {
1764
0
    Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1765
0
        << &TmpAttr
1766
0
        << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1767
0
    return;
1768
0
  }
1769
1770
0
  D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx));
1771
0
}
1772
1773
/// Check if \p AssumptionStr is a known assumption and warn if not.
1774
static void checkAssumptionAttr(Sema &S, SourceLocation Loc,
1775
0
                                StringRef AssumptionStr) {
1776
0
  if (llvm::KnownAssumptionStrings.count(AssumptionStr))
1777
0
    return;
1778
1779
0
  unsigned BestEditDistance = 3;
1780
0
  StringRef Suggestion;
1781
0
  for (const auto &KnownAssumptionIt : llvm::KnownAssumptionStrings) {
1782
0
    unsigned EditDistance =
1783
0
        AssumptionStr.edit_distance(KnownAssumptionIt.getKey());
1784
0
    if (EditDistance < BestEditDistance) {
1785
0
      Suggestion = KnownAssumptionIt.getKey();
1786
0
      BestEditDistance = EditDistance;
1787
0
    }
1788
0
  }
1789
1790
0
  if (!Suggestion.empty())
1791
0
    S.Diag(Loc, diag::warn_assume_attribute_string_unknown_suggested)
1792
0
        << AssumptionStr << Suggestion;
1793
0
  else
1794
0
    S.Diag(Loc, diag::warn_assume_attribute_string_unknown) << AssumptionStr;
1795
0
}
1796
1797
0
static void handleAssumumptionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1798
  // Handle the case where the attribute has a text message.
1799
0
  StringRef Str;
1800
0
  SourceLocation AttrStrLoc;
1801
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &AttrStrLoc))
1802
0
    return;
1803
1804
0
  checkAssumptionAttr(S, AttrStrLoc, Str);
1805
1806
0
  D->addAttr(::new (S.Context) AssumptionAttr(S.Context, AL, Str));
1807
0
}
1808
1809
/// Normalize the attribute, __foo__ becomes foo.
1810
/// Returns true if normalization was applied.
1811
0
static bool normalizeName(StringRef &AttrName) {
1812
0
  if (AttrName.size() > 4 && AttrName.starts_with("__") &&
1813
0
      AttrName.ends_with("__")) {
1814
0
    AttrName = AttrName.drop_front(2).drop_back(2);
1815
0
    return true;
1816
0
  }
1817
0
  return false;
1818
0
}
1819
1820
0
static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1821
  // This attribute must be applied to a function declaration. The first
1822
  // argument to the attribute must be an identifier, the name of the resource,
1823
  // for example: malloc. The following arguments must be argument indexes, the
1824
  // arguments must be of integer type for Returns, otherwise of pointer type.
1825
  // The difference between Holds and Takes is that a pointer may still be used
1826
  // after being held. free() should be __attribute((ownership_takes)), whereas
1827
  // a list append function may well be __attribute((ownership_holds)).
1828
1829
0
  if (!AL.isArgIdent(0)) {
1830
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1831
0
        << AL << 1 << AANT_ArgumentIdentifier;
1832
0
    return;
1833
0
  }
1834
1835
  // Figure out our Kind.
1836
0
  OwnershipAttr::OwnershipKind K =
1837
0
      OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
1838
1839
  // Check arguments.
1840
0
  switch (K) {
1841
0
  case OwnershipAttr::Takes:
1842
0
  case OwnershipAttr::Holds:
1843
0
    if (AL.getNumArgs() < 2) {
1844
0
      S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1845
0
      return;
1846
0
    }
1847
0
    break;
1848
0
  case OwnershipAttr::Returns:
1849
0
    if (AL.getNumArgs() > 2) {
1850
0
      S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1851
0
      return;
1852
0
    }
1853
0
    break;
1854
0
  }
1855
1856
0
  IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1857
1858
0
  StringRef ModuleName = Module->getName();
1859
0
  if (normalizeName(ModuleName)) {
1860
0
    Module = &S.PP.getIdentifierTable().get(ModuleName);
1861
0
  }
1862
1863
0
  SmallVector<ParamIdx, 8> OwnershipArgs;
1864
0
  for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1865
0
    Expr *Ex = AL.getArgAsExpr(i);
1866
0
    ParamIdx Idx;
1867
0
    if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1868
0
      return;
1869
1870
    // Is the function argument a pointer type?
1871
0
    QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1872
0
    int Err = -1;  // No error
1873
0
    switch (K) {
1874
0
      case OwnershipAttr::Takes:
1875
0
      case OwnershipAttr::Holds:
1876
0
        if (!T->isAnyPointerType() && !T->isBlockPointerType())
1877
0
          Err = 0;
1878
0
        break;
1879
0
      case OwnershipAttr::Returns:
1880
0
        if (!T->isIntegerType())
1881
0
          Err = 1;
1882
0
        break;
1883
0
    }
1884
0
    if (-1 != Err) {
1885
0
      S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1886
0
                                                    << Ex->getSourceRange();
1887
0
      return;
1888
0
    }
1889
1890
    // Check we don't have a conflict with another ownership attribute.
1891
0
    for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1892
      // Cannot have two ownership attributes of different kinds for the same
1893
      // index.
1894
0
      if (I->getOwnKind() != K && llvm::is_contained(I->args(), Idx)) {
1895
0
          S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1896
0
              << AL << I
1897
0
              << (AL.isRegularKeywordAttribute() ||
1898
0
                  I->isRegularKeywordAttribute());
1899
0
          return;
1900
0
      } else if (K == OwnershipAttr::Returns &&
1901
0
                 I->getOwnKind() == OwnershipAttr::Returns) {
1902
        // A returns attribute conflicts with any other returns attribute using
1903
        // a different index.
1904
0
        if (!llvm::is_contained(I->args(), Idx)) {
1905
0
          S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1906
0
              << I->args_begin()->getSourceIndex();
1907
0
          if (I->args_size())
1908
0
            S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1909
0
                << Idx.getSourceIndex() << Ex->getSourceRange();
1910
0
          return;
1911
0
        }
1912
0
      }
1913
0
    }
1914
0
    OwnershipArgs.push_back(Idx);
1915
0
  }
1916
1917
0
  ParamIdx *Start = OwnershipArgs.data();
1918
0
  unsigned Size = OwnershipArgs.size();
1919
0
  llvm::array_pod_sort(Start, Start + Size);
1920
0
  D->addAttr(::new (S.Context)
1921
0
                 OwnershipAttr(S.Context, AL, Module, Start, Size));
1922
0
}
1923
1924
0
static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1925
  // Check the attribute arguments.
1926
0
  if (AL.getNumArgs() > 1) {
1927
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1928
0
    return;
1929
0
  }
1930
1931
  // gcc rejects
1932
  // class c {
1933
  //   static int a __attribute__((weakref ("v2")));
1934
  //   static int b() __attribute__((weakref ("f3")));
1935
  // };
1936
  // and ignores the attributes of
1937
  // void f(void) {
1938
  //   static int a __attribute__((weakref ("v2")));
1939
  // }
1940
  // we reject them
1941
0
  const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1942
0
  if (!Ctx->isFileContext()) {
1943
0
    S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1944
0
        << cast<NamedDecl>(D);
1945
0
    return;
1946
0
  }
1947
1948
  // The GCC manual says
1949
  //
1950
  // At present, a declaration to which `weakref' is attached can only
1951
  // be `static'.
1952
  //
1953
  // It also says
1954
  //
1955
  // Without a TARGET,
1956
  // given as an argument to `weakref' or to `alias', `weakref' is
1957
  // equivalent to `weak'.
1958
  //
1959
  // gcc 4.4.1 will accept
1960
  // int a7 __attribute__((weakref));
1961
  // as
1962
  // int a7 __attribute__((weak));
1963
  // This looks like a bug in gcc. We reject that for now. We should revisit
1964
  // it if this behaviour is actually used.
1965
1966
  // GCC rejects
1967
  // static ((alias ("y"), weakref)).
1968
  // Should we? How to check that weakref is before or after alias?
1969
1970
  // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1971
  // of transforming it into an AliasAttr.  The WeakRefAttr never uses the
1972
  // StringRef parameter it was given anyway.
1973
0
  StringRef Str;
1974
0
  if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1975
    // GCC will accept anything as the argument of weakref. Should we
1976
    // check for an existing decl?
1977
0
    D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1978
1979
0
  D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
1980
0
}
1981
1982
0
static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1983
0
  StringRef Str;
1984
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1985
0
    return;
1986
1987
  // Aliases should be on declarations, not definitions.
1988
0
  const auto *FD = cast<FunctionDecl>(D);
1989
0
  if (FD->isThisDeclarationADefinition()) {
1990
0
    S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1991
0
    return;
1992
0
  }
1993
1994
0
  D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
1995
0
}
1996
1997
0
static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1998
0
  StringRef Str;
1999
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
2000
0
    return;
2001
2002
0
  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
2003
0
    S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
2004
0
    return;
2005
0
  }
2006
2007
0
  if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
2008
0
    CudaVersion Version =
2009
0
        ToCudaVersion(S.Context.getTargetInfo().getSDKVersion());
2010
0
    if (Version != CudaVersion::UNKNOWN && Version < CudaVersion::CUDA_100)
2011
0
      S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
2012
0
  }
2013
2014
  // Aliases should be on declarations, not definitions.
2015
0
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2016
0
    if (FD->isThisDeclarationADefinition()) {
2017
0
      S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
2018
0
      return;
2019
0
    }
2020
0
  } else {
2021
0
    const auto *VD = cast<VarDecl>(D);
2022
0
    if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
2023
0
      S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
2024
0
      return;
2025
0
    }
2026
0
  }
2027
2028
  // Mark target used to prevent unneeded-internal-declaration warnings.
2029
0
  if (!S.LangOpts.CPlusPlus) {
2030
    // FIXME: demangle Str for C++, as the attribute refers to the mangled
2031
    // linkage name, not the pre-mangled identifier.
2032
0
    const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
2033
0
    LookupResult LR(S, target, Sema::LookupOrdinaryName);
2034
0
    if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
2035
0
      for (NamedDecl *ND : LR)
2036
0
        ND->markUsed(S.Context);
2037
0
  }
2038
2039
0
  D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
2040
0
}
2041
2042
0
static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2043
0
  StringRef Model;
2044
0
  SourceLocation LiteralLoc;
2045
  // Check that it is a string.
2046
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
2047
0
    return;
2048
2049
  // Check that the value.
2050
0
  if (Model != "global-dynamic" && Model != "local-dynamic"
2051
0
      && Model != "initial-exec" && Model != "local-exec") {
2052
0
    S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
2053
0
    return;
2054
0
  }
2055
2056
0
  if (S.Context.getTargetInfo().getTriple().isOSAIX() &&
2057
0
      Model == "local-dynamic") {
2058
0
    S.Diag(LiteralLoc, diag::err_aix_attr_unsupported_tls_model) << Model;
2059
0
    return;
2060
0
  }
2061
2062
0
  D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model));
2063
0
}
2064
2065
0
static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2066
0
  QualType ResultType = getFunctionOrMethodResultType(D);
2067
0
  if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
2068
0
    D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
2069
0
    return;
2070
0
  }
2071
2072
0
  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
2073
0
      << AL << getFunctionOrMethodResultSourceRange(D);
2074
0
}
2075
2076
0
static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2077
  // Ensure we don't combine these with themselves, since that causes some
2078
  // confusing behavior.
2079
0
  if (AL.getParsedKind() == ParsedAttr::AT_CPUDispatch) {
2080
0
    if (checkAttrMutualExclusion<CPUSpecificAttr>(S, D, AL))
2081
0
      return;
2082
2083
0
    if (const auto *Other = D->getAttr<CPUDispatchAttr>()) {
2084
0
      S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
2085
0
      S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
2086
0
      return;
2087
0
    }
2088
0
  } else if (AL.getParsedKind() == ParsedAttr::AT_CPUSpecific) {
2089
0
    if (checkAttrMutualExclusion<CPUDispatchAttr>(S, D, AL))
2090
0
      return;
2091
2092
0
    if (const auto *Other = D->getAttr<CPUSpecificAttr>()) {
2093
0
      S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
2094
0
      S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
2095
0
      return;
2096
0
    }
2097
0
  }
2098
2099
0
  FunctionDecl *FD = cast<FunctionDecl>(D);
2100
2101
0
  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2102
0
    if (MD->getParent()->isLambda()) {
2103
0
      S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
2104
0
      return;
2105
0
    }
2106
0
  }
2107
2108
0
  if (!AL.checkAtLeastNumArgs(S, 1))
2109
0
    return;
2110
2111
0
  SmallVector<IdentifierInfo *, 8> CPUs;
2112
0
  for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
2113
0
    if (!AL.isArgIdent(ArgNo)) {
2114
0
      S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
2115
0
          << AL << AANT_ArgumentIdentifier;
2116
0
      return;
2117
0
    }
2118
2119
0
    IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
2120
0
    StringRef CPUName = CPUArg->Ident->getName().trim();
2121
2122
0
    if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName)) {
2123
0
      S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
2124
0
          << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
2125
0
      return;
2126
0
    }
2127
2128
0
    const TargetInfo &Target = S.Context.getTargetInfo();
2129
0
    if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
2130
0
          return Target.CPUSpecificManglingCharacter(CPUName) ==
2131
0
                 Target.CPUSpecificManglingCharacter(Cur->getName());
2132
0
        })) {
2133
0
      S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
2134
0
      return;
2135
0
    }
2136
0
    CPUs.push_back(CPUArg->Ident);
2137
0
  }
2138
2139
0
  FD->setIsMultiVersion(true);
2140
0
  if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
2141
0
    D->addAttr(::new (S.Context)
2142
0
                   CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2143
0
  else
2144
0
    D->addAttr(::new (S.Context)
2145
0
                   CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2146
0
}
2147
2148
0
static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2149
0
  if (S.LangOpts.CPlusPlus) {
2150
0
    S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
2151
0
        << AL << AttributeLangSupport::Cpp;
2152
0
    return;
2153
0
  }
2154
2155
0
  D->addAttr(::new (S.Context) CommonAttr(S.Context, AL));
2156
0
}
2157
2158
0
static void handleCmseNSEntryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2159
0
  if (S.LangOpts.CPlusPlus && !D->getDeclContext()->isExternCContext()) {
2160
0
    S.Diag(AL.getLoc(), diag::err_attribute_not_clinkage) << AL;
2161
0
    return;
2162
0
  }
2163
2164
0
  const auto *FD = cast<FunctionDecl>(D);
2165
0
  if (!FD->isExternallyVisible()) {
2166
0
    S.Diag(AL.getLoc(), diag::warn_attribute_cmse_entry_static);
2167
0
    return;
2168
0
  }
2169
2170
0
  D->addAttr(::new (S.Context) CmseNSEntryAttr(S.Context, AL));
2171
0
}
2172
2173
0
static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2174
0
  if (AL.isDeclspecAttribute()) {
2175
0
    const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2176
0
    const auto &Arch = Triple.getArch();
2177
0
    if (Arch != llvm::Triple::x86 &&
2178
0
        (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2179
0
      S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2180
0
          << AL << Triple.getArchName();
2181
0
      return;
2182
0
    }
2183
2184
    // This form is not allowed to be written on a member function (static or
2185
    // nonstatic) when in Microsoft compatibility mode.
2186
0
    if (S.getLangOpts().MSVCCompat && isa<CXXMethodDecl>(D)) {
2187
0
      S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type_str)
2188
0
          << AL << AL.isRegularKeywordAttribute() << "non-member functions";
2189
0
      return;
2190
0
    }
2191
0
  }
2192
2193
0
  D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
2194
0
}
2195
2196
0
static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2197
0
  if (hasDeclarator(D)) return;
2198
2199
0
  if (!isa<ObjCMethodDecl>(D)) {
2200
0
    S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2201
0
        << Attrs << Attrs.isRegularKeywordAttribute()
2202
0
        << ExpectedFunctionOrMethod;
2203
0
    return;
2204
0
  }
2205
2206
0
  D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
2207
0
}
2208
2209
0
static void handleStandardNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &A) {
2210
  // The [[_Noreturn]] spelling is deprecated in C23, so if that was used,
2211
  // issue an appropriate diagnostic. However, don't issue a diagnostic if the
2212
  // attribute name comes from a macro expansion. We don't want to punish users
2213
  // who write [[noreturn]] after including <stdnoreturn.h> (where 'noreturn'
2214
  // is defined as a macro which expands to '_Noreturn').
2215
0
  if (!S.getLangOpts().CPlusPlus &&
2216
0
      A.getSemanticSpelling() == CXX11NoReturnAttr::C23_Noreturn &&
2217
0
      !(A.getLoc().isMacroID() &&
2218
0
        S.getSourceManager().isInSystemMacro(A.getLoc())))
2219
0
    S.Diag(A.getLoc(), diag::warn_deprecated_noreturn_spelling) << A.getRange();
2220
2221
0
  D->addAttr(::new (S.Context) CXX11NoReturnAttr(S.Context, A));
2222
0
}
2223
2224
0
static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2225
0
  if (!S.getLangOpts().CFProtectionBranch)
2226
0
    S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2227
0
  else
2228
0
    handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2229
0
}
2230
2231
0
bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2232
0
  if (!Attrs.checkExactlyNumArgs(*this, 0)) {
2233
0
    Attrs.setInvalid();
2234
0
    return true;
2235
0
  }
2236
2237
0
  return false;
2238
0
}
2239
2240
0
bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
2241
  // Check whether the attribute is valid on the current target.
2242
0
  if (!AL.existsInTarget(Context.getTargetInfo())) {
2243
0
    Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
2244
0
                          ? diag::err_keyword_not_supported_on_target
2245
0
                          : diag::warn_unknown_attribute_ignored)
2246
0
        << AL << AL.getRange();
2247
0
    AL.setInvalid();
2248
0
    return true;
2249
0
  }
2250
2251
0
  return false;
2252
0
}
2253
2254
0
static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2255
2256
  // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2257
  // because 'analyzer_noreturn' does not impact the type.
2258
0
  if (!isFunctionOrMethodOrBlock(D)) {
2259
0
    ValueDecl *VD = dyn_cast<ValueDecl>(D);
2260
0
    if (!VD || (!VD->getType()->isBlockPointerType() &&
2261
0
                !VD->getType()->isFunctionPointerType())) {
2262
0
      S.Diag(AL.getLoc(), AL.isStandardAttributeSyntax()
2263
0
                              ? diag::err_attribute_wrong_decl_type
2264
0
                              : diag::warn_attribute_wrong_decl_type)
2265
0
          << AL << AL.isRegularKeywordAttribute()
2266
0
          << ExpectedFunctionMethodOrBlock;
2267
0
      return;
2268
0
    }
2269
0
  }
2270
2271
0
  D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
2272
0
}
2273
2274
// PS3 PPU-specific.
2275
0
static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2276
  /*
2277
    Returning a Vector Class in Registers
2278
2279
    According to the PPU ABI specifications, a class with a single member of
2280
    vector type is returned in memory when used as the return value of a
2281
    function.
2282
    This results in inefficient code when implementing vector classes. To return
2283
    the value in a single vector register, add the vecreturn attribute to the
2284
    class definition. This attribute is also applicable to struct types.
2285
2286
    Example:
2287
2288
    struct Vector
2289
    {
2290
      __vector float xyzw;
2291
    } __attribute__((vecreturn));
2292
2293
    Vector Add(Vector lhs, Vector rhs)
2294
    {
2295
      Vector result;
2296
      result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2297
      return result; // This will be returned in a register
2298
    }
2299
  */
2300
0
  if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2301
0
    S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2302
0
    return;
2303
0
  }
2304
2305
0
  const auto *R = cast<RecordDecl>(D);
2306
0
  int count = 0;
2307
2308
0
  if (!isa<CXXRecordDecl>(R)) {
2309
0
    S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2310
0
    return;
2311
0
  }
2312
2313
0
  if (!cast<CXXRecordDecl>(R)->isPOD()) {
2314
0
    S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2315
0
    return;
2316
0
  }
2317
2318
0
  for (const auto *I : R->fields()) {
2319
0
    if ((count == 1) || !I->getType()->isVectorType()) {
2320
0
      S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2321
0
      return;
2322
0
    }
2323
0
    count++;
2324
0
  }
2325
2326
0
  D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
2327
0
}
2328
2329
static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2330
0
                                 const ParsedAttr &AL) {
2331
0
  if (isa<ParmVarDecl>(D)) {
2332
    // [[carries_dependency]] can only be applied to a parameter if it is a
2333
    // parameter of a function declaration or lambda.
2334
0
    if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2335
0
      S.Diag(AL.getLoc(),
2336
0
             diag::err_carries_dependency_param_not_function_decl);
2337
0
      return;
2338
0
    }
2339
0
  }
2340
2341
0
  D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
2342
0
}
2343
2344
0
static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2345
0
  bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2346
2347
  // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2348
  // about using it as an extension.
2349
0
  if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2350
0
    S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2351
2352
0
  D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
2353
0
}
2354
2355
0
static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2356
0
  uint32_t priority = ConstructorAttr::DefaultPriority;
2357
0
  if (S.getLangOpts().HLSL && AL.getNumArgs()) {
2358
0
    S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
2359
0
    return;
2360
0
  }
2361
0
  if (AL.getNumArgs() &&
2362
0
      !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2363
0
    return;
2364
2365
0
  D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
2366
0
}
2367
2368
0
static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2369
0
  uint32_t priority = DestructorAttr::DefaultPriority;
2370
0
  if (AL.getNumArgs() &&
2371
0
      !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2372
0
    return;
2373
2374
0
  D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
2375
0
}
2376
2377
template <typename AttrTy>
2378
0
static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2379
  // Handle the case where the attribute has a text message.
2380
0
  StringRef Str;
2381
0
  if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2382
0
    return;
2383
2384
0
  D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str));
2385
0
}
2386
2387
static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2388
0
                                          const ParsedAttr &AL) {
2389
0
  if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2390
0
    S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2391
0
        << AL << AL.getRange();
2392
0
    return;
2393
0
  }
2394
2395
0
  D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL));
2396
0
}
2397
2398
static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2399
                                  IdentifierInfo *Platform,
2400
                                  VersionTuple Introduced,
2401
                                  VersionTuple Deprecated,
2402
0
                                  VersionTuple Obsoleted) {
2403
0
  StringRef PlatformName
2404
0
    = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2405
0
  if (PlatformName.empty())
2406
0
    PlatformName = Platform->getName();
2407
2408
  // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2409
  // of these steps are needed).
2410
0
  if (!Introduced.empty() && !Deprecated.empty() &&
2411
0
      !(Introduced <= Deprecated)) {
2412
0
    S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2413
0
      << 1 << PlatformName << Deprecated.getAsString()
2414
0
      << 0 << Introduced.getAsString();
2415
0
    return true;
2416
0
  }
2417
2418
0
  if (!Introduced.empty() && !Obsoleted.empty() &&
2419
0
      !(Introduced <= Obsoleted)) {
2420
0
    S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2421
0
      << 2 << PlatformName << Obsoleted.getAsString()
2422
0
      << 0 << Introduced.getAsString();
2423
0
    return true;
2424
0
  }
2425
2426
0
  if (!Deprecated.empty() && !Obsoleted.empty() &&
2427
0
      !(Deprecated <= Obsoleted)) {
2428
0
    S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2429
0
      << 2 << PlatformName << Obsoleted.getAsString()
2430
0
      << 1 << Deprecated.getAsString();
2431
0
    return true;
2432
0
  }
2433
2434
0
  return false;
2435
0
}
2436
2437
/// Check whether the two versions match.
2438
///
2439
/// If either version tuple is empty, then they are assumed to match. If
2440
/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2441
static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2442
0
                          bool BeforeIsOkay) {
2443
0
  if (X.empty() || Y.empty())
2444
0
    return true;
2445
2446
0
  if (X == Y)
2447
0
    return true;
2448
2449
0
  if (BeforeIsOkay && X < Y)
2450
0
    return true;
2451
2452
0
  return false;
2453
0
}
2454
2455
AvailabilityAttr *Sema::mergeAvailabilityAttr(
2456
    NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
2457
    bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2458
    VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2459
    bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2460
0
    int Priority) {
2461
0
  VersionTuple MergedIntroduced = Introduced;
2462
0
  VersionTuple MergedDeprecated = Deprecated;
2463
0
  VersionTuple MergedObsoleted = Obsoleted;
2464
0
  bool FoundAny = false;
2465
0
  bool OverrideOrImpl = false;
2466
0
  switch (AMK) {
2467
0
  case AMK_None:
2468
0
  case AMK_Redeclaration:
2469
0
    OverrideOrImpl = false;
2470
0
    break;
2471
2472
0
  case AMK_Override:
2473
0
  case AMK_ProtocolImplementation:
2474
0
  case AMK_OptionalProtocolImplementation:
2475
0
    OverrideOrImpl = true;
2476
0
    break;
2477
0
  }
2478
2479
0
  if (D->hasAttrs()) {
2480
0
    AttrVec &Attrs = D->getAttrs();
2481
0
    for (unsigned i = 0, e = Attrs.size(); i != e;) {
2482
0
      const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2483
0
      if (!OldAA) {
2484
0
        ++i;
2485
0
        continue;
2486
0
      }
2487
2488
0
      IdentifierInfo *OldPlatform = OldAA->getPlatform();
2489
0
      if (OldPlatform != Platform) {
2490
0
        ++i;
2491
0
        continue;
2492
0
      }
2493
2494
      // If there is an existing availability attribute for this platform that
2495
      // has a lower priority use the existing one and discard the new
2496
      // attribute.
2497
0
      if (OldAA->getPriority() < Priority)
2498
0
        return nullptr;
2499
2500
      // If there is an existing attribute for this platform that has a higher
2501
      // priority than the new attribute then erase the old one and continue
2502
      // processing the attributes.
2503
0
      if (OldAA->getPriority() > Priority) {
2504
0
        Attrs.erase(Attrs.begin() + i);
2505
0
        --e;
2506
0
        continue;
2507
0
      }
2508
2509
0
      FoundAny = true;
2510
0
      VersionTuple OldIntroduced = OldAA->getIntroduced();
2511
0
      VersionTuple OldDeprecated = OldAA->getDeprecated();
2512
0
      VersionTuple OldObsoleted = OldAA->getObsoleted();
2513
0
      bool OldIsUnavailable = OldAA->getUnavailable();
2514
2515
0
      if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2516
0
          !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2517
0
          !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2518
0
          !(OldIsUnavailable == IsUnavailable ||
2519
0
            (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2520
0
        if (OverrideOrImpl) {
2521
0
          int Which = -1;
2522
0
          VersionTuple FirstVersion;
2523
0
          VersionTuple SecondVersion;
2524
0
          if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2525
0
            Which = 0;
2526
0
            FirstVersion = OldIntroduced;
2527
0
            SecondVersion = Introduced;
2528
0
          } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2529
0
            Which = 1;
2530
0
            FirstVersion = Deprecated;
2531
0
            SecondVersion = OldDeprecated;
2532
0
          } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2533
0
            Which = 2;
2534
0
            FirstVersion = Obsoleted;
2535
0
            SecondVersion = OldObsoleted;
2536
0
          }
2537
2538
0
          if (Which == -1) {
2539
0
            Diag(OldAA->getLocation(),
2540
0
                 diag::warn_mismatched_availability_override_unavail)
2541
0
              << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2542
0
              << (AMK == AMK_Override);
2543
0
          } else if (Which != 1 && AMK == AMK_OptionalProtocolImplementation) {
2544
            // Allow different 'introduced' / 'obsoleted' availability versions
2545
            // on a method that implements an optional protocol requirement. It
2546
            // makes less sense to allow this for 'deprecated' as the user can't
2547
            // see if the method is 'deprecated' as 'respondsToSelector' will
2548
            // still return true when the method is deprecated.
2549
0
            ++i;
2550
0
            continue;
2551
0
          } else {
2552
0
            Diag(OldAA->getLocation(),
2553
0
                 diag::warn_mismatched_availability_override)
2554
0
              << Which
2555
0
              << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2556
0
              << FirstVersion.getAsString() << SecondVersion.getAsString()
2557
0
              << (AMK == AMK_Override);
2558
0
          }
2559
0
          if (AMK == AMK_Override)
2560
0
            Diag(CI.getLoc(), diag::note_overridden_method);
2561
0
          else
2562
0
            Diag(CI.getLoc(), diag::note_protocol_method);
2563
0
        } else {
2564
0
          Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2565
0
          Diag(CI.getLoc(), diag::note_previous_attribute);
2566
0
        }
2567
2568
0
        Attrs.erase(Attrs.begin() + i);
2569
0
        --e;
2570
0
        continue;
2571
0
      }
2572
2573
0
      VersionTuple MergedIntroduced2 = MergedIntroduced;
2574
0
      VersionTuple MergedDeprecated2 = MergedDeprecated;
2575
0
      VersionTuple MergedObsoleted2 = MergedObsoleted;
2576
2577
0
      if (MergedIntroduced2.empty())
2578
0
        MergedIntroduced2 = OldIntroduced;
2579
0
      if (MergedDeprecated2.empty())
2580
0
        MergedDeprecated2 = OldDeprecated;
2581
0
      if (MergedObsoleted2.empty())
2582
0
        MergedObsoleted2 = OldObsoleted;
2583
2584
0
      if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2585
0
                                MergedIntroduced2, MergedDeprecated2,
2586
0
                                MergedObsoleted2)) {
2587
0
        Attrs.erase(Attrs.begin() + i);
2588
0
        --e;
2589
0
        continue;
2590
0
      }
2591
2592
0
      MergedIntroduced = MergedIntroduced2;
2593
0
      MergedDeprecated = MergedDeprecated2;
2594
0
      MergedObsoleted = MergedObsoleted2;
2595
0
      ++i;
2596
0
    }
2597
0
  }
2598
2599
0
  if (FoundAny &&
2600
0
      MergedIntroduced == Introduced &&
2601
0
      MergedDeprecated == Deprecated &&
2602
0
      MergedObsoleted == Obsoleted)
2603
0
    return nullptr;
2604
2605
  // Only create a new attribute if !OverrideOrImpl, but we want to do
2606
  // the checking.
2607
0
  if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced,
2608
0
                             MergedDeprecated, MergedObsoleted) &&
2609
0
      !OverrideOrImpl) {
2610
0
    auto *Avail = ::new (Context) AvailabilityAttr(
2611
0
        Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2612
0
        Message, IsStrict, Replacement, Priority);
2613
0
    Avail->setImplicit(Implicit);
2614
0
    return Avail;
2615
0
  }
2616
0
  return nullptr;
2617
0
}
2618
2619
0
static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2620
0
  if (isa<UsingDecl, UnresolvedUsingTypenameDecl, UnresolvedUsingValueDecl>(
2621
0
          D)) {
2622
0
    S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
2623
0
        << AL;
2624
0
    return;
2625
0
  }
2626
2627
0
  if (!AL.checkExactlyNumArgs(S, 1))
2628
0
    return;
2629
0
  IdentifierLoc *Platform = AL.getArgAsIdent(0);
2630
2631
0
  IdentifierInfo *II = Platform->Ident;
2632
0
  if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2633
0
    S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2634
0
      << Platform->Ident;
2635
2636
0
  auto *ND = dyn_cast<NamedDecl>(D);
2637
0
  if (!ND) // We warned about this already, so just return.
2638
0
    return;
2639
2640
0
  AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
2641
0
  AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
2642
0
  AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
2643
0
  bool IsUnavailable = AL.getUnavailableLoc().isValid();
2644
0
  bool IsStrict = AL.getStrictLoc().isValid();
2645
0
  StringRef Str;
2646
0
  if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getMessageExpr()))
2647
0
    Str = SE->getString();
2648
0
  StringRef Replacement;
2649
0
  if (const auto *SE =
2650
0
          dyn_cast_if_present<StringLiteral>(AL.getReplacementExpr()))
2651
0
    Replacement = SE->getString();
2652
2653
0
  if (II->isStr("swift")) {
2654
0
    if (Introduced.isValid() || Obsoleted.isValid() ||
2655
0
        (!IsUnavailable && !Deprecated.isValid())) {
2656
0
      S.Diag(AL.getLoc(),
2657
0
             diag::warn_availability_swift_unavailable_deprecated_only);
2658
0
      return;
2659
0
    }
2660
0
  }
2661
2662
0
  if (II->isStr("fuchsia")) {
2663
0
    std::optional<unsigned> Min, Sub;
2664
0
    if ((Min = Introduced.Version.getMinor()) ||
2665
0
        (Sub = Introduced.Version.getSubminor())) {
2666
0
      S.Diag(AL.getLoc(), diag::warn_availability_fuchsia_unavailable_minor);
2667
0
      return;
2668
0
    }
2669
0
  }
2670
2671
0
  int PriorityModifier = AL.isPragmaClangAttribute()
2672
0
                             ? Sema::AP_PragmaClangAttribute
2673
0
                             : Sema::AP_Explicit;
2674
0
  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2675
0
      ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2676
0
      Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2677
0
      Sema::AMK_None, PriorityModifier);
2678
0
  if (NewAttr)
2679
0
    D->addAttr(NewAttr);
2680
2681
  // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2682
  // matches before the start of the watchOS platform.
2683
0
  if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2684
0
    IdentifierInfo *NewII = nullptr;
2685
0
    if (II->getName() == "ios")
2686
0
      NewII = &S.Context.Idents.get("watchos");
2687
0
    else if (II->getName() == "ios_app_extension")
2688
0
      NewII = &S.Context.Idents.get("watchos_app_extension");
2689
2690
0
    if (NewII) {
2691
0
      const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2692
0
      const auto *IOSToWatchOSMapping =
2693
0
          SDKInfo ? SDKInfo->getVersionMapping(
2694
0
                        DarwinSDKInfo::OSEnvPair::iOStoWatchOSPair())
2695
0
                  : nullptr;
2696
2697
0
      auto adjustWatchOSVersion =
2698
0
          [IOSToWatchOSMapping](VersionTuple Version) -> VersionTuple {
2699
0
        if (Version.empty())
2700
0
          return Version;
2701
0
        auto MinimumWatchOSVersion = VersionTuple(2, 0);
2702
2703
0
        if (IOSToWatchOSMapping) {
2704
0
          if (auto MappedVersion = IOSToWatchOSMapping->map(
2705
0
                  Version, MinimumWatchOSVersion, std::nullopt)) {
2706
0
            return *MappedVersion;
2707
0
          }
2708
0
        }
2709
2710
0
        auto Major = Version.getMajor();
2711
0
        auto NewMajor = Major >= 9 ? Major - 7 : 0;
2712
0
        if (NewMajor >= 2) {
2713
0
          if (Version.getMinor()) {
2714
0
            if (Version.getSubminor())
2715
0
              return VersionTuple(NewMajor, *Version.getMinor(),
2716
0
                                  *Version.getSubminor());
2717
0
            else
2718
0
              return VersionTuple(NewMajor, *Version.getMinor());
2719
0
          }
2720
0
          return VersionTuple(NewMajor);
2721
0
        }
2722
2723
0
        return MinimumWatchOSVersion;
2724
0
      };
2725
2726
0
      auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2727
0
      auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2728
0
      auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2729
2730
0
      AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2731
0
          ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2732
0
          NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2733
0
          Sema::AMK_None,
2734
0
          PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2735
0
      if (NewAttr)
2736
0
        D->addAttr(NewAttr);
2737
0
    }
2738
0
  } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2739
    // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2740
    // matches before the start of the tvOS platform.
2741
0
    IdentifierInfo *NewII = nullptr;
2742
0
    if (II->getName() == "ios")
2743
0
      NewII = &S.Context.Idents.get("tvos");
2744
0
    else if (II->getName() == "ios_app_extension")
2745
0
      NewII = &S.Context.Idents.get("tvos_app_extension");
2746
2747
0
    if (NewII) {
2748
0
      const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2749
0
      const auto *IOSToTvOSMapping =
2750
0
          SDKInfo ? SDKInfo->getVersionMapping(
2751
0
                        DarwinSDKInfo::OSEnvPair::iOStoTvOSPair())
2752
0
                  : nullptr;
2753
2754
0
      auto AdjustTvOSVersion =
2755
0
          [IOSToTvOSMapping](VersionTuple Version) -> VersionTuple {
2756
0
        if (Version.empty())
2757
0
          return Version;
2758
2759
0
        if (IOSToTvOSMapping) {
2760
0
          if (auto MappedVersion = IOSToTvOSMapping->map(
2761
0
                  Version, VersionTuple(0, 0), std::nullopt)) {
2762
0
            return *MappedVersion;
2763
0
          }
2764
0
        }
2765
0
        return Version;
2766
0
      };
2767
2768
0
      auto NewIntroduced = AdjustTvOSVersion(Introduced.Version);
2769
0
      auto NewDeprecated = AdjustTvOSVersion(Deprecated.Version);
2770
0
      auto NewObsoleted = AdjustTvOSVersion(Obsoleted.Version);
2771
2772
0
      AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2773
0
          ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2774
0
          NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2775
0
          Sema::AMK_None,
2776
0
          PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2777
0
      if (NewAttr)
2778
0
        D->addAttr(NewAttr);
2779
0
    }
2780
0
  } else if (S.Context.getTargetInfo().getTriple().getOS() ==
2781
0
                 llvm::Triple::IOS &&
2782
0
             S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) {
2783
0
    auto GetSDKInfo = [&]() {
2784
0
      return S.getDarwinSDKInfoForAvailabilityChecking(AL.getRange().getBegin(),
2785
0
                                                       "macOS");
2786
0
    };
2787
2788
    // Transcribe "ios" to "maccatalyst" (and add a new attribute).
2789
0
    IdentifierInfo *NewII = nullptr;
2790
0
    if (II->getName() == "ios")
2791
0
      NewII = &S.Context.Idents.get("maccatalyst");
2792
0
    else if (II->getName() == "ios_app_extension")
2793
0
      NewII = &S.Context.Idents.get("maccatalyst_app_extension");
2794
0
    if (NewII) {
2795
0
      auto MinMacCatalystVersion = [](const VersionTuple &V) {
2796
0
        if (V.empty())
2797
0
          return V;
2798
0
        if (V.getMajor() < 13 ||
2799
0
            (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1))
2800
0
          return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1.
2801
0
        return V;
2802
0
      };
2803
0
      AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2804
0
          ND, AL, NewII, true /*Implicit*/,
2805
0
          MinMacCatalystVersion(Introduced.Version),
2806
0
          MinMacCatalystVersion(Deprecated.Version),
2807
0
          MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str,
2808
0
          IsStrict, Replacement, Sema::AMK_None,
2809
0
          PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2810
0
      if (NewAttr)
2811
0
        D->addAttr(NewAttr);
2812
0
    } else if (II->getName() == "macos" && GetSDKInfo() &&
2813
0
               (!Introduced.Version.empty() || !Deprecated.Version.empty() ||
2814
0
                !Obsoleted.Version.empty())) {
2815
0
      if (const auto *MacOStoMacCatalystMapping =
2816
0
              GetSDKInfo()->getVersionMapping(
2817
0
                  DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
2818
        // Infer Mac Catalyst availability from the macOS availability attribute
2819
        // if it has versioned availability. Don't infer 'unavailable'. This
2820
        // inferred availability has lower priority than the other availability
2821
        // attributes that are inferred from 'ios'.
2822
0
        NewII = &S.Context.Idents.get("maccatalyst");
2823
0
        auto RemapMacOSVersion =
2824
0
            [&](const VersionTuple &V) -> std::optional<VersionTuple> {
2825
0
          if (V.empty())
2826
0
            return std::nullopt;
2827
          // API_TO_BE_DEPRECATED is 100000.
2828
0
          if (V.getMajor() == 100000)
2829
0
            return VersionTuple(100000);
2830
          // The minimum iosmac version is 13.1
2831
0
          return MacOStoMacCatalystMapping->map(V, VersionTuple(13, 1),
2832
0
                                                std::nullopt);
2833
0
        };
2834
0
        std::optional<VersionTuple> NewIntroduced =
2835
0
                                        RemapMacOSVersion(Introduced.Version),
2836
0
                                    NewDeprecated =
2837
0
                                        RemapMacOSVersion(Deprecated.Version),
2838
0
                                    NewObsoleted =
2839
0
                                        RemapMacOSVersion(Obsoleted.Version);
2840
0
        if (NewIntroduced || NewDeprecated || NewObsoleted) {
2841
0
          auto VersionOrEmptyVersion =
2842
0
              [](const std::optional<VersionTuple> &V) -> VersionTuple {
2843
0
            return V ? *V : VersionTuple();
2844
0
          };
2845
0
          AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2846
0
              ND, AL, NewII, true /*Implicit*/,
2847
0
              VersionOrEmptyVersion(NewIntroduced),
2848
0
              VersionOrEmptyVersion(NewDeprecated),
2849
0
              VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str,
2850
0
              IsStrict, Replacement, Sema::AMK_None,
2851
0
              PriorityModifier + Sema::AP_InferredFromOtherPlatform +
2852
0
                  Sema::AP_InferredFromOtherPlatform);
2853
0
          if (NewAttr)
2854
0
            D->addAttr(NewAttr);
2855
0
        }
2856
0
      }
2857
0
    }
2858
0
  }
2859
0
}
2860
2861
static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2862
0
                                           const ParsedAttr &AL) {
2863
0
  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 4))
2864
0
    return;
2865
2866
0
  StringRef Language;
2867
0
  if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getArgAsExpr(0)))
2868
0
    Language = SE->getString();
2869
0
  StringRef DefinedIn;
2870
0
  if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getArgAsExpr(1)))
2871
0
    DefinedIn = SE->getString();
2872
0
  bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2873
0
  StringRef USR;
2874
0
  if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getArgAsExpr(3)))
2875
0
    USR = SE->getString();
2876
2877
0
  D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2878
0
      S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration, USR));
2879
0
}
2880
2881
template <class T>
2882
static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
2883
0
                              typename T::VisibilityType value) {
2884
0
  T *existingAttr = D->getAttr<T>();
2885
0
  if (existingAttr) {
2886
0
    typename T::VisibilityType existingValue = existingAttr->getVisibility();
2887
0
    if (existingValue == value)
2888
0
      return nullptr;
2889
0
    S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2890
0
    S.Diag(CI.getLoc(), diag::note_previous_attribute);
2891
0
    D->dropAttr<T>();
2892
0
  }
2893
0
  return ::new (S.Context) T(S.Context, CI, value);
2894
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:clang::VisibilityAttr* mergeVisibilityAttr<clang::VisibilityAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, clang::VisibilityAttr::VisibilityType)
Unexecuted instantiation: SemaDeclAttr.cpp:clang::TypeVisibilityAttr* mergeVisibilityAttr<clang::TypeVisibilityAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, clang::TypeVisibilityAttr::VisibilityType)
2895
2896
VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
2897
                                          const AttributeCommonInfo &CI,
2898
0
                                          VisibilityAttr::VisibilityType Vis) {
2899
0
  return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
2900
0
}
2901
2902
TypeVisibilityAttr *
2903
Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2904
0
                              TypeVisibilityAttr::VisibilityType Vis) {
2905
0
  return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
2906
0
}
2907
2908
static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2909
0
                                 bool isTypeVisibility) {
2910
  // Visibility attributes don't mean anything on a typedef.
2911
0
  if (isa<TypedefNameDecl>(D)) {
2912
0
    S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2913
0
    return;
2914
0
  }
2915
2916
  // 'type_visibility' can only go on a type or namespace.
2917
0
  if (isTypeVisibility && !(isa<TagDecl>(D) || isa<ObjCInterfaceDecl>(D) ||
2918
0
                            isa<NamespaceDecl>(D))) {
2919
0
    S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2920
0
        << AL << AL.isRegularKeywordAttribute() << ExpectedTypeOrNamespace;
2921
0
    return;
2922
0
  }
2923
2924
  // Check that the argument is a string literal.
2925
0
  StringRef TypeStr;
2926
0
  SourceLocation LiteralLoc;
2927
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2928
0
    return;
2929
2930
0
  VisibilityAttr::VisibilityType type;
2931
0
  if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2932
0
    S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2933
0
                                                                << TypeStr;
2934
0
    return;
2935
0
  }
2936
2937
  // Complain about attempts to use protected visibility on targets
2938
  // (like Darwin) that don't support it.
2939
0
  if (type == VisibilityAttr::Protected &&
2940
0
      !S.Context.getTargetInfo().hasProtectedVisibility()) {
2941
0
    S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2942
0
    type = VisibilityAttr::Default;
2943
0
  }
2944
2945
0
  Attr *newAttr;
2946
0
  if (isTypeVisibility) {
2947
0
    newAttr = S.mergeTypeVisibilityAttr(
2948
0
        D, AL, (TypeVisibilityAttr::VisibilityType)type);
2949
0
  } else {
2950
0
    newAttr = S.mergeVisibilityAttr(D, AL, type);
2951
0
  }
2952
0
  if (newAttr)
2953
0
    D->addAttr(newAttr);
2954
0
}
2955
2956
0
static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2957
  // objc_direct cannot be set on methods declared in the context of a protocol
2958
0
  if (isa<ObjCProtocolDecl>(D->getDeclContext())) {
2959
0
    S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
2960
0
    return;
2961
0
  }
2962
2963
0
  if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2964
0
    handleSimpleAttribute<ObjCDirectAttr>(S, D, AL);
2965
0
  } else {
2966
0
    S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2967
0
  }
2968
0
}
2969
2970
static void handleObjCDirectMembersAttr(Sema &S, Decl *D,
2971
0
                                        const ParsedAttr &AL) {
2972
0
  if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2973
0
    handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
2974
0
  } else {
2975
0
    S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2976
0
  }
2977
0
}
2978
2979
0
static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2980
0
  const auto *M = cast<ObjCMethodDecl>(D);
2981
0
  if (!AL.isArgIdent(0)) {
2982
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2983
0
        << AL << 1 << AANT_ArgumentIdentifier;
2984
0
    return;
2985
0
  }
2986
2987
0
  IdentifierLoc *IL = AL.getArgAsIdent(0);
2988
0
  ObjCMethodFamilyAttr::FamilyKind F;
2989
0
  if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2990
0
    S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2991
0
    return;
2992
0
  }
2993
2994
0
  if (F == ObjCMethodFamilyAttr::OMF_init &&
2995
0
      !M->getReturnType()->isObjCObjectPointerType()) {
2996
0
    S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2997
0
        << M->getReturnType();
2998
    // Ignore the attribute.
2999
0
    return;
3000
0
  }
3001
3002
0
  D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F));
3003
0
}
3004
3005
0
static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
3006
0
  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
3007
0
    QualType T = TD->getUnderlyingType();
3008
0
    if (!T->isCARCBridgableType()) {
3009
0
      S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
3010
0
      return;
3011
0
    }
3012
0
  }
3013
0
  else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
3014
0
    QualType T = PD->getType();
3015
0
    if (!T->isCARCBridgableType()) {
3016
0
      S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
3017
0
      return;
3018
0
    }
3019
0
  }
3020
0
  else {
3021
    // It is okay to include this attribute on properties, e.g.:
3022
    //
3023
    //  @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
3024
    //
3025
    // In this case it follows tradition and suppresses an error in the above
3026
    // case.
3027
0
    S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
3028
0
  }
3029
0
  D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL));
3030
0
}
3031
3032
0
static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
3033
0
  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
3034
0
    QualType T = TD->getUnderlyingType();
3035
0
    if (!T->isObjCObjectPointerType()) {
3036
0
      S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
3037
0
      return;
3038
0
    }
3039
0
  } else {
3040
0
    S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
3041
0
    return;
3042
0
  }
3043
0
  D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL));
3044
0
}
3045
3046
0
static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3047
0
  if (!AL.isArgIdent(0)) {
3048
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3049
0
        << AL << 1 << AANT_ArgumentIdentifier;
3050
0
    return;
3051
0
  }
3052
3053
0
  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3054
0
  BlocksAttr::BlockType type;
3055
0
  if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
3056
0
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3057
0
    return;
3058
0
  }
3059
3060
0
  D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type));
3061
0
}
3062
3063
0
static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3064
0
  unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
3065
0
  if (AL.getNumArgs() > 0) {
3066
0
    Expr *E = AL.getArgAsExpr(0);
3067
0
    std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
3068
0
    if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
3069
0
      S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3070
0
          << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
3071
0
      return;
3072
0
    }
3073
3074
0
    if (Idx->isSigned() && Idx->isNegative()) {
3075
0
      S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
3076
0
        << E->getSourceRange();
3077
0
      return;
3078
0
    }
3079
3080
0
    sentinel = Idx->getZExtValue();
3081
0
  }
3082
3083
0
  unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
3084
0
  if (AL.getNumArgs() > 1) {
3085
0
    Expr *E = AL.getArgAsExpr(1);
3086
0
    std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
3087
0
    if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
3088
0
      S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3089
0
          << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
3090
0
      return;
3091
0
    }
3092
0
    nullPos = Idx->getZExtValue();
3093
3094
0
    if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) {
3095
      // FIXME: This error message could be improved, it would be nice
3096
      // to say what the bounds actually are.
3097
0
      S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
3098
0
        << E->getSourceRange();
3099
0
      return;
3100
0
    }
3101
0
  }
3102
3103
0
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3104
0
    const FunctionType *FT = FD->getType()->castAs<FunctionType>();
3105
0
    if (isa<FunctionNoProtoType>(FT)) {
3106
0
      S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
3107
0
      return;
3108
0
    }
3109
3110
0
    if (!cast<FunctionProtoType>(FT)->isVariadic()) {
3111
0
      S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
3112
0
      return;
3113
0
    }
3114
0
  } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
3115
0
    if (!MD->isVariadic()) {
3116
0
      S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
3117
0
      return;
3118
0
    }
3119
0
  } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
3120
0
    if (!BD->isVariadic()) {
3121
0
      S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
3122
0
      return;
3123
0
    }
3124
0
  } else if (const auto *V = dyn_cast<VarDecl>(D)) {
3125
0
    QualType Ty = V->getType();
3126
0
    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
3127
0
      const FunctionType *FT = Ty->isFunctionPointerType()
3128
0
                                   ? D->getFunctionType()
3129
0
                                   : Ty->castAs<BlockPointerType>()
3130
0
                                         ->getPointeeType()
3131
0
                                         ->castAs<FunctionType>();
3132
0
      if (!cast<FunctionProtoType>(FT)->isVariadic()) {
3133
0
        int m = Ty->isFunctionPointerType() ? 0 : 1;
3134
0
        S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
3135
0
        return;
3136
0
      }
3137
0
    } else {
3138
0
      S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3139
0
          << AL << AL.isRegularKeywordAttribute()
3140
0
          << ExpectedFunctionMethodOrBlock;
3141
0
      return;
3142
0
    }
3143
0
  } else {
3144
0
    S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3145
0
        << AL << AL.isRegularKeywordAttribute()
3146
0
        << ExpectedFunctionMethodOrBlock;
3147
0
    return;
3148
0
  }
3149
0
  D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
3150
0
}
3151
3152
0
static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
3153
0
  if (D->getFunctionType() &&
3154
0
      D->getFunctionType()->getReturnType()->isVoidType() &&
3155
0
      !isa<CXXConstructorDecl>(D)) {
3156
0
    S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
3157
0
    return;
3158
0
  }
3159
0
  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
3160
0
    if (MD->getReturnType()->isVoidType()) {
3161
0
      S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
3162
0
      return;
3163
0
    }
3164
3165
0
  StringRef Str;
3166
0
  if (AL.isStandardAttributeSyntax() && !AL.getScopeName()) {
3167
    // The standard attribute cannot be applied to variable declarations such
3168
    // as a function pointer.
3169
0
    if (isa<VarDecl>(D))
3170
0
      S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
3171
0
          << AL << AL.isRegularKeywordAttribute()
3172
0
          << "functions, classes, or enumerations";
3173
3174
    // If this is spelled as the standard C++17 attribute, but not in C++17,
3175
    // warn about using it as an extension. If there are attribute arguments,
3176
    // then claim it's a C++20 extension instead.
3177
    // FIXME: If WG14 does not seem likely to adopt the same feature, add an
3178
    // extension warning for C23 mode.
3179
0
    const LangOptions &LO = S.getLangOpts();
3180
0
    if (AL.getNumArgs() == 1) {
3181
0
      if (LO.CPlusPlus && !LO.CPlusPlus20)
3182
0
        S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL;
3183
3184
      // Since this is spelled [[nodiscard]], get the optional string
3185
      // literal. If in C++ mode, but not in C++20 mode, diagnose as an
3186
      // extension.
3187
      // FIXME: C23 should support this feature as well, even as an extension.
3188
0
      if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
3189
0
        return;
3190
0
    } else if (LO.CPlusPlus && !LO.CPlusPlus17)
3191
0
      S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
3192
0
  }
3193
3194
0
  if ((!AL.isGNUAttribute() &&
3195
0
       !(AL.isStandardAttributeSyntax() && AL.isClangScope())) &&
3196
0
      isa<TypedefNameDecl>(D)) {
3197
0
    S.Diag(AL.getLoc(), diag::warn_unused_result_typedef_unsupported_spelling)
3198
0
        << AL.isGNUScope();
3199
0
    return;
3200
0
  }
3201
3202
0
  D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
3203
0
}
3204
3205
0
static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3206
  // weak_import only applies to variable & function declarations.
3207
0
  bool isDef = false;
3208
0
  if (!D->canBeWeakImported(isDef)) {
3209
0
    if (isDef)
3210
0
      S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
3211
0
        << "weak_import";
3212
0
    else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
3213
0
             (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
3214
0
              (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
3215
      // Nothing to warn about here.
3216
0
    } else
3217
0
      S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3218
0
          << AL << AL.isRegularKeywordAttribute() << ExpectedVariableOrFunction;
3219
3220
0
    return;
3221
0
  }
3222
3223
0
  D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
3224
0
}
3225
3226
// Handles reqd_work_group_size and work_group_size_hint.
3227
template <typename WorkGroupAttr>
3228
0
static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3229
0
  uint32_t WGSize[3];
3230
0
  for (unsigned i = 0; i < 3; ++i) {
3231
0
    const Expr *E = AL.getArgAsExpr(i);
3232
0
    if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
3233
0
                             /*StrictlyUnsigned=*/true))
3234
0
      return;
3235
0
    if (WGSize[i] == 0) {
3236
0
      S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3237
0
          << AL << E->getSourceRange();
3238
0
      return;
3239
0
    }
3240
0
  }
3241
3242
0
  WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
3243
0
  if (Existing && !(Existing->getXDim() == WGSize[0] &&
3244
0
                    Existing->getYDim() == WGSize[1] &&
3245
0
                    Existing->getZDim() == WGSize[2]))
3246
0
    S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3247
3248
0
  D->addAttr(::new (S.Context)
3249
0
                 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
3250
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:void handleWorkGroupSize<clang::WorkGroupSizeHintAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleWorkGroupSize<clang::ReqdWorkGroupSizeAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
3251
3252
// Handles intel_reqd_sub_group_size.
3253
0
static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3254
0
  uint32_t SGSize;
3255
0
  const Expr *E = AL.getArgAsExpr(0);
3256
0
  if (!checkUInt32Argument(S, AL, E, SGSize))
3257
0
    return;
3258
0
  if (SGSize == 0) {
3259
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3260
0
        << AL << E->getSourceRange();
3261
0
    return;
3262
0
  }
3263
3264
0
  OpenCLIntelReqdSubGroupSizeAttr *Existing =
3265
0
      D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
3266
0
  if (Existing && Existing->getSubGroupSize() != SGSize)
3267
0
    S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3268
3269
0
  D->addAttr(::new (S.Context)
3270
0
                 OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize));
3271
0
}
3272
3273
0
static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
3274
0
  if (!AL.hasParsedType()) {
3275
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3276
0
    return;
3277
0
  }
3278
3279
0
  TypeSourceInfo *ParmTSI = nullptr;
3280
0
  QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
3281
0
  assert(ParmTSI && "no type source info for attribute argument");
3282
3283
0
  if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
3284
0
      (ParmType->isBooleanType() ||
3285
0
       !ParmType->isIntegralType(S.getASTContext()))) {
3286
0
    S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
3287
0
    return;
3288
0
  }
3289
3290
0
  if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
3291
0
    if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
3292
0
      S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3293
0
      return;
3294
0
    }
3295
0
  }
3296
3297
0
  D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
3298
0
}
3299
3300
SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3301
0
                                    StringRef Name) {
3302
  // Explicit or partial specializations do not inherit
3303
  // the section attribute from the primary template.
3304
0
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3305
0
    if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
3306
0
        FD->isFunctionTemplateSpecialization())
3307
0
      return nullptr;
3308
0
  }
3309
0
  if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
3310
0
    if (ExistingAttr->getName() == Name)
3311
0
      return nullptr;
3312
0
    Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3313
0
         << 1 /*section*/;
3314
0
    Diag(CI.getLoc(), diag::note_previous_attribute);
3315
0
    return nullptr;
3316
0
  }
3317
0
  return ::new (Context) SectionAttr(Context, CI, Name);
3318
0
}
3319
3320
/// Used to implement to perform semantic checking on
3321
/// attribute((section("foo"))) specifiers.
3322
///
3323
/// In this case, "foo" is passed in to be checked.  If the section
3324
/// specifier is invalid, return an Error that indicates the problem.
3325
///
3326
/// This is a simple quality of implementation feature to catch errors
3327
/// and give good diagnostics in cases when the assembler or code generator
3328
/// would otherwise reject the section specifier.
3329
0
llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) {
3330
0
  if (!Context.getTargetInfo().getTriple().isOSDarwin())
3331
0
    return llvm::Error::success();
3332
3333
  // Let MCSectionMachO validate this.
3334
0
  StringRef Segment, Section;
3335
0
  unsigned TAA, StubSize;
3336
0
  bool HasTAA;
3337
0
  return llvm::MCSectionMachO::ParseSectionSpecifier(SecName, Segment, Section,
3338
0
                                                     TAA, HasTAA, StubSize);
3339
0
}
3340
3341
0
bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
3342
0
  if (llvm::Error E = isValidSectionSpecifier(SecName)) {
3343
0
    Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3344
0
        << toString(std::move(E)) << 1 /*'section'*/;
3345
0
    return false;
3346
0
  }
3347
0
  return true;
3348
0
}
3349
3350
0
static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3351
  // Make sure that there is a string literal as the sections's single
3352
  // argument.
3353
0
  StringRef Str;
3354
0
  SourceLocation LiteralLoc;
3355
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3356
0
    return;
3357
3358
0
  if (!S.checkSectionName(LiteralLoc, Str))
3359
0
    return;
3360
3361
0
  SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
3362
0
  if (NewAttr) {
3363
0
    D->addAttr(NewAttr);
3364
0
    if (isa<FunctionDecl, FunctionTemplateDecl, ObjCMethodDecl,
3365
0
            ObjCPropertyDecl>(D))
3366
0
      S.UnifySection(NewAttr->getName(),
3367
0
                     ASTContext::PSF_Execute | ASTContext::PSF_Read,
3368
0
                     cast<NamedDecl>(D));
3369
0
  }
3370
0
}
3371
3372
0
static void handleCodeModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3373
0
  StringRef Str;
3374
0
  SourceLocation LiteralLoc;
3375
  // Check that it is a string.
3376
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3377
0
    return;
3378
3379
0
  llvm::CodeModel::Model CM;
3380
0
  if (!CodeModelAttr::ConvertStrToModel(Str, CM)) {
3381
0
    S.Diag(LiteralLoc, diag::err_attr_codemodel_arg) << Str;
3382
0
    return;
3383
0
  }
3384
3385
0
  D->addAttr(::new (S.Context) CodeModelAttr(S.Context, AL, CM));
3386
0
}
3387
3388
// This is used for `__declspec(code_seg("segname"))` on a decl.
3389
// `#pragma code_seg("segname")` uses checkSectionName() instead.
3390
static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
3391
0
                             StringRef CodeSegName) {
3392
0
  if (llvm::Error E = S.isValidSectionSpecifier(CodeSegName)) {
3393
0
    S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3394
0
        << toString(std::move(E)) << 0 /*'code-seg'*/;
3395
0
    return false;
3396
0
  }
3397
3398
0
  return true;
3399
0
}
3400
3401
CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3402
0
                                    StringRef Name) {
3403
  // Explicit or partial specializations do not inherit
3404
  // the code_seg attribute from the primary template.
3405
0
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3406
0
    if (FD->isFunctionTemplateSpecialization())
3407
0
      return nullptr;
3408
0
  }
3409
0
  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3410
0
    if (ExistingAttr->getName() == Name)
3411
0
      return nullptr;
3412
0
    Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3413
0
         << 0 /*codeseg*/;
3414
0
    Diag(CI.getLoc(), diag::note_previous_attribute);
3415
0
    return nullptr;
3416
0
  }
3417
0
  return ::new (Context) CodeSegAttr(Context, CI, Name);
3418
0
}
3419
3420
0
static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3421
0
  StringRef Str;
3422
0
  SourceLocation LiteralLoc;
3423
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3424
0
    return;
3425
0
  if (!checkCodeSegName(S, LiteralLoc, Str))
3426
0
    return;
3427
0
  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3428
0
    if (!ExistingAttr->isImplicit()) {
3429
0
      S.Diag(AL.getLoc(),
3430
0
             ExistingAttr->getName() == Str
3431
0
             ? diag::warn_duplicate_codeseg_attribute
3432
0
             : diag::err_conflicting_codeseg_attribute);
3433
0
      return;
3434
0
    }
3435
0
    D->dropAttr<CodeSegAttr>();
3436
0
  }
3437
0
  if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
3438
0
    D->addAttr(CSA);
3439
0
}
3440
3441
// Check for things we'd like to warn about. Multiversioning issues are
3442
// handled later in the process, once we know how many exist.
3443
0
bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3444
0
  enum FirstParam { Unsupported, Duplicate, Unknown };
3445
0
  enum SecondParam { None, CPU, Tune };
3446
0
  enum ThirdParam { Target, TargetClones };
3447
0
  if (AttrStr.contains("fpmath="))
3448
0
    return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3449
0
           << Unsupported << None << "fpmath=" << Target;
3450
3451
  // Diagnose use of tune if target doesn't support it.
3452
0
  if (!Context.getTargetInfo().supportsTargetAttributeTune() &&
3453
0
      AttrStr.contains("tune="))
3454
0
    return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3455
0
           << Unsupported << None << "tune=" << Target;
3456
3457
0
  ParsedTargetAttr ParsedAttrs =
3458
0
      Context.getTargetInfo().parseTargetAttr(AttrStr);
3459
3460
0
  if (!ParsedAttrs.CPU.empty() &&
3461
0
      !Context.getTargetInfo().isValidCPUName(ParsedAttrs.CPU))
3462
0
    return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3463
0
           << Unknown << CPU << ParsedAttrs.CPU << Target;
3464
3465
0
  if (!ParsedAttrs.Tune.empty() &&
3466
0
      !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune))
3467
0
    return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3468
0
           << Unknown << Tune << ParsedAttrs.Tune << Target;
3469
3470
0
  if (Context.getTargetInfo().getTriple().isRISCV() &&
3471
0
      ParsedAttrs.Duplicate != "")
3472
0
    return Diag(LiteralLoc, diag::err_duplicate_target_attribute)
3473
0
           << Duplicate << None << ParsedAttrs.Duplicate << Target;
3474
3475
0
  if (ParsedAttrs.Duplicate != "")
3476
0
    return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3477
0
           << Duplicate << None << ParsedAttrs.Duplicate << Target;
3478
3479
0
  for (const auto &Feature : ParsedAttrs.Features) {
3480
0
    auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3481
0
    if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3482
0
      return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3483
0
             << Unsupported << None << CurFeature << Target;
3484
0
  }
3485
3486
0
  TargetInfo::BranchProtectionInfo BPI;
3487
0
  StringRef DiagMsg;
3488
0
  if (ParsedAttrs.BranchProtection.empty())
3489
0
    return false;
3490
0
  if (!Context.getTargetInfo().validateBranchProtection(
3491
0
          ParsedAttrs.BranchProtection, ParsedAttrs.CPU, BPI, DiagMsg)) {
3492
0
    if (DiagMsg.empty())
3493
0
      return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3494
0
             << Unsupported << None << "branch-protection" << Target;
3495
0
    return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
3496
0
           << DiagMsg;
3497
0
  }
3498
0
  if (!DiagMsg.empty())
3499
0
    Diag(LiteralLoc, diag::warn_unsupported_branch_protection_spec) << DiagMsg;
3500
3501
0
  return false;
3502
0
}
3503
3504
// Check Target Version attrs
3505
bool Sema::checkTargetVersionAttr(SourceLocation LiteralLoc, StringRef &AttrStr,
3506
0
                                  bool &isDefault) {
3507
0
  enum FirstParam { Unsupported };
3508
0
  enum SecondParam { None };
3509
0
  enum ThirdParam { Target, TargetClones, TargetVersion };
3510
0
  if (AttrStr.trim() == "default")
3511
0
    isDefault = true;
3512
0
  llvm::SmallVector<StringRef, 8> Features;
3513
0
  AttrStr.split(Features, "+");
3514
0
  for (auto &CurFeature : Features) {
3515
0
    CurFeature = CurFeature.trim();
3516
0
    if (CurFeature == "default")
3517
0
      continue;
3518
0
    if (!Context.getTargetInfo().validateCpuSupports(CurFeature))
3519
0
      return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3520
0
             << Unsupported << None << CurFeature << TargetVersion;
3521
0
  }
3522
0
  return false;
3523
0
}
3524
3525
0
static void handleTargetVersionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3526
0
  StringRef Str;
3527
0
  SourceLocation LiteralLoc;
3528
0
  bool isDefault = false;
3529
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3530
0
      S.checkTargetVersionAttr(LiteralLoc, Str, isDefault))
3531
0
    return;
3532
  // Do not create default only target_version attribute
3533
0
  if (!isDefault) {
3534
0
    TargetVersionAttr *NewAttr =
3535
0
        ::new (S.Context) TargetVersionAttr(S.Context, AL, Str);
3536
0
    D->addAttr(NewAttr);
3537
0
  }
3538
0
}
3539
3540
0
static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3541
0
  StringRef Str;
3542
0
  SourceLocation LiteralLoc;
3543
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3544
0
      S.checkTargetAttr(LiteralLoc, Str))
3545
0
    return;
3546
3547
0
  TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3548
0
  D->addAttr(NewAttr);
3549
0
}
3550
3551
bool Sema::checkTargetClonesAttrString(
3552
    SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal,
3553
    bool &HasDefault, bool &HasCommas, bool &HasNotDefault,
3554
0
    SmallVectorImpl<SmallString<64>> &StringsBuffer) {
3555
0
  enum FirstParam { Unsupported, Duplicate, Unknown };
3556
0
  enum SecondParam { None, CPU, Tune };
3557
0
  enum ThirdParam { Target, TargetClones };
3558
0
  HasCommas = HasCommas || Str.contains(',');
3559
0
  const TargetInfo &TInfo = Context.getTargetInfo();
3560
  // Warn on empty at the beginning of a string.
3561
0
  if (Str.size() == 0)
3562
0
    return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3563
0
           << Unsupported << None << "" << TargetClones;
3564
3565
0
  std::pair<StringRef, StringRef> Parts = {{}, Str};
3566
0
  while (!Parts.second.empty()) {
3567
0
    Parts = Parts.second.split(',');
3568
0
    StringRef Cur = Parts.first.trim();
3569
0
    SourceLocation CurLoc =
3570
0
        Literal->getLocationOfByte(Cur.data() - Literal->getString().data(),
3571
0
                                   getSourceManager(), getLangOpts(), TInfo);
3572
3573
0
    bool DefaultIsDupe = false;
3574
0
    bool HasCodeGenImpact = false;
3575
0
    if (Cur.empty())
3576
0
      return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3577
0
             << Unsupported << None << "" << TargetClones;
3578
3579
0
    if (TInfo.getTriple().isAArch64()) {
3580
      // AArch64 target clones specific
3581
0
      if (Cur == "default") {
3582
0
        DefaultIsDupe = HasDefault;
3583
0
        HasDefault = true;
3584
0
        if (llvm::is_contained(StringsBuffer, Cur) || DefaultIsDupe)
3585
0
          Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3586
0
        else
3587
0
          StringsBuffer.push_back(Cur);
3588
0
      } else {
3589
0
        std::pair<StringRef, StringRef> CurParts = {{}, Cur};
3590
0
        llvm::SmallVector<StringRef, 8> CurFeatures;
3591
0
        while (!CurParts.second.empty()) {
3592
0
          CurParts = CurParts.second.split('+');
3593
0
          StringRef CurFeature = CurParts.first.trim();
3594
0
          if (!TInfo.validateCpuSupports(CurFeature)) {
3595
0
            Diag(CurLoc, diag::warn_unsupported_target_attribute)
3596
0
                << Unsupported << None << CurFeature << TargetClones;
3597
0
            continue;
3598
0
          }
3599
0
          if (TInfo.doesFeatureAffectCodeGen(CurFeature))
3600
0
            HasCodeGenImpact = true;
3601
0
          CurFeatures.push_back(CurFeature);
3602
0
        }
3603
        // Canonize TargetClones Attributes
3604
0
        llvm::sort(CurFeatures);
3605
0
        SmallString<64> Res;
3606
0
        for (auto &CurFeat : CurFeatures) {
3607
0
          if (!Res.equals(""))
3608
0
            Res.append("+");
3609
0
          Res.append(CurFeat);
3610
0
        }
3611
0
        if (llvm::is_contained(StringsBuffer, Res) || DefaultIsDupe)
3612
0
          Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3613
0
        else if (!HasCodeGenImpact)
3614
          // Ignore features in target_clone attribute that don't impact
3615
          // code generation
3616
0
          Diag(CurLoc, diag::warn_target_clone_no_impact_options);
3617
0
        else if (!Res.empty()) {
3618
0
          StringsBuffer.push_back(Res);
3619
0
          HasNotDefault = true;
3620
0
        }
3621
0
      }
3622
0
    } else {
3623
      // Other targets ( currently X86 )
3624
0
      if (Cur.starts_with("arch=")) {
3625
0
        if (!Context.getTargetInfo().isValidCPUName(
3626
0
                Cur.drop_front(sizeof("arch=") - 1)))
3627
0
          return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3628
0
                 << Unsupported << CPU << Cur.drop_front(sizeof("arch=") - 1)
3629
0
                 << TargetClones;
3630
0
      } else if (Cur == "default") {
3631
0
        DefaultIsDupe = HasDefault;
3632
0
        HasDefault = true;
3633
0
      } else if (!Context.getTargetInfo().isValidFeatureName(Cur))
3634
0
        return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3635
0
               << Unsupported << None << Cur << TargetClones;
3636
0
      if (llvm::is_contained(StringsBuffer, Cur) || DefaultIsDupe)
3637
0
        Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3638
      // Note: Add even if there are duplicates, since it changes name mangling.
3639
0
      StringsBuffer.push_back(Cur);
3640
0
    }
3641
0
  }
3642
0
  if (Str.rtrim().ends_with(","))
3643
0
    return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3644
0
           << Unsupported << None << "" << TargetClones;
3645
0
  return false;
3646
0
}
3647
3648
0
static void handleTargetClonesAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3649
0
  if (S.Context.getTargetInfo().getTriple().isAArch64() &&
3650
0
      !S.Context.getTargetInfo().hasFeature("fmv"))
3651
0
    return;
3652
3653
  // Ensure we don't combine these with themselves, since that causes some
3654
  // confusing behavior.
3655
0
  if (const auto *Other = D->getAttr<TargetClonesAttr>()) {
3656
0
    S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
3657
0
    S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
3658
0
    return;
3659
0
  }
3660
0
  if (checkAttrMutualExclusion<TargetClonesAttr>(S, D, AL))
3661
0
    return;
3662
3663
0
  SmallVector<StringRef, 2> Strings;
3664
0
  SmallVector<SmallString<64>, 2> StringsBuffer;
3665
0
  bool HasCommas = false, HasDefault = false, HasNotDefault = false;
3666
3667
0
  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
3668
0
    StringRef CurStr;
3669
0
    SourceLocation LiteralLoc;
3670
0
    if (!S.checkStringLiteralArgumentAttr(AL, I, CurStr, &LiteralLoc) ||
3671
0
        S.checkTargetClonesAttrString(
3672
0
            LiteralLoc, CurStr,
3673
0
            cast<StringLiteral>(AL.getArgAsExpr(I)->IgnoreParenCasts()),
3674
0
            HasDefault, HasCommas, HasNotDefault, StringsBuffer))
3675
0
      return;
3676
0
  }
3677
0
  for (auto &SmallStr : StringsBuffer)
3678
0
    Strings.push_back(SmallStr.str());
3679
3680
0
  if (HasCommas && AL.getNumArgs() > 1)
3681
0
    S.Diag(AL.getLoc(), diag::warn_target_clone_mixed_values);
3682
3683
0
  if (S.Context.getTargetInfo().getTriple().isAArch64() && !HasDefault) {
3684
    // Add default attribute if there is no one
3685
0
    HasDefault = true;
3686
0
    Strings.push_back("default");
3687
0
  }
3688
3689
0
  if (!HasDefault) {
3690
0
    S.Diag(AL.getLoc(), diag::err_target_clone_must_have_default);
3691
0
    return;
3692
0
  }
3693
3694
  // FIXME: We could probably figure out how to get this to work for lambdas
3695
  // someday.
3696
0
  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
3697
0
    if (MD->getParent()->isLambda()) {
3698
0
      S.Diag(D->getLocation(), diag::err_multiversion_doesnt_support)
3699
0
          << static_cast<unsigned>(MultiVersionKind::TargetClones)
3700
0
          << /*Lambda*/ 9;
3701
0
      return;
3702
0
    }
3703
0
  }
3704
3705
  // No multiversion if we have default version only.
3706
0
  if (S.Context.getTargetInfo().getTriple().isAArch64() && !HasNotDefault)
3707
0
    return;
3708
3709
0
  cast<FunctionDecl>(D)->setIsMultiVersion();
3710
0
  TargetClonesAttr *NewAttr = ::new (S.Context)
3711
0
      TargetClonesAttr(S.Context, AL, Strings.data(), Strings.size());
3712
0
  D->addAttr(NewAttr);
3713
0
}
3714
3715
0
static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3716
0
  Expr *E = AL.getArgAsExpr(0);
3717
0
  uint32_t VecWidth;
3718
0
  if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3719
0
    AL.setInvalid();
3720
0
    return;
3721
0
  }
3722
3723
0
  MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3724
0
  if (Existing && Existing->getVectorWidth() != VecWidth) {
3725
0
    S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3726
0
    return;
3727
0
  }
3728
3729
0
  D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3730
0
}
3731
3732
0
static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3733
0
  Expr *E = AL.getArgAsExpr(0);
3734
0
  SourceLocation Loc = E->getExprLoc();
3735
0
  FunctionDecl *FD = nullptr;
3736
0
  DeclarationNameInfo NI;
3737
3738
  // gcc only allows for simple identifiers. Since we support more than gcc, we
3739
  // will warn the user.
3740
0
  if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3741
0
    if (DRE->hasQualifier())
3742
0
      S.Diag(Loc, diag::warn_cleanup_ext);
3743
0
    FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3744
0
    NI = DRE->getNameInfo();
3745
0
    if (!FD) {
3746
0
      S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3747
0
        << NI.getName();
3748
0
      return;
3749
0
    }
3750
0
  } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3751
0
    if (ULE->hasExplicitTemplateArgs())
3752
0
      S.Diag(Loc, diag::warn_cleanup_ext);
3753
0
    FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3754
0
    NI = ULE->getNameInfo();
3755
0
    if (!FD) {
3756
0
      S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3757
0
        << NI.getName();
3758
0
      if (ULE->getType() == S.Context.OverloadTy)
3759
0
        S.NoteAllOverloadCandidates(ULE);
3760
0
      return;
3761
0
    }
3762
0
  } else {
3763
0
    S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3764
0
    return;
3765
0
  }
3766
3767
0
  if (FD->getNumParams() != 1) {
3768
0
    S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3769
0
      << NI.getName();
3770
0
    return;
3771
0
  }
3772
3773
  // We're currently more strict than GCC about what function types we accept.
3774
  // If this ever proves to be a problem it should be easy to fix.
3775
0
  QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3776
0
  QualType ParamTy = FD->getParamDecl(0)->getType();
3777
0
  if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3778
0
                                   ParamTy, Ty) != Sema::Compatible) {
3779
0
    S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3780
0
      << NI.getName() << ParamTy << Ty;
3781
0
    return;
3782
0
  }
3783
3784
0
  D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
3785
0
}
3786
3787
static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3788
0
                                        const ParsedAttr &AL) {
3789
0
  if (!AL.isArgIdent(0)) {
3790
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3791
0
        << AL << 0 << AANT_ArgumentIdentifier;
3792
0
    return;
3793
0
  }
3794
3795
0
  EnumExtensibilityAttr::Kind ExtensibilityKind;
3796
0
  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3797
0
  if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3798
0
                                               ExtensibilityKind)) {
3799
0
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3800
0
    return;
3801
0
  }
3802
3803
0
  D->addAttr(::new (S.Context)
3804
0
                 EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3805
0
}
3806
3807
/// Handle __attribute__((format_arg((idx)))) attribute based on
3808
/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3809
0
static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3810
0
  const Expr *IdxExpr = AL.getArgAsExpr(0);
3811
0
  ParamIdx Idx;
3812
0
  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3813
0
    return;
3814
3815
  // Make sure the format string is really a string.
3816
0
  QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
3817
3818
0
  bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3819
0
  if (NotNSStringTy &&
3820
0
      !isCFStringType(Ty, S.Context) &&
3821
0
      (!Ty->isPointerType() ||
3822
0
       !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3823
0
    S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3824
0
        << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3825
0
    return;
3826
0
  }
3827
0
  Ty = getFunctionOrMethodResultType(D);
3828
  // replace instancetype with the class type
3829
0
  auto Instancetype = S.Context.getObjCInstanceTypeDecl()->getTypeForDecl();
3830
0
  if (Ty->getAs<TypedefType>() == Instancetype)
3831
0
    if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3832
0
      if (auto *Interface = OMD->getClassInterface())
3833
0
        Ty = S.Context.getObjCObjectPointerType(
3834
0
            QualType(Interface->getTypeForDecl(), 0));
3835
0
  if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true) &&
3836
0
      !isCFStringType(Ty, S.Context) &&
3837
0
      (!Ty->isPointerType() ||
3838
0
       !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3839
0
    S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3840
0
        << (NotNSStringTy ? "string type" : "NSString")
3841
0
        << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3842
0
    return;
3843
0
  }
3844
3845
0
  D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
3846
0
}
3847
3848
enum FormatAttrKind {
3849
  CFStringFormat,
3850
  NSStringFormat,
3851
  StrftimeFormat,
3852
  SupportedFormat,
3853
  IgnoredFormat,
3854
  InvalidFormat
3855
};
3856
3857
/// getFormatAttrKind - Map from format attribute names to supported format
3858
/// types.
3859
0
static FormatAttrKind getFormatAttrKind(StringRef Format) {
3860
0
  return llvm::StringSwitch<FormatAttrKind>(Format)
3861
      // Check for formats that get handled specially.
3862
0
      .Case("NSString", NSStringFormat)
3863
0
      .Case("CFString", CFStringFormat)
3864
0
      .Case("strftime", StrftimeFormat)
3865
3866
      // Otherwise, check for supported formats.
3867
0
      .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3868
0
      .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3869
0
      .Case("kprintf", SupportedFormat)         // OpenBSD.
3870
0
      .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3871
0
      .Case("os_trace", SupportedFormat)
3872
0
      .Case("os_log", SupportedFormat)
3873
3874
0
      .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3875
0
      .Default(InvalidFormat);
3876
0
}
3877
3878
/// Handle __attribute__((init_priority(priority))) attributes based on
3879
/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3880
0
static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3881
0
  if (!S.getLangOpts().CPlusPlus) {
3882
0
    S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3883
0
    return;
3884
0
  }
3885
3886
0
  if (S.getLangOpts().HLSL) {
3887
0
    S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
3888
0
    return;
3889
0
  }
3890
3891
0
  if (S.getCurFunctionOrMethodDecl()) {
3892
0
    S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3893
0
    AL.setInvalid();
3894
0
    return;
3895
0
  }
3896
0
  QualType T = cast<VarDecl>(D)->getType();
3897
0
  if (S.Context.getAsArrayType(T))
3898
0
    T = S.Context.getBaseElementType(T);
3899
0
  if (!T->getAs<RecordType>()) {
3900
0
    S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3901
0
    AL.setInvalid();
3902
0
    return;
3903
0
  }
3904
3905
0
  Expr *E = AL.getArgAsExpr(0);
3906
0
  uint32_t prioritynum;
3907
0
  if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3908
0
    AL.setInvalid();
3909
0
    return;
3910
0
  }
3911
3912
  // Only perform the priority check if the attribute is outside of a system
3913
  // header. Values <= 100 are reserved for the implementation, and libc++
3914
  // benefits from being able to specify values in that range.
3915
0
  if ((prioritynum < 101 || prioritynum > 65535) &&
3916
0
      !S.getSourceManager().isInSystemHeader(AL.getLoc())) {
3917
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3918
0
        << E->getSourceRange() << AL << 101 << 65535;
3919
0
    AL.setInvalid();
3920
0
    return;
3921
0
  }
3922
0
  D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3923
0
}
3924
3925
ErrorAttr *Sema::mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3926
0
                                StringRef NewUserDiagnostic) {
3927
0
  if (const auto *EA = D->getAttr<ErrorAttr>()) {
3928
0
    std::string NewAttr = CI.getNormalizedFullName();
3929
0
    assert((NewAttr == "error" || NewAttr == "warning") &&
3930
0
           "unexpected normalized full name");
3931
0
    bool Match = (EA->isError() && NewAttr == "error") ||
3932
0
                 (EA->isWarning() && NewAttr == "warning");
3933
0
    if (!Match) {
3934
0
      Diag(EA->getLocation(), diag::err_attributes_are_not_compatible)
3935
0
          << CI << EA
3936
0
          << (CI.isRegularKeywordAttribute() ||
3937
0
              EA->isRegularKeywordAttribute());
3938
0
      Diag(CI.getLoc(), diag::note_conflicting_attribute);
3939
0
      return nullptr;
3940
0
    }
3941
0
    if (EA->getUserDiagnostic() != NewUserDiagnostic) {
3942
0
      Diag(CI.getLoc(), diag::warn_duplicate_attribute) << EA;
3943
0
      Diag(EA->getLoc(), diag::note_previous_attribute);
3944
0
    }
3945
0
    D->dropAttr<ErrorAttr>();
3946
0
  }
3947
0
  return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic);
3948
0
}
3949
3950
FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3951
                                  IdentifierInfo *Format, int FormatIdx,
3952
0
                                  int FirstArg) {
3953
  // Check whether we already have an equivalent format attribute.
3954
0
  for (auto *F : D->specific_attrs<FormatAttr>()) {
3955
0
    if (F->getType() == Format &&
3956
0
        F->getFormatIdx() == FormatIdx &&
3957
0
        F->getFirstArg() == FirstArg) {
3958
      // If we don't have a valid location for this attribute, adopt the
3959
      // location.
3960
0
      if (F->getLocation().isInvalid())
3961
0
        F->setRange(CI.getRange());
3962
0
      return nullptr;
3963
0
    }
3964
0
  }
3965
3966
0
  return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3967
0
}
3968
3969
/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3970
/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3971
0
static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3972
0
  if (!AL.isArgIdent(0)) {
3973
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3974
0
        << AL << 1 << AANT_ArgumentIdentifier;
3975
0
    return;
3976
0
  }
3977
3978
  // In C++ the implicit 'this' function parameter also counts, and they are
3979
  // counted from one.
3980
0
  bool HasImplicitThisParam = isInstanceMethod(D);
3981
0
  unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3982
3983
0
  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3984
0
  StringRef Format = II->getName();
3985
3986
0
  if (normalizeName(Format)) {
3987
    // If we've modified the string name, we need a new identifier for it.
3988
0
    II = &S.Context.Idents.get(Format);
3989
0
  }
3990
3991
  // Check for supported formats.
3992
0
  FormatAttrKind Kind = getFormatAttrKind(Format);
3993
3994
0
  if (Kind == IgnoredFormat)
3995
0
    return;
3996
3997
0
  if (Kind == InvalidFormat) {
3998
0
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3999
0
        << AL << II->getName();
4000
0
    return;
4001
0
  }
4002
4003
  // checks for the 2nd argument
4004
0
  Expr *IdxExpr = AL.getArgAsExpr(1);
4005
0
  uint32_t Idx;
4006
0
  if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
4007
0
    return;
4008
4009
0
  if (Idx < 1 || Idx > NumArgs) {
4010
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4011
0
        << AL << 2 << IdxExpr->getSourceRange();
4012
0
    return;
4013
0
  }
4014
4015
  // FIXME: Do we need to bounds check?
4016
0
  unsigned ArgIdx = Idx - 1;
4017
4018
0
  if (HasImplicitThisParam) {
4019
0
    if (ArgIdx == 0) {
4020
0
      S.Diag(AL.getLoc(),
4021
0
             diag::err_format_attribute_implicit_this_format_string)
4022
0
        << IdxExpr->getSourceRange();
4023
0
      return;
4024
0
    }
4025
0
    ArgIdx--;
4026
0
  }
4027
4028
  // make sure the format string is really a string
4029
0
  QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
4030
4031
0
  if (!isNSStringType(Ty, S.Context, true) &&
4032
0
      !isCFStringType(Ty, S.Context) &&
4033
0
      (!Ty->isPointerType() ||
4034
0
       !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
4035
0
    S.Diag(AL.getLoc(), diag::err_format_attribute_not)
4036
0
      << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, ArgIdx);
4037
0
    return;
4038
0
  }
4039
4040
  // check the 3rd argument
4041
0
  Expr *FirstArgExpr = AL.getArgAsExpr(2);
4042
0
  uint32_t FirstArg;
4043
0
  if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
4044
0
    return;
4045
4046
  // FirstArg == 0 is is always valid.
4047
0
  if (FirstArg != 0) {
4048
0
    if (Kind == StrftimeFormat) {
4049
      // If the kind is strftime, FirstArg must be 0 because strftime does not
4050
      // use any variadic arguments.
4051
0
      S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
4052
0
          << FirstArgExpr->getSourceRange()
4053
0
          << FixItHint::CreateReplacement(FirstArgExpr->getSourceRange(), "0");
4054
0
      return;
4055
0
    } else if (isFunctionOrMethodVariadic(D)) {
4056
      // Else, if the function is variadic, then FirstArg must be 0 or the
4057
      // "position" of the ... parameter. It's unusual to use 0 with variadic
4058
      // functions, so the fixit proposes the latter.
4059
0
      if (FirstArg != NumArgs + 1) {
4060
0
        S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4061
0
            << AL << 3 << FirstArgExpr->getSourceRange()
4062
0
            << FixItHint::CreateReplacement(FirstArgExpr->getSourceRange(),
4063
0
                                            std::to_string(NumArgs + 1));
4064
0
        return;
4065
0
      }
4066
0
    } else {
4067
      // Inescapable GCC compatibility diagnostic.
4068
0
      S.Diag(D->getLocation(), diag::warn_gcc_requires_variadic_function) << AL;
4069
0
      if (FirstArg <= Idx) {
4070
        // Else, the function is not variadic, and FirstArg must be 0 or any
4071
        // parameter after the format parameter. We don't offer a fixit because
4072
        // there are too many possible good values.
4073
0
        S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4074
0
            << AL << 3 << FirstArgExpr->getSourceRange();
4075
0
        return;
4076
0
      }
4077
0
    }
4078
0
  }
4079
4080
0
  FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
4081
0
  if (NewAttr)
4082
0
    D->addAttr(NewAttr);
4083
0
}
4084
4085
/// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
4086
0
static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4087
  // The index that identifies the callback callee is mandatory.
4088
0
  if (AL.getNumArgs() == 0) {
4089
0
    S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
4090
0
        << AL.getRange();
4091
0
    return;
4092
0
  }
4093
4094
0
  bool HasImplicitThisParam = isInstanceMethod(D);
4095
0
  int32_t NumArgs = getFunctionOrMethodNumParams(D);
4096
4097
0
  FunctionDecl *FD = D->getAsFunction();
4098
0
  assert(FD && "Expected a function declaration!");
4099
4100
0
  llvm::StringMap<int> NameIdxMapping;
4101
0
  NameIdxMapping["__"] = -1;
4102
4103
0
  NameIdxMapping["this"] = 0;
4104
4105
0
  int Idx = 1;
4106
0
  for (const ParmVarDecl *PVD : FD->parameters())
4107
0
    NameIdxMapping[PVD->getName()] = Idx++;
4108
4109
0
  auto UnknownName = NameIdxMapping.end();
4110
4111
0
  SmallVector<int, 8> EncodingIndices;
4112
0
  for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
4113
0
    SourceRange SR;
4114
0
    int32_t ArgIdx;
4115
4116
0
    if (AL.isArgIdent(I)) {
4117
0
      IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
4118
0
      auto It = NameIdxMapping.find(IdLoc->Ident->getName());
4119
0
      if (It == UnknownName) {
4120
0
        S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
4121
0
            << IdLoc->Ident << IdLoc->Loc;
4122
0
        return;
4123
0
      }
4124
4125
0
      SR = SourceRange(IdLoc->Loc);
4126
0
      ArgIdx = It->second;
4127
0
    } else if (AL.isArgExpr(I)) {
4128
0
      Expr *IdxExpr = AL.getArgAsExpr(I);
4129
4130
      // If the expression is not parseable as an int32_t we have a problem.
4131
0
      if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
4132
0
                               false)) {
4133
0
        S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4134
0
            << AL << (I + 1) << IdxExpr->getSourceRange();
4135
0
        return;
4136
0
      }
4137
4138
      // Check oob, excluding the special values, 0 and -1.
4139
0
      if (ArgIdx < -1 || ArgIdx > NumArgs) {
4140
0
        S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4141
0
            << AL << (I + 1) << IdxExpr->getSourceRange();
4142
0
        return;
4143
0
      }
4144
4145
0
      SR = IdxExpr->getSourceRange();
4146
0
    } else {
4147
0
      llvm_unreachable("Unexpected ParsedAttr argument type!");
4148
0
    }
4149
4150
0
    if (ArgIdx == 0 && !HasImplicitThisParam) {
4151
0
      S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
4152
0
          << (I + 1) << SR;
4153
0
      return;
4154
0
    }
4155
4156
    // Adjust for the case we do not have an implicit "this" parameter. In this
4157
    // case we decrease all positive values by 1 to get LLVM argument indices.
4158
0
    if (!HasImplicitThisParam && ArgIdx > 0)
4159
0
      ArgIdx -= 1;
4160
4161
0
    EncodingIndices.push_back(ArgIdx);
4162
0
  }
4163
4164
0
  int CalleeIdx = EncodingIndices.front();
4165
  // Check if the callee index is proper, thus not "this" and not "unknown".
4166
  // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
4167
  // is false and positive if "HasImplicitThisParam" is true.
4168
0
  if (CalleeIdx < (int)HasImplicitThisParam) {
4169
0
    S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
4170
0
        << AL.getRange();
4171
0
    return;
4172
0
  }
4173
4174
  // Get the callee type, note the index adjustment as the AST doesn't contain
4175
  // the this type (which the callee cannot reference anyway!).
4176
0
  const Type *CalleeType =
4177
0
      getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
4178
0
          .getTypePtr();
4179
0
  if (!CalleeType || !CalleeType->isFunctionPointerType()) {
4180
0
    S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
4181
0
        << AL.getRange();
4182
0
    return;
4183
0
  }
4184
4185
0
  const Type *CalleeFnType =
4186
0
      CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
4187
4188
  // TODO: Check the type of the callee arguments.
4189
4190
0
  const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
4191
0
  if (!CalleeFnProtoType) {
4192
0
    S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
4193
0
        << AL.getRange();
4194
0
    return;
4195
0
  }
4196
4197
0
  if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
4198
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
4199
0
        << AL << (unsigned)(EncodingIndices.size() - 1);
4200
0
    return;
4201
0
  }
4202
4203
0
  if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
4204
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
4205
0
        << AL << (unsigned)(EncodingIndices.size() - 1);
4206
0
    return;
4207
0
  }
4208
4209
0
  if (CalleeFnProtoType->isVariadic()) {
4210
0
    S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
4211
0
    return;
4212
0
  }
4213
4214
  // Do not allow multiple callback attributes.
4215
0
  if (D->hasAttr<CallbackAttr>()) {
4216
0
    S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
4217
0
    return;
4218
0
  }
4219
4220
0
  D->addAttr(::new (S.Context) CallbackAttr(
4221
0
      S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
4222
0
}
4223
4224
0
static bool isFunctionLike(const Type &T) {
4225
  // Check for explicit function types.
4226
  // 'called_once' is only supported in Objective-C and it has
4227
  // function pointers and block pointers.
4228
0
  return T.isFunctionPointerType() || T.isBlockPointerType();
4229
0
}
4230
4231
/// Handle 'called_once' attribute.
4232
0
static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4233
  // 'called_once' only applies to parameters representing functions.
4234
0
  QualType T = cast<ParmVarDecl>(D)->getType();
4235
4236
0
  if (!isFunctionLike(*T)) {
4237
0
    S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type);
4238
0
    return;
4239
0
  }
4240
4241
0
  D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL));
4242
0
}
4243
4244
0
static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4245
  // Try to find the underlying union declaration.
4246
0
  RecordDecl *RD = nullptr;
4247
0
  const auto *TD = dyn_cast<TypedefNameDecl>(D);
4248
0
  if (TD && TD->getUnderlyingType()->isUnionType())
4249
0
    RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
4250
0
  else
4251
0
    RD = dyn_cast<RecordDecl>(D);
4252
4253
0
  if (!RD || !RD->isUnion()) {
4254
0
    S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4255
0
        << AL << AL.isRegularKeywordAttribute() << ExpectedUnion;
4256
0
    return;
4257
0
  }
4258
4259
0
  if (!RD->isCompleteDefinition()) {
4260
0
    if (!RD->isBeingDefined())
4261
0
      S.Diag(AL.getLoc(),
4262
0
             diag::warn_transparent_union_attribute_not_definition);
4263
0
    return;
4264
0
  }
4265
4266
0
  RecordDecl::field_iterator Field = RD->field_begin(),
4267
0
                          FieldEnd = RD->field_end();
4268
0
  if (Field == FieldEnd) {
4269
0
    S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
4270
0
    return;
4271
0
  }
4272
4273
0
  FieldDecl *FirstField = *Field;
4274
0
  QualType FirstType = FirstField->getType();
4275
0
  if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
4276
0
    S.Diag(FirstField->getLocation(),
4277
0
           diag::warn_transparent_union_attribute_floating)
4278
0
      << FirstType->isVectorType() << FirstType;
4279
0
    return;
4280
0
  }
4281
4282
0
  if (FirstType->isIncompleteType())
4283
0
    return;
4284
0
  uint64_t FirstSize = S.Context.getTypeSize(FirstType);
4285
0
  uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
4286
0
  for (; Field != FieldEnd; ++Field) {
4287
0
    QualType FieldType = Field->getType();
4288
0
    if (FieldType->isIncompleteType())
4289
0
      return;
4290
    // FIXME: this isn't fully correct; we also need to test whether the
4291
    // members of the union would all have the same calling convention as the
4292
    // first member of the union. Checking just the size and alignment isn't
4293
    // sufficient (consider structs passed on the stack instead of in registers
4294
    // as an example).
4295
0
    if (S.Context.getTypeSize(FieldType) != FirstSize ||
4296
0
        S.Context.getTypeAlign(FieldType) > FirstAlign) {
4297
      // Warn if we drop the attribute.
4298
0
      bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
4299
0
      unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType)
4300
0
                                  : S.Context.getTypeAlign(FieldType);
4301
0
      S.Diag(Field->getLocation(),
4302
0
             diag::warn_transparent_union_attribute_field_size_align)
4303
0
          << isSize << *Field << FieldBits;
4304
0
      unsigned FirstBits = isSize ? FirstSize : FirstAlign;
4305
0
      S.Diag(FirstField->getLocation(),
4306
0
             diag::note_transparent_union_first_field_size_align)
4307
0
          << isSize << FirstBits;
4308
0
      return;
4309
0
    }
4310
0
  }
4311
4312
0
  RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
4313
0
}
4314
4315
void Sema::AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
4316
0
                             StringRef Str, MutableArrayRef<Expr *> Args) {
4317
0
  auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI);
4318
0
  if (ConstantFoldAttrArgs(
4319
0
          CI, MutableArrayRef<Expr *>(Attr->args_begin(), Attr->args_end()))) {
4320
0
    D->addAttr(Attr);
4321
0
  }
4322
0
}
4323
4324
0
static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4325
  // Make sure that there is a string literal as the annotation's first
4326
  // argument.
4327
0
  StringRef Str;
4328
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
4329
0
    return;
4330
4331
0
  llvm::SmallVector<Expr *, 4> Args;
4332
0
  Args.reserve(AL.getNumArgs() - 1);
4333
0
  for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
4334
0
    assert(!AL.isArgIdent(Idx));
4335
0
    Args.push_back(AL.getArgAsExpr(Idx));
4336
0
  }
4337
4338
0
  S.AddAnnotationAttr(D, AL, Str, Args);
4339
0
}
4340
4341
0
static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4342
0
  S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
4343
0
}
4344
4345
0
void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) {
4346
0
  AlignValueAttr TmpAttr(Context, CI, E);
4347
0
  SourceLocation AttrLoc = CI.getLoc();
4348
4349
0
  QualType T;
4350
0
  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4351
0
    T = TD->getUnderlyingType();
4352
0
  else if (const auto *VD = dyn_cast<ValueDecl>(D))
4353
0
    T = VD->getType();
4354
0
  else
4355
0
    llvm_unreachable("Unknown decl type for align_value");
4356
4357
0
  if (!T->isDependentType() && !T->isAnyPointerType() &&
4358
0
      !T->isReferenceType() && !T->isMemberPointerType()) {
4359
0
    Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
4360
0
      << &TmpAttr << T << D->getSourceRange();
4361
0
    return;
4362
0
  }
4363
4364
0
  if (!E->isValueDependent()) {
4365
0
    llvm::APSInt Alignment;
4366
0
    ExprResult ICE = VerifyIntegerConstantExpression(
4367
0
        E, &Alignment, diag::err_align_value_attribute_argument_not_int);
4368
0
    if (ICE.isInvalid())
4369
0
      return;
4370
4371
0
    if (!Alignment.isPowerOf2()) {
4372
0
      Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4373
0
        << E->getSourceRange();
4374
0
      return;
4375
0
    }
4376
4377
0
    D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
4378
0
    return;
4379
0
  }
4380
4381
  // Save dependent expressions in the AST to be instantiated.
4382
0
  D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
4383
0
}
4384
4385
0
static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4386
0
  if (AL.hasParsedType()) {
4387
0
    const ParsedType &TypeArg = AL.getTypeArg();
4388
0
    TypeSourceInfo *TInfo;
4389
0
    (void)S.GetTypeFromParser(
4390
0
        ParsedType::getFromOpaquePtr(TypeArg.getAsOpaquePtr()), &TInfo);
4391
0
    if (AL.isPackExpansion() &&
4392
0
        !TInfo->getType()->containsUnexpandedParameterPack()) {
4393
0
      S.Diag(AL.getEllipsisLoc(),
4394
0
             diag::err_pack_expansion_without_parameter_packs);
4395
0
      return;
4396
0
    }
4397
4398
0
    if (!AL.isPackExpansion() &&
4399
0
        S.DiagnoseUnexpandedParameterPack(TInfo->getTypeLoc().getBeginLoc(),
4400
0
                                          TInfo, Sema::UPPC_Expression))
4401
0
      return;
4402
4403
0
    S.AddAlignedAttr(D, AL, TInfo, AL.isPackExpansion());
4404
0
    return;
4405
0
  }
4406
4407
  // check the attribute arguments.
4408
0
  if (AL.getNumArgs() > 1) {
4409
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
4410
0
    return;
4411
0
  }
4412
4413
0
  if (AL.getNumArgs() == 0) {
4414
0
    D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
4415
0
    return;
4416
0
  }
4417
4418
0
  Expr *E = AL.getArgAsExpr(0);
4419
0
  if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
4420
0
    S.Diag(AL.getEllipsisLoc(),
4421
0
           diag::err_pack_expansion_without_parameter_packs);
4422
0
    return;
4423
0
  }
4424
4425
0
  if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
4426
0
    return;
4427
4428
0
  S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
4429
0
}
4430
4431
/// Perform checking of type validity
4432
///
4433
/// C++11 [dcl.align]p1:
4434
///   An alignment-specifier may be applied to a variable or to a class
4435
///   data member, but it shall not be applied to a bit-field, a function
4436
///   parameter, the formal parameter of a catch clause, or a variable
4437
///   declared with the register storage class specifier. An
4438
///   alignment-specifier may also be applied to the declaration of a class
4439
///   or enumeration type.
4440
/// CWG 2354:
4441
///   CWG agreed to remove permission for alignas to be applied to
4442
///   enumerations.
4443
/// C11 6.7.5/2:
4444
///   An alignment attribute shall not be specified in a declaration of
4445
///   a typedef, or a bit-field, or a function, or a parameter, or an
4446
///   object declared with the register storage-class specifier.
4447
static bool validateAlignasAppliedType(Sema &S, Decl *D,
4448
                                       const AlignedAttr &Attr,
4449
0
                                       SourceLocation AttrLoc) {
4450
0
  int DiagKind = -1;
4451
0
  if (isa<ParmVarDecl>(D)) {
4452
0
    DiagKind = 0;
4453
0
  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
4454
0
    if (VD->getStorageClass() == SC_Register)
4455
0
      DiagKind = 1;
4456
0
    if (VD->isExceptionVariable())
4457
0
      DiagKind = 2;
4458
0
  } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
4459
0
    if (FD->isBitField())
4460
0
      DiagKind = 3;
4461
0
  } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4462
0
    if (ED->getLangOpts().CPlusPlus)
4463
0
      DiagKind = 4;
4464
0
  } else if (!isa<TagDecl>(D)) {
4465
0
    return S.Diag(AttrLoc, diag::err_attribute_wrong_decl_type)
4466
0
           << &Attr << Attr.isRegularKeywordAttribute()
4467
0
           << (Attr.isC11() ? ExpectedVariableOrField
4468
0
                            : ExpectedVariableFieldOrTag);
4469
0
  }
4470
0
  if (DiagKind != -1) {
4471
0
    return S.Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
4472
0
           << &Attr << DiagKind;
4473
0
  }
4474
0
  return false;
4475
0
}
4476
4477
void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4478
0
                          bool IsPackExpansion) {
4479
0
  AlignedAttr TmpAttr(Context, CI, true, E);
4480
0
  SourceLocation AttrLoc = CI.getLoc();
4481
4482
  // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4483
0
  if (TmpAttr.isAlignas() &&
4484
0
      validateAlignasAppliedType(*this, D, TmpAttr, AttrLoc))
4485
0
    return;
4486
4487
0
  if (E->isValueDependent()) {
4488
    // We can't support a dependent alignment on a non-dependent type,
4489
    // because we have no way to model that a type is "alignment-dependent"
4490
    // but not dependent in any other way.
4491
0
    if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
4492
0
      if (!TND->getUnderlyingType()->isDependentType()) {
4493
0
        Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4494
0
            << E->getSourceRange();
4495
0
        return;
4496
0
      }
4497
0
    }
4498
4499
    // Save dependent expressions in the AST to be instantiated.
4500
0
    AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
4501
0
    AA->setPackExpansion(IsPackExpansion);
4502
0
    D->addAttr(AA);
4503
0
    return;
4504
0
  }
4505
4506
  // FIXME: Cache the number on the AL object?
4507
0
  llvm::APSInt Alignment;
4508
0
  ExprResult ICE = VerifyIntegerConstantExpression(
4509
0
      E, &Alignment, diag::err_aligned_attribute_argument_not_int);
4510
0
  if (ICE.isInvalid())
4511
0
    return;
4512
4513
0
  uint64_t MaximumAlignment = Sema::MaximumAlignment;
4514
0
  if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
4515
0
    MaximumAlignment = std::min(MaximumAlignment, uint64_t(8192));
4516
0
  if (Alignment > MaximumAlignment) {
4517
0
    Diag(AttrLoc, diag::err_attribute_aligned_too_great)
4518
0
        << MaximumAlignment << E->getSourceRange();
4519
0
    return;
4520
0
  }
4521
4522
0
  uint64_t AlignVal = Alignment.getZExtValue();
4523
  // C++11 [dcl.align]p2:
4524
  //   -- if the constant expression evaluates to zero, the alignment
4525
  //      specifier shall have no effect
4526
  // C11 6.7.5p6:
4527
  //   An alignment specification of zero has no effect.
4528
0
  if (!(TmpAttr.isAlignas() && !Alignment)) {
4529
0
    if (!llvm::isPowerOf2_64(AlignVal)) {
4530
0
      Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4531
0
        << E->getSourceRange();
4532
0
      return;
4533
0
    }
4534
0
  }
4535
4536
0
  const auto *VD = dyn_cast<VarDecl>(D);
4537
0
  if (VD) {
4538
0
    unsigned MaxTLSAlign =
4539
0
        Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
4540
0
            .getQuantity();
4541
0
    if (MaxTLSAlign && AlignVal > MaxTLSAlign &&
4542
0
        VD->getTLSKind() != VarDecl::TLS_None) {
4543
0
      Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
4544
0
          << (unsigned)AlignVal << VD << MaxTLSAlign;
4545
0
      return;
4546
0
    }
4547
0
  }
4548
4549
  // On AIX, an aligned attribute can not decrease the alignment when applied
4550
  // to a variable declaration with vector type.
4551
0
  if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4552
0
    const Type *Ty = VD->getType().getTypePtr();
4553
0
    if (Ty->isVectorType() && AlignVal < 16) {
4554
0
      Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4555
0
          << VD->getType() << 16;
4556
0
      return;
4557
0
    }
4558
0
  }
4559
4560
0
  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
4561
0
  AA->setPackExpansion(IsPackExpansion);
4562
0
  AA->setCachedAlignmentValue(
4563
0
      static_cast<unsigned>(AlignVal * Context.getCharWidth()));
4564
0
  D->addAttr(AA);
4565
0
}
4566
4567
void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI,
4568
0
                          TypeSourceInfo *TS, bool IsPackExpansion) {
4569
0
  AlignedAttr TmpAttr(Context, CI, false, TS);
4570
0
  SourceLocation AttrLoc = CI.getLoc();
4571
4572
  // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4573
0
  if (TmpAttr.isAlignas() &&
4574
0
      validateAlignasAppliedType(*this, D, TmpAttr, AttrLoc))
4575
0
    return;
4576
4577
0
  if (TS->getType()->isDependentType()) {
4578
    // We can't support a dependent alignment on a non-dependent type,
4579
    // because we have no way to model that a type is "type-dependent"
4580
    // but not dependent in any other way.
4581
0
    if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
4582
0
      if (!TND->getUnderlyingType()->isDependentType()) {
4583
0
        Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4584
0
            << TS->getTypeLoc().getSourceRange();
4585
0
        return;
4586
0
      }
4587
0
    }
4588
4589
0
    AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4590
0
    AA->setPackExpansion(IsPackExpansion);
4591
0
    D->addAttr(AA);
4592
0
    return;
4593
0
  }
4594
4595
0
  const auto *VD = dyn_cast<VarDecl>(D);
4596
0
  unsigned AlignVal = TmpAttr.getAlignment(Context);
4597
  // On AIX, an aligned attribute can not decrease the alignment when applied
4598
  // to a variable declaration with vector type.
4599
0
  if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4600
0
    const Type *Ty = VD->getType().getTypePtr();
4601
0
    if (Ty->isVectorType() &&
4602
0
        Context.toCharUnitsFromBits(AlignVal).getQuantity() < 16) {
4603
0
      Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4604
0
          << VD->getType() << 16;
4605
0
      return;
4606
0
    }
4607
0
  }
4608
4609
0
  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4610
0
  AA->setPackExpansion(IsPackExpansion);
4611
0
  AA->setCachedAlignmentValue(AlignVal);
4612
0
  D->addAttr(AA);
4613
0
}
4614
4615
0
void Sema::CheckAlignasUnderalignment(Decl *D) {
4616
0
  assert(D->hasAttrs() && "no attributes on decl");
4617
4618
0
  QualType UnderlyingTy, DiagTy;
4619
0
  if (const auto *VD = dyn_cast<ValueDecl>(D)) {
4620
0
    UnderlyingTy = DiagTy = VD->getType();
4621
0
  } else {
4622
0
    UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
4623
0
    if (const auto *ED = dyn_cast<EnumDecl>(D))
4624
0
      UnderlyingTy = ED->getIntegerType();
4625
0
  }
4626
0
  if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
4627
0
    return;
4628
4629
  // C++11 [dcl.align]p5, C11 6.7.5/4:
4630
  //   The combined effect of all alignment attributes in a declaration shall
4631
  //   not specify an alignment that is less strict than the alignment that
4632
  //   would otherwise be required for the entity being declared.
4633
0
  AlignedAttr *AlignasAttr = nullptr;
4634
0
  AlignedAttr *LastAlignedAttr = nullptr;
4635
0
  unsigned Align = 0;
4636
0
  for (auto *I : D->specific_attrs<AlignedAttr>()) {
4637
0
    if (I->isAlignmentDependent())
4638
0
      return;
4639
0
    if (I->isAlignas())
4640
0
      AlignasAttr = I;
4641
0
    Align = std::max(Align, I->getAlignment(Context));
4642
0
    LastAlignedAttr = I;
4643
0
  }
4644
4645
0
  if (Align && DiagTy->isSizelessType()) {
4646
0
    Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
4647
0
        << LastAlignedAttr << DiagTy;
4648
0
  } else if (AlignasAttr && Align) {
4649
0
    CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
4650
0
    CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
4651
0
    if (NaturalAlign > RequestedAlign)
4652
0
      Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
4653
0
        << DiagTy << (unsigned)NaturalAlign.getQuantity();
4654
0
  }
4655
0
}
4656
4657
bool Sema::checkMSInheritanceAttrOnDefinition(
4658
    CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4659
0
    MSInheritanceModel ExplicitModel) {
4660
0
  assert(RD->hasDefinition() && "RD has no definition!");
4661
4662
  // We may not have seen base specifiers or any virtual methods yet.  We will
4663
  // have to wait until the record is defined to catch any mismatches.
4664
0
  if (!RD->getDefinition()->isCompleteDefinition())
4665
0
    return false;
4666
4667
  // The unspecified model never matches what a definition could need.
4668
0
  if (ExplicitModel == MSInheritanceModel::Unspecified)
4669
0
    return false;
4670
4671
0
  if (BestCase) {
4672
0
    if (RD->calculateInheritanceModel() == ExplicitModel)
4673
0
      return false;
4674
0
  } else {
4675
0
    if (RD->calculateInheritanceModel() <= ExplicitModel)
4676
0
      return false;
4677
0
  }
4678
4679
0
  Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
4680
0
      << 0 /*definition*/;
4681
0
  Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
4682
0
  return true;
4683
0
}
4684
4685
/// parseModeAttrArg - Parses attribute mode string and returns parsed type
4686
/// attribute.
4687
static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
4688
                             bool &IntegerMode, bool &ComplexMode,
4689
0
                             FloatModeKind &ExplicitType) {
4690
0
  IntegerMode = true;
4691
0
  ComplexMode = false;
4692
0
  ExplicitType = FloatModeKind::NoFloat;
4693
0
  switch (Str.size()) {
4694
0
  case 2:
4695
0
    switch (Str[0]) {
4696
0
    case 'Q':
4697
0
      DestWidth = 8;
4698
0
      break;
4699
0
    case 'H':
4700
0
      DestWidth = 16;
4701
0
      break;
4702
0
    case 'S':
4703
0
      DestWidth = 32;
4704
0
      break;
4705
0
    case 'D':
4706
0
      DestWidth = 64;
4707
0
      break;
4708
0
    case 'X':
4709
0
      DestWidth = 96;
4710
0
      break;
4711
0
    case 'K': // KFmode - IEEE quad precision (__float128)
4712
0
      ExplicitType = FloatModeKind::Float128;
4713
0
      DestWidth = Str[1] == 'I' ? 0 : 128;
4714
0
      break;
4715
0
    case 'T':
4716
0
      ExplicitType = FloatModeKind::LongDouble;
4717
0
      DestWidth = 128;
4718
0
      break;
4719
0
    case 'I':
4720
0
      ExplicitType = FloatModeKind::Ibm128;
4721
0
      DestWidth = Str[1] == 'I' ? 0 : 128;
4722
0
      break;
4723
0
    }
4724
0
    if (Str[1] == 'F') {
4725
0
      IntegerMode = false;
4726
0
    } else if (Str[1] == 'C') {
4727
0
      IntegerMode = false;
4728
0
      ComplexMode = true;
4729
0
    } else if (Str[1] != 'I') {
4730
0
      DestWidth = 0;
4731
0
    }
4732
0
    break;
4733
0
  case 4:
4734
    // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4735
    // pointer on PIC16 and other embedded platforms.
4736
0
    if (Str == "word")
4737
0
      DestWidth = S.Context.getTargetInfo().getRegisterWidth();
4738
0
    else if (Str == "byte")
4739
0
      DestWidth = S.Context.getTargetInfo().getCharWidth();
4740
0
    break;
4741
0
  case 7:
4742
0
    if (Str == "pointer")
4743
0
      DestWidth = S.Context.getTargetInfo().getPointerWidth(LangAS::Default);
4744
0
    break;
4745
0
  case 11:
4746
0
    if (Str == "unwind_word")
4747
0
      DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4748
0
    break;
4749
0
  }
4750
0
}
4751
4752
/// handleModeAttr - This attribute modifies the width of a decl with primitive
4753
/// type.
4754
///
4755
/// Despite what would be logical, the mode attribute is a decl attribute, not a
4756
/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4757
/// HImode, not an intermediate pointer.
4758
0
static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4759
  // This attribute isn't documented, but glibc uses it.  It changes
4760
  // the width of an int or unsigned int to the specified size.
4761
0
  if (!AL.isArgIdent(0)) {
4762
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4763
0
        << AL << AANT_ArgumentIdentifier;
4764
0
    return;
4765
0
  }
4766
4767
0
  IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
4768
4769
0
  S.AddModeAttr(D, AL, Name);
4770
0
}
4771
4772
void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
4773
0
                       IdentifierInfo *Name, bool InInstantiation) {
4774
0
  StringRef Str = Name->getName();
4775
0
  normalizeName(Str);
4776
0
  SourceLocation AttrLoc = CI.getLoc();
4777
4778
0
  unsigned DestWidth = 0;
4779
0
  bool IntegerMode = true;
4780
0
  bool ComplexMode = false;
4781
0
  FloatModeKind ExplicitType = FloatModeKind::NoFloat;
4782
0
  llvm::APInt VectorSize(64, 0);
4783
0
  if (Str.size() >= 4 && Str[0] == 'V') {
4784
    // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4785
0
    size_t StrSize = Str.size();
4786
0
    size_t VectorStringLength = 0;
4787
0
    while ((VectorStringLength + 1) < StrSize &&
4788
0
           isdigit(Str[VectorStringLength + 1]))
4789
0
      ++VectorStringLength;
4790
0
    if (VectorStringLength &&
4791
0
        !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4792
0
        VectorSize.isPowerOf2()) {
4793
0
      parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4794
0
                       IntegerMode, ComplexMode, ExplicitType);
4795
      // Avoid duplicate warning from template instantiation.
4796
0
      if (!InInstantiation)
4797
0
        Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4798
0
    } else {
4799
0
      VectorSize = 0;
4800
0
    }
4801
0
  }
4802
4803
0
  if (!VectorSize)
4804
0
    parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode,
4805
0
                     ExplicitType);
4806
4807
  // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4808
  // and friends, at least with glibc.
4809
  // FIXME: Make sure floating-point mappings are accurate
4810
  // FIXME: Support XF and TF types
4811
0
  if (!DestWidth) {
4812
0
    Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4813
0
    return;
4814
0
  }
4815
4816
0
  QualType OldTy;
4817
0
  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4818
0
    OldTy = TD->getUnderlyingType();
4819
0
  else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4820
    // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4821
    // Try to get type from enum declaration, default to int.
4822
0
    OldTy = ED->getIntegerType();
4823
0
    if (OldTy.isNull())
4824
0
      OldTy = Context.IntTy;
4825
0
  } else
4826
0
    OldTy = cast<ValueDecl>(D)->getType();
4827
4828
0
  if (OldTy->isDependentType()) {
4829
0
    D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4830
0
    return;
4831
0
  }
4832
4833
  // Base type can also be a vector type (see PR17453).
4834
  // Distinguish between base type and base element type.
4835
0
  QualType OldElemTy = OldTy;
4836
0
  if (const auto *VT = OldTy->getAs<VectorType>())
4837
0
    OldElemTy = VT->getElementType();
4838
4839
  // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4840
  // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4841
  // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4842
0
  if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
4843
0
      VectorSize.getBoolValue()) {
4844
0
    Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
4845
0
    return;
4846
0
  }
4847
0
  bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
4848
0
                                !OldElemTy->isBitIntType()) ||
4849
0
                               OldElemTy->getAs<EnumType>();
4850
4851
0
  if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4852
0
      !IntegralOrAnyEnumType)
4853
0
    Diag(AttrLoc, diag::err_mode_not_primitive);
4854
0
  else if (IntegerMode) {
4855
0
    if (!IntegralOrAnyEnumType)
4856
0
      Diag(AttrLoc, diag::err_mode_wrong_type);
4857
0
  } else if (ComplexMode) {
4858
0
    if (!OldElemTy->isComplexType())
4859
0
      Diag(AttrLoc, diag::err_mode_wrong_type);
4860
0
  } else {
4861
0
    if (!OldElemTy->isFloatingType())
4862
0
      Diag(AttrLoc, diag::err_mode_wrong_type);
4863
0
  }
4864
4865
0
  QualType NewElemTy;
4866
4867
0
  if (IntegerMode)
4868
0
    NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4869
0
                                              OldElemTy->isSignedIntegerType());
4870
0
  else
4871
0
    NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitType);
4872
4873
0
  if (NewElemTy.isNull()) {
4874
0
    Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4875
0
    return;
4876
0
  }
4877
4878
0
  if (ComplexMode) {
4879
0
    NewElemTy = Context.getComplexType(NewElemTy);
4880
0
  }
4881
4882
0
  QualType NewTy = NewElemTy;
4883
0
  if (VectorSize.getBoolValue()) {
4884
0
    NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4885
0
                                  VectorKind::Generic);
4886
0
  } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4887
    // Complex machine mode does not support base vector types.
4888
0
    if (ComplexMode) {
4889
0
      Diag(AttrLoc, diag::err_complex_mode_vector_type);
4890
0
      return;
4891
0
    }
4892
0
    unsigned NumElements = Context.getTypeSize(OldElemTy) *
4893
0
                           OldVT->getNumElements() /
4894
0
                           Context.getTypeSize(NewElemTy);
4895
0
    NewTy =
4896
0
        Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4897
0
  }
4898
4899
0
  if (NewTy.isNull()) {
4900
0
    Diag(AttrLoc, diag::err_mode_wrong_type);
4901
0
    return;
4902
0
  }
4903
4904
  // Install the new type.
4905
0
  if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4906
0
    TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4907
0
  else if (auto *ED = dyn_cast<EnumDecl>(D))
4908
0
    ED->setIntegerType(NewTy);
4909
0
  else
4910
0
    cast<ValueDecl>(D)->setType(NewTy);
4911
4912
0
  D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4913
0
}
4914
4915
0
static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4916
0
  D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4917
0
}
4918
4919
AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
4920
                                              const AttributeCommonInfo &CI,
4921
0
                                              const IdentifierInfo *Ident) {
4922
0
  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4923
0
    Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4924
0
    Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4925
0
    return nullptr;
4926
0
  }
4927
4928
0
  if (D->hasAttr<AlwaysInlineAttr>())
4929
0
    return nullptr;
4930
4931
0
  return ::new (Context) AlwaysInlineAttr(Context, CI);
4932
0
}
4933
4934
InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4935
0
                                                    const ParsedAttr &AL) {
4936
0
  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4937
    // Attribute applies to Var but not any subclass of it (like ParmVar,
4938
    // ImplicitParm or VarTemplateSpecialization).
4939
0
    if (VD->getKind() != Decl::Var) {
4940
0
      Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4941
0
          << AL << AL.isRegularKeywordAttribute()
4942
0
          << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4943
0
                                      : ExpectedVariableOrFunction);
4944
0
      return nullptr;
4945
0
    }
4946
    // Attribute does not apply to non-static local variables.
4947
0
    if (VD->hasLocalStorage()) {
4948
0
      Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4949
0
      return nullptr;
4950
0
    }
4951
0
  }
4952
4953
0
  return ::new (Context) InternalLinkageAttr(Context, AL);
4954
0
}
4955
InternalLinkageAttr *
4956
0
Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4957
0
  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4958
    // Attribute applies to Var but not any subclass of it (like ParmVar,
4959
    // ImplicitParm or VarTemplateSpecialization).
4960
0
    if (VD->getKind() != Decl::Var) {
4961
0
      Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4962
0
          << &AL << AL.isRegularKeywordAttribute()
4963
0
          << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4964
0
                                      : ExpectedVariableOrFunction);
4965
0
      return nullptr;
4966
0
    }
4967
    // Attribute does not apply to non-static local variables.
4968
0
    if (VD->hasLocalStorage()) {
4969
0
      Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4970
0
      return nullptr;
4971
0
    }
4972
0
  }
4973
4974
0
  return ::new (Context) InternalLinkageAttr(Context, AL);
4975
0
}
4976
4977
0
MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
4978
0
  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4979
0
    Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4980
0
    Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4981
0
    return nullptr;
4982
0
  }
4983
4984
0
  if (D->hasAttr<MinSizeAttr>())
4985
0
    return nullptr;
4986
4987
0
  return ::new (Context) MinSizeAttr(Context, CI);
4988
0
}
4989
4990
SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
4991
0
                                        StringRef Name) {
4992
0
  if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) {
4993
0
    if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
4994
0
      Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
4995
0
          << PrevSNA << &SNA
4996
0
          << (PrevSNA->isRegularKeywordAttribute() ||
4997
0
              SNA.isRegularKeywordAttribute());
4998
0
      Diag(SNA.getLoc(), diag::note_conflicting_attribute);
4999
0
    }
5000
5001
0
    D->dropAttr<SwiftNameAttr>();
5002
0
  }
5003
0
  return ::new (Context) SwiftNameAttr(Context, SNA, Name);
5004
0
}
5005
5006
OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
5007
0
                                              const AttributeCommonInfo &CI) {
5008
0
  if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
5009
0
    Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
5010
0
    Diag(CI.getLoc(), diag::note_conflicting_attribute);
5011
0
    D->dropAttr<AlwaysInlineAttr>();
5012
0
  }
5013
0
  if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
5014
0
    Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
5015
0
    Diag(CI.getLoc(), diag::note_conflicting_attribute);
5016
0
    D->dropAttr<MinSizeAttr>();
5017
0
  }
5018
5019
0
  if (D->hasAttr<OptimizeNoneAttr>())
5020
0
    return nullptr;
5021
5022
0
  return ::new (Context) OptimizeNoneAttr(Context, CI);
5023
0
}
5024
5025
0
static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5026
0
  if (AlwaysInlineAttr *Inline =
5027
0
          S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
5028
0
    D->addAttr(Inline);
5029
0
}
5030
5031
0
static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5032
0
  if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
5033
0
    D->addAttr(MinSize);
5034
0
}
5035
5036
0
static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5037
0
  if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
5038
0
    D->addAttr(Optnone);
5039
0
}
5040
5041
0
static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5042
0
  const auto *VD = cast<VarDecl>(D);
5043
0
  if (VD->hasLocalStorage()) {
5044
0
    S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
5045
0
    return;
5046
0
  }
5047
  // constexpr variable may already get an implicit constant attr, which should
5048
  // be replaced by the explicit constant attr.
5049
0
  if (auto *A = D->getAttr<CUDAConstantAttr>()) {
5050
0
    if (!A->isImplicit())
5051
0
      return;
5052
0
    D->dropAttr<CUDAConstantAttr>();
5053
0
  }
5054
0
  D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
5055
0
}
5056
5057
0
static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5058
0
  const auto *VD = cast<VarDecl>(D);
5059
  // extern __shared__ is only allowed on arrays with no length (e.g.
5060
  // "int x[]").
5061
0
  if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
5062
0
      !isa<IncompleteArrayType>(VD->getType())) {
5063
0
    S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
5064
0
    return;
5065
0
  }
5066
0
  if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
5067
0
      S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
5068
0
          << S.CurrentCUDATarget())
5069
0
    return;
5070
0
  D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
5071
0
}
5072
5073
0
static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5074
0
  const auto *FD = cast<FunctionDecl>(D);
5075
0
  if (!FD->getReturnType()->isVoidType() &&
5076
0
      !FD->getReturnType()->getAs<AutoType>() &&
5077
0
      !FD->getReturnType()->isInstantiationDependentType()) {
5078
0
    SourceRange RTRange = FD->getReturnTypeSourceRange();
5079
0
    S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
5080
0
        << FD->getType()
5081
0
        << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
5082
0
                              : FixItHint());
5083
0
    return;
5084
0
  }
5085
0
  if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
5086
0
    if (Method->isInstance()) {
5087
0
      S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
5088
0
          << Method;
5089
0
      return;
5090
0
    }
5091
0
    S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
5092
0
  }
5093
  // Only warn for "inline" when compiling for host, to cut down on noise.
5094
0
  if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
5095
0
    S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
5096
5097
0
  if (AL.getKind() == ParsedAttr::AT_NVPTXKernel)
5098
0
    D->addAttr(::new (S.Context) NVPTXKernelAttr(S.Context, AL));
5099
0
  else
5100
0
    D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
5101
  // In host compilation the kernel is emitted as a stub function, which is
5102
  // a helper function for launching the kernel. The instructions in the helper
5103
  // function has nothing to do with the source code of the kernel. Do not emit
5104
  // debug info for the stub function to avoid confusing the debugger.
5105
0
  if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice)
5106
0
    D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
5107
0
}
5108
5109
0
static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5110
0
  if (const auto *VD = dyn_cast<VarDecl>(D)) {
5111
0
    if (VD->hasLocalStorage()) {
5112
0
      S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
5113
0
      return;
5114
0
    }
5115
0
  }
5116
5117
0
  if (auto *A = D->getAttr<CUDADeviceAttr>()) {
5118
0
    if (!A->isImplicit())
5119
0
      return;
5120
0
    D->dropAttr<CUDADeviceAttr>();
5121
0
  }
5122
0
  D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL));
5123
0
}
5124
5125
0
static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5126
0
  if (const auto *VD = dyn_cast<VarDecl>(D)) {
5127
0
    if (VD->hasLocalStorage()) {
5128
0
      S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
5129
0
      return;
5130
0
    }
5131
0
  }
5132
0
  if (!D->hasAttr<HIPManagedAttr>())
5133
0
    D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL));
5134
0
  if (!D->hasAttr<CUDADeviceAttr>())
5135
0
    D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context));
5136
0
}
5137
5138
0
static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5139
0
  const auto *Fn = cast<FunctionDecl>(D);
5140
0
  if (!Fn->isInlineSpecified()) {
5141
0
    S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
5142
0
    return;
5143
0
  }
5144
5145
0
  if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
5146
0
    S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
5147
5148
0
  D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
5149
0
}
5150
5151
0
static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5152
0
  if (hasDeclarator(D)) return;
5153
5154
  // Diagnostic is emitted elsewhere: here we store the (valid) AL
5155
  // in the Decl node for syntactic reasoning, e.g., pretty-printing.
5156
0
  CallingConv CC;
5157
0
  if (S.CheckCallingConvAttr(AL, CC, /*FD*/ nullptr,
5158
0
                             S.IdentifyCUDATarget(dyn_cast<FunctionDecl>(D))))
5159
0
    return;
5160
5161
0
  if (!isa<ObjCMethodDecl>(D)) {
5162
0
    S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5163
0
        << AL << AL.isRegularKeywordAttribute() << ExpectedFunctionOrMethod;
5164
0
    return;
5165
0
  }
5166
5167
0
  switch (AL.getKind()) {
5168
0
  case ParsedAttr::AT_FastCall:
5169
0
    D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
5170
0
    return;
5171
0
  case ParsedAttr::AT_StdCall:
5172
0
    D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
5173
0
    return;
5174
0
  case ParsedAttr::AT_ThisCall:
5175
0
    D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
5176
0
    return;
5177
0
  case ParsedAttr::AT_CDecl:
5178
0
    D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
5179
0
    return;
5180
0
  case ParsedAttr::AT_Pascal:
5181
0
    D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
5182
0
    return;
5183
0
  case ParsedAttr::AT_SwiftCall:
5184
0
    D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
5185
0
    return;
5186
0
  case ParsedAttr::AT_SwiftAsyncCall:
5187
0
    D->addAttr(::new (S.Context) SwiftAsyncCallAttr(S.Context, AL));
5188
0
    return;
5189
0
  case ParsedAttr::AT_VectorCall:
5190
0
    D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
5191
0
    return;
5192
0
  case ParsedAttr::AT_MSABI:
5193
0
    D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
5194
0
    return;
5195
0
  case ParsedAttr::AT_SysVABI:
5196
0
    D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
5197
0
    return;
5198
0
  case ParsedAttr::AT_RegCall:
5199
0
    D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
5200
0
    return;
5201
0
  case ParsedAttr::AT_Pcs: {
5202
0
    PcsAttr::PCSType PCS;
5203
0
    switch (CC) {
5204
0
    case CC_AAPCS:
5205
0
      PCS = PcsAttr::AAPCS;
5206
0
      break;
5207
0
    case CC_AAPCS_VFP:
5208
0
      PCS = PcsAttr::AAPCS_VFP;
5209
0
      break;
5210
0
    default:
5211
0
      llvm_unreachable("unexpected calling convention in pcs attribute");
5212
0
    }
5213
5214
0
    D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
5215
0
    return;
5216
0
  }
5217
0
  case ParsedAttr::AT_AArch64VectorPcs:
5218
0
    D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
5219
0
    return;
5220
0
  case ParsedAttr::AT_AArch64SVEPcs:
5221
0
    D->addAttr(::new (S.Context) AArch64SVEPcsAttr(S.Context, AL));
5222
0
    return;
5223
0
  case ParsedAttr::AT_AMDGPUKernelCall:
5224
0
    D->addAttr(::new (S.Context) AMDGPUKernelCallAttr(S.Context, AL));
5225
0
    return;
5226
0
  case ParsedAttr::AT_IntelOclBicc:
5227
0
    D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
5228
0
    return;
5229
0
  case ParsedAttr::AT_PreserveMost:
5230
0
    D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
5231
0
    return;
5232
0
  case ParsedAttr::AT_PreserveAll:
5233
0
    D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
5234
0
    return;
5235
0
  case ParsedAttr::AT_M68kRTD:
5236
0
    D->addAttr(::new (S.Context) M68kRTDAttr(S.Context, AL));
5237
0
    return;
5238
0
  default:
5239
0
    llvm_unreachable("unexpected attribute kind");
5240
0
  }
5241
0
}
5242
5243
0
static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5244
0
  if (AL.getAttributeSpellingListIndex() == SuppressAttr::CXX11_gsl_suppress) {
5245
    // Suppression attribute with GSL spelling requires at least 1 argument.
5246
0
    if (!AL.checkAtLeastNumArgs(S, 1))
5247
0
      return;
5248
0
  } else if (!isa<VarDecl>(D)) {
5249
    // Analyzer suppression applies only to variables and statements.
5250
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type_str)
5251
0
        << AL << 0 << "variables and statements";
5252
0
    return;
5253
0
  }
5254
5255
0
  std::vector<StringRef> DiagnosticIdentifiers;
5256
0
  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5257
0
    StringRef RuleName;
5258
5259
0
    if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
5260
0
      return;
5261
5262
0
    DiagnosticIdentifiers.push_back(RuleName);
5263
0
  }
5264
0
  D->addAttr(::new (S.Context)
5265
0
                 SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
5266
0
                              DiagnosticIdentifiers.size()));
5267
0
}
5268
5269
0
static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5270
0
  TypeSourceInfo *DerefTypeLoc = nullptr;
5271
0
  QualType ParmType;
5272
0
  if (AL.hasParsedType()) {
5273
0
    ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc);
5274
5275
0
    unsigned SelectIdx = ~0U;
5276
0
    if (ParmType->isReferenceType())
5277
0
      SelectIdx = 0;
5278
0
    else if (ParmType->isArrayType())
5279
0
      SelectIdx = 1;
5280
5281
0
    if (SelectIdx != ~0U) {
5282
0
      S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
5283
0
          << SelectIdx << AL;
5284
0
      return;
5285
0
    }
5286
0
  }
5287
5288
  // To check if earlier decl attributes do not conflict the newly parsed ones
5289
  // we always add (and check) the attribute to the canonical decl. We need
5290
  // to repeat the check for attribute mutual exclusion because we're attaching
5291
  // all of the attributes to the canonical declaration rather than the current
5292
  // declaration.
5293
0
  D = D->getCanonicalDecl();
5294
0
  if (AL.getKind() == ParsedAttr::AT_Owner) {
5295
0
    if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
5296
0
      return;
5297
0
    if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
5298
0
      const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
5299
0
                                          ? OAttr->getDerefType().getTypePtr()
5300
0
                                          : nullptr;
5301
0
      if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
5302
0
        S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
5303
0
            << AL << OAttr
5304
0
            << (AL.isRegularKeywordAttribute() ||
5305
0
                OAttr->isRegularKeywordAttribute());
5306
0
        S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
5307
0
      }
5308
0
      return;
5309
0
    }
5310
0
    for (Decl *Redecl : D->redecls()) {
5311
0
      Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
5312
0
    }
5313
0
  } else {
5314
0
    if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
5315
0
      return;
5316
0
    if (const auto *PAttr = D->getAttr<PointerAttr>()) {
5317
0
      const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
5318
0
                                          ? PAttr->getDerefType().getTypePtr()
5319
0
                                          : nullptr;
5320
0
      if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
5321
0
        S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
5322
0
            << AL << PAttr
5323
0
            << (AL.isRegularKeywordAttribute() ||
5324
0
                PAttr->isRegularKeywordAttribute());
5325
0
        S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
5326
0
      }
5327
0
      return;
5328
0
    }
5329
0
    for (Decl *Redecl : D->redecls()) {
5330
0
      Redecl->addAttr(::new (S.Context)
5331
0
                          PointerAttr(S.Context, AL, DerefTypeLoc));
5332
0
    }
5333
0
  }
5334
0
}
5335
5336
0
static void handleRandomizeLayoutAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5337
0
  if (checkAttrMutualExclusion<NoRandomizeLayoutAttr>(S, D, AL))
5338
0
    return;
5339
0
  if (!D->hasAttr<RandomizeLayoutAttr>())
5340
0
    D->addAttr(::new (S.Context) RandomizeLayoutAttr(S.Context, AL));
5341
0
}
5342
5343
static void handleNoRandomizeLayoutAttr(Sema &S, Decl *D,
5344
0
                                        const ParsedAttr &AL) {
5345
0
  if (checkAttrMutualExclusion<RandomizeLayoutAttr>(S, D, AL))
5346
0
    return;
5347
0
  if (!D->hasAttr<NoRandomizeLayoutAttr>())
5348
0
    D->addAttr(::new (S.Context) NoRandomizeLayoutAttr(S.Context, AL));
5349
0
}
5350
5351
bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
5352
                                const FunctionDecl *FD,
5353
0
                                CUDAFunctionTarget CFT) {
5354
0
  if (Attrs.isInvalid())
5355
0
    return true;
5356
5357
0
  if (Attrs.hasProcessingCache()) {
5358
0
    CC = (CallingConv) Attrs.getProcessingCache();
5359
0
    return false;
5360
0
  }
5361
5362
0
  unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
5363
0
  if (!Attrs.checkExactlyNumArgs(*this, ReqArgs)) {
5364
0
    Attrs.setInvalid();
5365
0
    return true;
5366
0
  }
5367
5368
  // TODO: diagnose uses of these conventions on the wrong target.
5369
0
  switch (Attrs.getKind()) {
5370
0
  case ParsedAttr::AT_CDecl:
5371
0
    CC = CC_C;
5372
0
    break;
5373
0
  case ParsedAttr::AT_FastCall:
5374
0
    CC = CC_X86FastCall;
5375
0
    break;
5376
0
  case ParsedAttr::AT_StdCall:
5377
0
    CC = CC_X86StdCall;
5378
0
    break;
5379
0
  case ParsedAttr::AT_ThisCall:
5380
0
    CC = CC_X86ThisCall;
5381
0
    break;
5382
0
  case ParsedAttr::AT_Pascal:
5383
0
    CC = CC_X86Pascal;
5384
0
    break;
5385
0
  case ParsedAttr::AT_SwiftCall:
5386
0
    CC = CC_Swift;
5387
0
    break;
5388
0
  case ParsedAttr::AT_SwiftAsyncCall:
5389
0
    CC = CC_SwiftAsync;
5390
0
    break;
5391
0
  case ParsedAttr::AT_VectorCall:
5392
0
    CC = CC_X86VectorCall;
5393
0
    break;
5394
0
  case ParsedAttr::AT_AArch64VectorPcs:
5395
0
    CC = CC_AArch64VectorCall;
5396
0
    break;
5397
0
  case ParsedAttr::AT_AArch64SVEPcs:
5398
0
    CC = CC_AArch64SVEPCS;
5399
0
    break;
5400
0
  case ParsedAttr::AT_AMDGPUKernelCall:
5401
0
    CC = CC_AMDGPUKernelCall;
5402
0
    break;
5403
0
  case ParsedAttr::AT_RegCall:
5404
0
    CC = CC_X86RegCall;
5405
0
    break;
5406
0
  case ParsedAttr::AT_MSABI:
5407
0
    CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
5408
0
                                                             CC_Win64;
5409
0
    break;
5410
0
  case ParsedAttr::AT_SysVABI:
5411
0
    CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
5412
0
                                                             CC_C;
5413
0
    break;
5414
0
  case ParsedAttr::AT_Pcs: {
5415
0
    StringRef StrRef;
5416
0
    if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
5417
0
      Attrs.setInvalid();
5418
0
      return true;
5419
0
    }
5420
0
    if (StrRef == "aapcs") {
5421
0
      CC = CC_AAPCS;
5422
0
      break;
5423
0
    } else if (StrRef == "aapcs-vfp") {
5424
0
      CC = CC_AAPCS_VFP;
5425
0
      break;
5426
0
    }
5427
5428
0
    Attrs.setInvalid();
5429
0
    Diag(Attrs.getLoc(), diag::err_invalid_pcs);
5430
0
    return true;
5431
0
  }
5432
0
  case ParsedAttr::AT_IntelOclBicc:
5433
0
    CC = CC_IntelOclBicc;
5434
0
    break;
5435
0
  case ParsedAttr::AT_PreserveMost:
5436
0
    CC = CC_PreserveMost;
5437
0
    break;
5438
0
  case ParsedAttr::AT_PreserveAll:
5439
0
    CC = CC_PreserveAll;
5440
0
    break;
5441
0
  case ParsedAttr::AT_M68kRTD:
5442
0
    CC = CC_M68kRTD;
5443
0
    break;
5444
0
  default: llvm_unreachable("unexpected attribute kind");
5445
0
  }
5446
5447
0
  TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK;
5448
0
  const TargetInfo &TI = Context.getTargetInfo();
5449
  // CUDA functions may have host and/or device attributes which indicate
5450
  // their targeted execution environment, therefore the calling convention
5451
  // of functions in CUDA should be checked against the target deduced based
5452
  // on their host/device attributes.
5453
0
  if (LangOpts.CUDA) {
5454
0
    auto *Aux = Context.getAuxTargetInfo();
5455
0
    assert(FD || CFT != CFT_InvalidTarget);
5456
0
    auto CudaTarget = FD ? IdentifyCUDATarget(FD) : CFT;
5457
0
    bool CheckHost = false, CheckDevice = false;
5458
0
    switch (CudaTarget) {
5459
0
    case CFT_HostDevice:
5460
0
      CheckHost = true;
5461
0
      CheckDevice = true;
5462
0
      break;
5463
0
    case CFT_Host:
5464
0
      CheckHost = true;
5465
0
      break;
5466
0
    case CFT_Device:
5467
0
    case CFT_Global:
5468
0
      CheckDevice = true;
5469
0
      break;
5470
0
    case CFT_InvalidTarget:
5471
0
      llvm_unreachable("unexpected cuda target");
5472
0
    }
5473
0
    auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
5474
0
    auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
5475
0
    if (CheckHost && HostTI)
5476
0
      A = HostTI->checkCallingConvention(CC);
5477
0
    if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
5478
0
      A = DeviceTI->checkCallingConvention(CC);
5479
0
  } else {
5480
0
    A = TI.checkCallingConvention(CC);
5481
0
  }
5482
5483
0
  switch (A) {
5484
0
  case TargetInfo::CCCR_OK:
5485
0
    break;
5486
5487
0
  case TargetInfo::CCCR_Ignore:
5488
    // Treat an ignored convention as if it was an explicit C calling convention
5489
    // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
5490
    // that command line flags that change the default convention to
5491
    // __vectorcall don't affect declarations marked __stdcall.
5492
0
    CC = CC_C;
5493
0
    break;
5494
5495
0
  case TargetInfo::CCCR_Error:
5496
0
    Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
5497
0
        << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
5498
0
    break;
5499
5500
0
  case TargetInfo::CCCR_Warning: {
5501
0
    Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
5502
0
        << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
5503
5504
    // This convention is not valid for the target. Use the default function or
5505
    // method calling convention.
5506
0
    bool IsCXXMethod = false, IsVariadic = false;
5507
0
    if (FD) {
5508
0
      IsCXXMethod = FD->isCXXInstanceMember();
5509
0
      IsVariadic = FD->isVariadic();
5510
0
    }
5511
0
    CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
5512
0
    break;
5513
0
  }
5514
0
  }
5515
5516
0
  Attrs.setProcessingCache((unsigned) CC);
5517
0
  return false;
5518
0
}
5519
5520
/// Pointer-like types in the default address space.
5521
0
static bool isValidSwiftContextType(QualType Ty) {
5522
0
  if (!Ty->hasPointerRepresentation())
5523
0
    return Ty->isDependentType();
5524
0
  return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
5525
0
}
5526
5527
/// Pointers and references in the default address space.
5528
0
static bool isValidSwiftIndirectResultType(QualType Ty) {
5529
0
  if (const auto *PtrType = Ty->getAs<PointerType>()) {
5530
0
    Ty = PtrType->getPointeeType();
5531
0
  } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
5532
0
    Ty = RefType->getPointeeType();
5533
0
  } else {
5534
0
    return Ty->isDependentType();
5535
0
  }
5536
0
  return Ty.getAddressSpace() == LangAS::Default;
5537
0
}
5538
5539
/// Pointers and references to pointers in the default address space.
5540
0
static bool isValidSwiftErrorResultType(QualType Ty) {
5541
0
  if (const auto *PtrType = Ty->getAs<PointerType>()) {
5542
0
    Ty = PtrType->getPointeeType();
5543
0
  } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
5544
0
    Ty = RefType->getPointeeType();
5545
0
  } else {
5546
0
    return Ty->isDependentType();
5547
0
  }
5548
0
  if (!Ty.getQualifiers().empty())
5549
0
    return false;
5550
0
  return isValidSwiftContextType(Ty);
5551
0
}
5552
5553
void Sema::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
5554
0
                               ParameterABI abi) {
5555
5556
0
  QualType type = cast<ParmVarDecl>(D)->getType();
5557
5558
0
  if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
5559
0
    if (existingAttr->getABI() != abi) {
5560
0
      Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
5561
0
          << getParameterABISpelling(abi) << existingAttr
5562
0
          << (CI.isRegularKeywordAttribute() ||
5563
0
              existingAttr->isRegularKeywordAttribute());
5564
0
      Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
5565
0
      return;
5566
0
    }
5567
0
  }
5568
5569
0
  switch (abi) {
5570
0
  case ParameterABI::Ordinary:
5571
0
    llvm_unreachable("explicit attribute for ordinary parameter ABI?");
5572
5573
0
  case ParameterABI::SwiftContext:
5574
0
    if (!isValidSwiftContextType(type)) {
5575
0
      Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5576
0
          << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
5577
0
    }
5578
0
    D->addAttr(::new (Context) SwiftContextAttr(Context, CI));
5579
0
    return;
5580
5581
0
  case ParameterABI::SwiftAsyncContext:
5582
0
    if (!isValidSwiftContextType(type)) {
5583
0
      Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5584
0
          << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
5585
0
    }
5586
0
    D->addAttr(::new (Context) SwiftAsyncContextAttr(Context, CI));
5587
0
    return;
5588
5589
0
  case ParameterABI::SwiftErrorResult:
5590
0
    if (!isValidSwiftErrorResultType(type)) {
5591
0
      Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5592
0
          << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type;
5593
0
    }
5594
0
    D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI));
5595
0
    return;
5596
5597
0
  case ParameterABI::SwiftIndirectResult:
5598
0
    if (!isValidSwiftIndirectResultType(type)) {
5599
0
      Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5600
0
          << getParameterABISpelling(abi) << /*pointer*/ 0 << type;
5601
0
    }
5602
0
    D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI));
5603
0
    return;
5604
0
  }
5605
0
  llvm_unreachable("bad parameter ABI attribute");
5606
0
}
5607
5608
/// Checks a regparm attribute, returning true if it is ill-formed and
5609
/// otherwise setting numParams to the appropriate value.
5610
0
bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
5611
0
  if (AL.isInvalid())
5612
0
    return true;
5613
5614
0
  if (!AL.checkExactlyNumArgs(*this, 1)) {
5615
0
    AL.setInvalid();
5616
0
    return true;
5617
0
  }
5618
5619
0
  uint32_t NP;
5620
0
  Expr *NumParamsExpr = AL.getArgAsExpr(0);
5621
0
  if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
5622
0
    AL.setInvalid();
5623
0
    return true;
5624
0
  }
5625
5626
0
  if (Context.getTargetInfo().getRegParmMax() == 0) {
5627
0
    Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
5628
0
      << NumParamsExpr->getSourceRange();
5629
0
    AL.setInvalid();
5630
0
    return true;
5631
0
  }
5632
5633
0
  numParams = NP;
5634
0
  if (numParams > Context.getTargetInfo().getRegParmMax()) {
5635
0
    Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
5636
0
      << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
5637
0
    AL.setInvalid();
5638
0
    return true;
5639
0
  }
5640
5641
0
  return false;
5642
0
}
5643
5644
// Helper to get CudaArch.
5645
0
static CudaArch getCudaArch(const TargetInfo &TI) {
5646
0
  if (!TI.getTriple().isNVPTX())
5647
0
    llvm_unreachable("getCudaArch is only valid for NVPTX triple");
5648
0
  auto &TO = TI.getTargetOpts();
5649
0
  return StringToCudaArch(TO.CPU);
5650
0
}
5651
5652
// Checks whether an argument of launch_bounds attribute is
5653
// acceptable, performs implicit conversion to Rvalue, and returns
5654
// non-nullptr Expr result on success. Otherwise, it returns nullptr
5655
// and may output an error.
5656
static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
5657
                                     const CUDALaunchBoundsAttr &AL,
5658
0
                                     const unsigned Idx) {
5659
0
  if (S.DiagnoseUnexpandedParameterPack(E))
5660
0
    return nullptr;
5661
5662
  // Accept template arguments for now as they depend on something else.
5663
  // We'll get to check them when they eventually get instantiated.
5664
0
  if (E->isValueDependent())
5665
0
    return E;
5666
5667
0
  std::optional<llvm::APSInt> I = llvm::APSInt(64);
5668
0
  if (!(I = E->getIntegerConstantExpr(S.Context))) {
5669
0
    S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
5670
0
        << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
5671
0
    return nullptr;
5672
0
  }
5673
  // Make sure we can fit it in 32 bits.
5674
0
  if (!I->isIntN(32)) {
5675
0
    S.Diag(E->getExprLoc(), diag::err_ice_too_large)
5676
0
        << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
5677
0
    return nullptr;
5678
0
  }
5679
0
  if (*I < 0)
5680
0
    S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
5681
0
        << &AL << Idx << E->getSourceRange();
5682
5683
  // We may need to perform implicit conversion of the argument.
5684
0
  InitializedEntity Entity = InitializedEntity::InitializeParameter(
5685
0
      S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
5686
0
  ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
5687
0
  assert(!ValArg.isInvalid() &&
5688
0
         "Unexpected PerformCopyInitialization() failure.");
5689
5690
0
  return ValArg.getAs<Expr>();
5691
0
}
5692
5693
CUDALaunchBoundsAttr *
5694
Sema::CreateLaunchBoundsAttr(const AttributeCommonInfo &CI, Expr *MaxThreads,
5695
0
                             Expr *MinBlocks, Expr *MaxBlocks) {
5696
0
  CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks, MaxBlocks);
5697
0
  MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
5698
0
  if (!MaxThreads)
5699
0
    return nullptr;
5700
5701
0
  if (MinBlocks) {
5702
0
    MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
5703
0
    if (!MinBlocks)
5704
0
      return nullptr;
5705
0
  }
5706
5707
0
  if (MaxBlocks) {
5708
    // '.maxclusterrank' ptx directive requires .target sm_90 or higher.
5709
0
    auto SM = getCudaArch(Context.getTargetInfo());
5710
0
    if (SM == CudaArch::UNKNOWN || SM < CudaArch::SM_90) {
5711
0
      Diag(MaxBlocks->getBeginLoc(), diag::warn_cuda_maxclusterrank_sm_90)
5712
0
          << CudaArchToString(SM) << CI << MaxBlocks->getSourceRange();
5713
      // Ignore it by setting MaxBlocks to null;
5714
0
      MaxBlocks = nullptr;
5715
0
    } else {
5716
0
      MaxBlocks = makeLaunchBoundsArgExpr(*this, MaxBlocks, TmpAttr, 2);
5717
0
      if (!MaxBlocks)
5718
0
        return nullptr;
5719
0
    }
5720
0
  }
5721
5722
0
  return ::new (Context)
5723
0
      CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks, MaxBlocks);
5724
0
}
5725
5726
void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5727
                               Expr *MaxThreads, Expr *MinBlocks,
5728
0
                               Expr *MaxBlocks) {
5729
0
  if (auto *Attr = CreateLaunchBoundsAttr(CI, MaxThreads, MinBlocks, MaxBlocks))
5730
0
    D->addAttr(Attr);
5731
0
}
5732
5733
0
static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5734
0
  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 3))
5735
0
    return;
5736
5737
0
  S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0),
5738
0
                        AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr,
5739
0
                        AL.getNumArgs() > 2 ? AL.getArgAsExpr(2) : nullptr);
5740
0
}
5741
5742
static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
5743
0
                                          const ParsedAttr &AL) {
5744
0
  if (!AL.isArgIdent(0)) {
5745
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5746
0
        << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
5747
0
    return;
5748
0
  }
5749
5750
0
  ParamIdx ArgumentIdx;
5751
0
  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
5752
0
                                           ArgumentIdx))
5753
0
    return;
5754
5755
0
  ParamIdx TypeTagIdx;
5756
0
  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
5757
0
                                           TypeTagIdx))
5758
0
    return;
5759
5760
0
  bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag";
5761
0
  if (IsPointer) {
5762
    // Ensure that buffer has a pointer type.
5763
0
    unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
5764
0
    if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
5765
0
        !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
5766
0
      S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
5767
0
  }
5768
5769
0
  D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
5770
0
      S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx,
5771
0
      IsPointer));
5772
0
}
5773
5774
static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
5775
0
                                         const ParsedAttr &AL) {
5776
0
  if (!AL.isArgIdent(0)) {
5777
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5778
0
        << AL << 1 << AANT_ArgumentIdentifier;
5779
0
    return;
5780
0
  }
5781
5782
0
  if (!AL.checkExactlyNumArgs(S, 1))
5783
0
    return;
5784
5785
0
  if (!isa<VarDecl>(D)) {
5786
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
5787
0
        << AL << AL.isRegularKeywordAttribute() << ExpectedVariable;
5788
0
    return;
5789
0
  }
5790
5791
0
  IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
5792
0
  TypeSourceInfo *MatchingCTypeLoc = nullptr;
5793
0
  S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
5794
0
  assert(MatchingCTypeLoc && "no type source info for attribute argument");
5795
5796
0
  D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(
5797
0
      S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(),
5798
0
      AL.getMustBeNull()));
5799
0
}
5800
5801
0
static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5802
0
  ParamIdx ArgCount;
5803
5804
0
  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
5805
0
                                           ArgCount,
5806
0
                                           true /* CanIndexImplicitThis */))
5807
0
    return;
5808
5809
  // ArgCount isn't a parameter index [0;n), it's a count [1;n]
5810
0
  D->addAttr(::new (S.Context)
5811
0
                 XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
5812
0
}
5813
5814
static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D,
5815
0
                                             const ParsedAttr &AL) {
5816
0
  uint32_t Count = 0, Offset = 0;
5817
0
  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Count, 0, true))
5818
0
    return;
5819
0
  if (AL.getNumArgs() == 2) {
5820
0
    Expr *Arg = AL.getArgAsExpr(1);
5821
0
    if (!checkUInt32Argument(S, AL, Arg, Offset, 1, true))
5822
0
      return;
5823
0
    if (Count < Offset) {
5824
0
      S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range)
5825
0
          << &AL << 0 << Count << Arg->getBeginLoc();
5826
0
      return;
5827
0
    }
5828
0
  }
5829
0
  D->addAttr(::new (S.Context)
5830
0
                 PatchableFunctionEntryAttr(S.Context, AL, Count, Offset));
5831
0
}
5832
5833
namespace {
5834
struct IntrinToName {
5835
  uint32_t Id;
5836
  int32_t FullName;
5837
  int32_t ShortName;
5838
};
5839
} // unnamed namespace
5840
5841
static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName,
5842
                                 ArrayRef<IntrinToName> Map,
5843
0
                                 const char *IntrinNames) {
5844
0
  AliasName.consume_front("__arm_");
5845
0
  const IntrinToName *It =
5846
0
      llvm::lower_bound(Map, BuiltinID, [](const IntrinToName &L, unsigned Id) {
5847
0
        return L.Id < Id;
5848
0
      });
5849
0
  if (It == Map.end() || It->Id != BuiltinID)
5850
0
    return false;
5851
0
  StringRef FullName(&IntrinNames[It->FullName]);
5852
0
  if (AliasName == FullName)
5853
0
    return true;
5854
0
  if (It->ShortName == -1)
5855
0
    return false;
5856
0
  StringRef ShortName(&IntrinNames[It->ShortName]);
5857
0
  return AliasName == ShortName;
5858
0
}
5859
5860
0
static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) {
5861
0
#include "clang/Basic/arm_mve_builtin_aliases.inc"
5862
  // The included file defines:
5863
  // - ArrayRef<IntrinToName> Map
5864
  // - const char IntrinNames[]
5865
0
  return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5866
0
}
5867
5868
0
static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) {
5869
0
#include "clang/Basic/arm_cde_builtin_aliases.inc"
5870
0
  return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5871
0
}
5872
5873
static bool ArmSveAliasValid(ASTContext &Context, unsigned BuiltinID,
5874
0
                             StringRef AliasName) {
5875
0
  if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
5876
0
    BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(BuiltinID);
5877
0
  return BuiltinID >= AArch64::FirstSVEBuiltin &&
5878
0
         BuiltinID <= AArch64::LastSVEBuiltin;
5879
0
}
5880
5881
static bool ArmSmeAliasValid(ASTContext &Context, unsigned BuiltinID,
5882
0
                             StringRef AliasName) {
5883
0
  if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
5884
0
    BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(BuiltinID);
5885
0
  return BuiltinID >= AArch64::FirstSMEBuiltin &&
5886
0
         BuiltinID <= AArch64::LastSMEBuiltin;
5887
0
}
5888
5889
0
static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5890
0
  if (!AL.isArgIdent(0)) {
5891
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5892
0
        << AL << 1 << AANT_ArgumentIdentifier;
5893
0
    return;
5894
0
  }
5895
5896
0
  IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
5897
0
  unsigned BuiltinID = Ident->getBuiltinID();
5898
0
  StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
5899
5900
0
  bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5901
0
  if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName) &&
5902
0
       !ArmSmeAliasValid(S.Context, BuiltinID, AliasName)) ||
5903
0
      (!IsAArch64 && !ArmMveAliasValid(BuiltinID, AliasName) &&
5904
0
       !ArmCdeAliasValid(BuiltinID, AliasName))) {
5905
0
    S.Diag(AL.getLoc(), diag::err_attribute_arm_builtin_alias);
5906
0
    return;
5907
0
  }
5908
5909
0
  D->addAttr(::new (S.Context) ArmBuiltinAliasAttr(S.Context, AL, Ident));
5910
0
}
5911
5912
0
static bool RISCVAliasValid(unsigned BuiltinID, StringRef AliasName) {
5913
0
  return BuiltinID >= RISCV::FirstRVVBuiltin &&
5914
0
         BuiltinID <= RISCV::LastRVVBuiltin;
5915
0
}
5916
5917
static void handleBuiltinAliasAttr(Sema &S, Decl *D,
5918
0
                                        const ParsedAttr &AL) {
5919
0
  if (!AL.isArgIdent(0)) {
5920
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5921
0
        << AL << 1 << AANT_ArgumentIdentifier;
5922
0
    return;
5923
0
  }
5924
5925
0
  IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
5926
0
  unsigned BuiltinID = Ident->getBuiltinID();
5927
0
  StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
5928
5929
0
  bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5930
0
  bool IsARM = S.Context.getTargetInfo().getTriple().isARM();
5931
0
  bool IsRISCV = S.Context.getTargetInfo().getTriple().isRISCV();
5932
0
  bool IsHLSL = S.Context.getLangOpts().HLSL;
5933
0
  if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) ||
5934
0
      (IsARM && !ArmMveAliasValid(BuiltinID, AliasName) &&
5935
0
       !ArmCdeAliasValid(BuiltinID, AliasName)) ||
5936
0
      (IsRISCV && !RISCVAliasValid(BuiltinID, AliasName)) ||
5937
0
      (!IsAArch64 && !IsARM && !IsRISCV && !IsHLSL)) {
5938
0
    S.Diag(AL.getLoc(), diag::err_attribute_builtin_alias) << AL;
5939
0
    return;
5940
0
  }
5941
5942
0
  D->addAttr(::new (S.Context) BuiltinAliasAttr(S.Context, AL, Ident));
5943
0
}
5944
5945
0
static void handlePreferredTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5946
0
  if (!AL.hasParsedType()) {
5947
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
5948
0
    return;
5949
0
  }
5950
5951
0
  TypeSourceInfo *ParmTSI = nullptr;
5952
0
  QualType QT = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
5953
0
  assert(ParmTSI && "no type source info for attribute argument");
5954
0
  S.RequireCompleteType(ParmTSI->getTypeLoc().getBeginLoc(), QT,
5955
0
                        diag::err_incomplete_type);
5956
5957
0
  D->addAttr(::new (S.Context) PreferredTypeAttr(S.Context, AL, ParmTSI));
5958
0
}
5959
5960
//===----------------------------------------------------------------------===//
5961
// Checker-specific attribute handlers.
5962
//===----------------------------------------------------------------------===//
5963
0
static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
5964
0
  return QT->isDependentType() || QT->isObjCRetainableType();
5965
0
}
5966
5967
0
static bool isValidSubjectOfNSAttribute(QualType QT) {
5968
0
  return QT->isDependentType() || QT->isObjCObjectPointerType() ||
5969
0
         QT->isObjCNSObjectType();
5970
0
}
5971
5972
0
static bool isValidSubjectOfCFAttribute(QualType QT) {
5973
0
  return QT->isDependentType() || QT->isPointerType() ||
5974
0
         isValidSubjectOfNSAttribute(QT);
5975
0
}
5976
5977
0
static bool isValidSubjectOfOSAttribute(QualType QT) {
5978
0
  if (QT->isDependentType())
5979
0
    return true;
5980
0
  QualType PT = QT->getPointeeType();
5981
0
  return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
5982
0
}
5983
5984
void Sema::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
5985
                            RetainOwnershipKind K,
5986
0
                            bool IsTemplateInstantiation) {
5987
0
  ValueDecl *VD = cast<ValueDecl>(D);
5988
0
  switch (K) {
5989
0
  case RetainOwnershipKind::OS:
5990
0
    handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
5991
0
        *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()),
5992
0
        diag::warn_ns_attribute_wrong_parameter_type,
5993
0
        /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1);
5994
0
    return;
5995
0
  case RetainOwnershipKind::NS:
5996
0
    handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
5997
0
        *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()),
5998
5999
        // These attributes are normally just advisory, but in ARC, ns_consumed
6000
        // is significant.  Allow non-dependent code to contain inappropriate
6001
        // attributes even in ARC, but require template instantiations to be
6002
        // set up correctly.
6003
0
        ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
6004
0
             ? diag::err_ns_attribute_wrong_parameter_type
6005
0
             : diag::warn_ns_attribute_wrong_parameter_type),
6006
0
        /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0);
6007
0
    return;
6008
0
  case RetainOwnershipKind::CF:
6009
0
    handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
6010
0
        *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()),
6011
0
        diag::warn_ns_attribute_wrong_parameter_type,
6012
0
        /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1);
6013
0
    return;
6014
0
  }
6015
0
}
6016
6017
static Sema::RetainOwnershipKind
6018
0
parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
6019
0
  switch (AL.getKind()) {
6020
0
  case ParsedAttr::AT_CFConsumed:
6021
0
  case ParsedAttr::AT_CFReturnsRetained:
6022
0
  case ParsedAttr::AT_CFReturnsNotRetained:
6023
0
    return Sema::RetainOwnershipKind::CF;
6024
0
  case ParsedAttr::AT_OSConsumesThis:
6025
0
  case ParsedAttr::AT_OSConsumed:
6026
0
  case ParsedAttr::AT_OSReturnsRetained:
6027
0
  case ParsedAttr::AT_OSReturnsNotRetained:
6028
0
  case ParsedAttr::AT_OSReturnsRetainedOnZero:
6029
0
  case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
6030
0
    return Sema::RetainOwnershipKind::OS;
6031
0
  case ParsedAttr::AT_NSConsumesSelf:
6032
0
  case ParsedAttr::AT_NSConsumed:
6033
0
  case ParsedAttr::AT_NSReturnsRetained:
6034
0
  case ParsedAttr::AT_NSReturnsNotRetained:
6035
0
  case ParsedAttr::AT_NSReturnsAutoreleased:
6036
0
    return Sema::RetainOwnershipKind::NS;
6037
0
  default:
6038
0
    llvm_unreachable("Wrong argument supplied");
6039
0
  }
6040
0
}
6041
6042
0
bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
6043
0
  if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
6044
0
    return false;
6045
6046
0
  Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
6047
0
      << "'ns_returns_retained'" << 0 << 0;
6048
0
  return true;
6049
0
}
6050
6051
/// \return whether the parameter is a pointer to OSObject pointer.
6052
0
static bool isValidOSObjectOutParameter(const Decl *D) {
6053
0
  const auto *PVD = dyn_cast<ParmVarDecl>(D);
6054
0
  if (!PVD)
6055
0
    return false;
6056
0
  QualType QT = PVD->getType();
6057
0
  QualType PT = QT->getPointeeType();
6058
0
  return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
6059
0
}
6060
6061
static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
6062
0
                                        const ParsedAttr &AL) {
6063
0
  QualType ReturnType;
6064
0
  Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
6065
6066
0
  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
6067
0
    ReturnType = MD->getReturnType();
6068
0
  } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
6069
0
             (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
6070
0
    return; // ignore: was handled as a type attribute
6071
0
  } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
6072
0
    ReturnType = PD->getType();
6073
0
  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
6074
0
    ReturnType = FD->getReturnType();
6075
0
  } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
6076
    // Attributes on parameters are used for out-parameters,
6077
    // passed as pointers-to-pointers.
6078
0
    unsigned DiagID = K == Sema::RetainOwnershipKind::CF
6079
0
            ? /*pointer-to-CF-pointer*/2
6080
0
            : /*pointer-to-OSObject-pointer*/3;
6081
0
    ReturnType = Param->getType()->getPointeeType();
6082
0
    if (ReturnType.isNull()) {
6083
0
      S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
6084
0
          << AL << DiagID << AL.getRange();
6085
0
      return;
6086
0
    }
6087
0
  } else if (AL.isUsedAsTypeAttr()) {
6088
0
    return;
6089
0
  } else {
6090
0
    AttributeDeclKind ExpectedDeclKind;
6091
0
    switch (AL.getKind()) {
6092
0
    default: llvm_unreachable("invalid ownership attribute");
6093
0
    case ParsedAttr::AT_NSReturnsRetained:
6094
0
    case ParsedAttr::AT_NSReturnsAutoreleased:
6095
0
    case ParsedAttr::AT_NSReturnsNotRetained:
6096
0
      ExpectedDeclKind = ExpectedFunctionOrMethod;
6097
0
      break;
6098
6099
0
    case ParsedAttr::AT_OSReturnsRetained:
6100
0
    case ParsedAttr::AT_OSReturnsNotRetained:
6101
0
    case ParsedAttr::AT_CFReturnsRetained:
6102
0
    case ParsedAttr::AT_CFReturnsNotRetained:
6103
0
      ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
6104
0
      break;
6105
0
    }
6106
0
    S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
6107
0
        << AL.getRange() << AL << AL.isRegularKeywordAttribute()
6108
0
        << ExpectedDeclKind;
6109
0
    return;
6110
0
  }
6111
6112
0
  bool TypeOK;
6113
0
  bool Cf;
6114
0
  unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
6115
0
  switch (AL.getKind()) {
6116
0
  default: llvm_unreachable("invalid ownership attribute");
6117
0
  case ParsedAttr::AT_NSReturnsRetained:
6118
0
    TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
6119
0
    Cf = false;
6120
0
    break;
6121
6122
0
  case ParsedAttr::AT_NSReturnsAutoreleased:
6123
0
  case ParsedAttr::AT_NSReturnsNotRetained:
6124
0
    TypeOK = isValidSubjectOfNSAttribute(ReturnType);
6125
0
    Cf = false;
6126
0
    break;
6127
6128
0
  case ParsedAttr::AT_CFReturnsRetained:
6129
0
  case ParsedAttr::AT_CFReturnsNotRetained:
6130
0
    TypeOK = isValidSubjectOfCFAttribute(ReturnType);
6131
0
    Cf = true;
6132
0
    break;
6133
6134
0
  case ParsedAttr::AT_OSReturnsRetained:
6135
0
  case ParsedAttr::AT_OSReturnsNotRetained:
6136
0
    TypeOK = isValidSubjectOfOSAttribute(ReturnType);
6137
0
    Cf = true;
6138
0
    ParmDiagID = 3; // Pointer-to-OSObject-pointer
6139
0
    break;
6140
0
  }
6141
6142
0
  if (!TypeOK) {
6143
0
    if (AL.isUsedAsTypeAttr())
6144
0
      return;
6145
6146
0
    if (isa<ParmVarDecl>(D)) {
6147
0
      S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
6148
0
          << AL << ParmDiagID << AL.getRange();
6149
0
    } else {
6150
      // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
6151
0
      enum : unsigned {
6152
0
        Function,
6153
0
        Method,
6154
0
        Property
6155
0
      } SubjectKind = Function;
6156
0
      if (isa<ObjCMethodDecl>(D))
6157
0
        SubjectKind = Method;
6158
0
      else if (isa<ObjCPropertyDecl>(D))
6159
0
        SubjectKind = Property;
6160
0
      S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
6161
0
          << AL << SubjectKind << Cf << AL.getRange();
6162
0
    }
6163
0
    return;
6164
0
  }
6165
6166
0
  switch (AL.getKind()) {
6167
0
    default:
6168
0
      llvm_unreachable("invalid ownership attribute");
6169
0
    case ParsedAttr::AT_NSReturnsAutoreleased:
6170
0
      handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
6171
0
      return;
6172
0
    case ParsedAttr::AT_CFReturnsNotRetained:
6173
0
      handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
6174
0
      return;
6175
0
    case ParsedAttr::AT_NSReturnsNotRetained:
6176
0
      handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
6177
0
      return;
6178
0
    case ParsedAttr::AT_CFReturnsRetained:
6179
0
      handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
6180
0
      return;
6181
0
    case ParsedAttr::AT_NSReturnsRetained:
6182
0
      handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
6183
0
      return;
6184
0
    case ParsedAttr::AT_OSReturnsRetained:
6185
0
      handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
6186
0
      return;
6187
0
    case ParsedAttr::AT_OSReturnsNotRetained:
6188
0
      handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
6189
0
      return;
6190
0
  };
6191
0
}
6192
6193
static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
6194
0
                                              const ParsedAttr &Attrs) {
6195
0
  const int EP_ObjCMethod = 1;
6196
0
  const int EP_ObjCProperty = 2;
6197
6198
0
  SourceLocation loc = Attrs.getLoc();
6199
0
  QualType resultType;
6200
0
  if (isa<ObjCMethodDecl>(D))
6201
0
    resultType = cast<ObjCMethodDecl>(D)->getReturnType();
6202
0
  else
6203
0
    resultType = cast<ObjCPropertyDecl>(D)->getType();
6204
6205
0
  if (!resultType->isReferenceType() &&
6206
0
      (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
6207
0
    S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
6208
0
        << SourceRange(loc) << Attrs
6209
0
        << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
6210
0
        << /*non-retainable pointer*/ 2;
6211
6212
    // Drop the attribute.
6213
0
    return;
6214
0
  }
6215
6216
0
  D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs));
6217
0
}
6218
6219
static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
6220
0
                                        const ParsedAttr &Attrs) {
6221
0
  const auto *Method = cast<ObjCMethodDecl>(D);
6222
6223
0
  const DeclContext *DC = Method->getDeclContext();
6224
0
  if (const auto *PDecl = dyn_cast_if_present<ObjCProtocolDecl>(DC)) {
6225
0
    S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
6226
0
                                                                      << 0;
6227
0
    S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
6228
0
    return;
6229
0
  }
6230
0
  if (Method->getMethodFamily() == OMF_dealloc) {
6231
0
    S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
6232
0
                                                                      << 1;
6233
0
    return;
6234
0
  }
6235
6236
0
  D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
6237
0
}
6238
6239
0
static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &AL) {
6240
0
  auto *E = AL.getArgAsExpr(0);
6241
0
  auto Loc = E ? E->getBeginLoc() : AL.getLoc();
6242
6243
0
  auto *DRE = dyn_cast<DeclRefExpr>(AL.getArgAsExpr(0));
6244
0
  if (!DRE) {
6245
0
    S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 0;
6246
0
    return;
6247
0
  }
6248
6249
0
  auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6250
0
  if (!VD) {
6251
0
    S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 1 << DRE->getDecl();
6252
0
    return;
6253
0
  }
6254
6255
0
  if (!isNSStringType(VD->getType(), S.Context) &&
6256
0
      !isCFStringType(VD->getType(), S.Context)) {
6257
0
    S.Diag(Loc, diag::err_nserrordomain_wrong_type) << VD;
6258
0
    return;
6259
0
  }
6260
6261
0
  D->addAttr(::new (S.Context) NSErrorDomainAttr(S.Context, AL, VD));
6262
0
}
6263
6264
0
static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6265
0
  IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
6266
6267
0
  if (!Parm) {
6268
0
    S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
6269
0
    return;
6270
0
  }
6271
6272
  // Typedefs only allow objc_bridge(id) and have some additional checking.
6273
0
  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
6274
0
    if (!Parm->Ident->isStr("id")) {
6275
0
      S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
6276
0
      return;
6277
0
    }
6278
6279
    // Only allow 'cv void *'.
6280
0
    QualType T = TD->getUnderlyingType();
6281
0
    if (!T->isVoidPointerType()) {
6282
0
      S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
6283
0
      return;
6284
0
    }
6285
0
  }
6286
6287
0
  D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident));
6288
0
}
6289
6290
static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
6291
0
                                        const ParsedAttr &AL) {
6292
0
  IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
6293
6294
0
  if (!Parm) {
6295
0
    S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
6296
0
    return;
6297
0
  }
6298
6299
0
  D->addAttr(::new (S.Context)
6300
0
                 ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident));
6301
0
}
6302
6303
static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
6304
0
                                        const ParsedAttr &AL) {
6305
0
  IdentifierInfo *RelatedClass =
6306
0
      AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
6307
0
  if (!RelatedClass) {
6308
0
    S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
6309
0
    return;
6310
0
  }
6311
0
  IdentifierInfo *ClassMethod =
6312
0
    AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
6313
0
  IdentifierInfo *InstanceMethod =
6314
0
    AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
6315
0
  D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr(
6316
0
      S.Context, AL, RelatedClass, ClassMethod, InstanceMethod));
6317
0
}
6318
6319
static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
6320
0
                                            const ParsedAttr &AL) {
6321
0
  DeclContext *Ctx = D->getDeclContext();
6322
6323
  // This attribute can only be applied to methods in interfaces or class
6324
  // extensions.
6325
0
  if (!isa<ObjCInterfaceDecl>(Ctx) &&
6326
0
      !(isa<ObjCCategoryDecl>(Ctx) &&
6327
0
        cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
6328
0
    S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
6329
0
    return;
6330
0
  }
6331
6332
0
  ObjCInterfaceDecl *IFace;
6333
0
  if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
6334
0
    IFace = CatDecl->getClassInterface();
6335
0
  else
6336
0
    IFace = cast<ObjCInterfaceDecl>(Ctx);
6337
6338
0
  if (!IFace)
6339
0
    return;
6340
6341
0
  IFace->setHasDesignatedInitializers();
6342
0
  D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL));
6343
0
}
6344
6345
0
static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
6346
0
  StringRef MetaDataName;
6347
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
6348
0
    return;
6349
0
  D->addAttr(::new (S.Context)
6350
0
                 ObjCRuntimeNameAttr(S.Context, AL, MetaDataName));
6351
0
}
6352
6353
// When a user wants to use objc_boxable with a union or struct
6354
// but they don't have access to the declaration (legacy/third-party code)
6355
// then they can 'enable' this feature with a typedef:
6356
// typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
6357
0
static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
6358
0
  bool notify = false;
6359
6360
0
  auto *RD = dyn_cast<RecordDecl>(D);
6361
0
  if (RD && RD->getDefinition()) {
6362
0
    RD = RD->getDefinition();
6363
0
    notify = true;
6364
0
  }
6365
6366
0
  if (RD) {
6367
0
    ObjCBoxableAttr *BoxableAttr =
6368
0
        ::new (S.Context) ObjCBoxableAttr(S.Context, AL);
6369
0
    RD->addAttr(BoxableAttr);
6370
0
    if (notify) {
6371
      // we need to notify ASTReader/ASTWriter about
6372
      // modification of existing declaration
6373
0
      if (ASTMutationListener *L = S.getASTMutationListener())
6374
0
        L->AddedAttributeToRecord(BoxableAttr, RD);
6375
0
    }
6376
0
  }
6377
0
}
6378
6379
0
static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6380
0
  if (hasDeclarator(D))
6381
0
    return;
6382
6383
0
  S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
6384
0
      << AL.getRange() << AL << AL.isRegularKeywordAttribute()
6385
0
      << ExpectedVariable;
6386
0
}
6387
6388
static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
6389
0
                                          const ParsedAttr &AL) {
6390
0
  const auto *VD = cast<ValueDecl>(D);
6391
0
  QualType QT = VD->getType();
6392
6393
0
  if (!QT->isDependentType() &&
6394
0
      !QT->isObjCLifetimeType()) {
6395
0
    S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
6396
0
      << QT;
6397
0
    return;
6398
0
  }
6399
6400
0
  Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
6401
6402
  // If we have no lifetime yet, check the lifetime we're presumably
6403
  // going to infer.
6404
0
  if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
6405
0
    Lifetime = QT->getObjCARCImplicitLifetime();
6406
6407
0
  switch (Lifetime) {
6408
0
  case Qualifiers::OCL_None:
6409
0
    assert(QT->isDependentType() &&
6410
0
           "didn't infer lifetime for non-dependent type?");
6411
0
    break;
6412
6413
0
  case Qualifiers::OCL_Weak:   // meaningful
6414
0
  case Qualifiers::OCL_Strong: // meaningful
6415
0
    break;
6416
6417
0
  case Qualifiers::OCL_ExplicitNone:
6418
0
  case Qualifiers::OCL_Autoreleasing:
6419
0
    S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
6420
0
        << (Lifetime == Qualifiers::OCL_Autoreleasing);
6421
0
    break;
6422
0
  }
6423
6424
0
  D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL));
6425
0
}
6426
6427
0
static void handleSwiftAttrAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6428
  // Make sure that there is a string literal as the annotation's single
6429
  // argument.
6430
0
  StringRef Str;
6431
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
6432
0
    return;
6433
6434
0
  D->addAttr(::new (S.Context) SwiftAttrAttr(S.Context, AL, Str));
6435
0
}
6436
6437
0
static void handleSwiftBridge(Sema &S, Decl *D, const ParsedAttr &AL) {
6438
  // Make sure that there is a string literal as the annotation's single
6439
  // argument.
6440
0
  StringRef BT;
6441
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, BT))
6442
0
    return;
6443
6444
  // Warn about duplicate attributes if they have different arguments, but drop
6445
  // any duplicate attributes regardless.
6446
0
  if (const auto *Other = D->getAttr<SwiftBridgeAttr>()) {
6447
0
    if (Other->getSwiftType() != BT)
6448
0
      S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
6449
0
    return;
6450
0
  }
6451
6452
0
  D->addAttr(::new (S.Context) SwiftBridgeAttr(S.Context, AL, BT));
6453
0
}
6454
6455
0
static bool isErrorParameter(Sema &S, QualType QT) {
6456
0
  const auto *PT = QT->getAs<PointerType>();
6457
0
  if (!PT)
6458
0
    return false;
6459
6460
0
  QualType Pointee = PT->getPointeeType();
6461
6462
  // Check for NSError**.
6463
0
  if (const auto *OPT = Pointee->getAs<ObjCObjectPointerType>())
6464
0
    if (const auto *ID = OPT->getInterfaceDecl())
6465
0
      if (ID->getIdentifier() == S.getNSErrorIdent())
6466
0
        return true;
6467
6468
  // Check for CFError**.
6469
0
  if (const auto *PT = Pointee->getAs<PointerType>())
6470
0
    if (const auto *RT = PT->getPointeeType()->getAs<RecordType>())
6471
0
      if (S.isCFError(RT->getDecl()))
6472
0
        return true;
6473
6474
0
  return false;
6475
0
}
6476
6477
0
static void handleSwiftError(Sema &S, Decl *D, const ParsedAttr &AL) {
6478
0
  auto hasErrorParameter = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
6479
0
    for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
6480
0
      if (isErrorParameter(S, getFunctionOrMethodParamType(D, I)))
6481
0
        return true;
6482
0
    }
6483
6484
0
    S.Diag(AL.getLoc(), diag::err_attr_swift_error_no_error_parameter)
6485
0
        << AL << isa<ObjCMethodDecl>(D);
6486
0
    return false;
6487
0
  };
6488
6489
0
  auto hasPointerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
6490
    // - C, ObjC, and block pointers are definitely okay.
6491
    // - References are definitely not okay.
6492
    // - nullptr_t is weird, but acceptable.
6493
0
    QualType RT = getFunctionOrMethodResultType(D);
6494
0
    if (RT->hasPointerRepresentation() && !RT->isReferenceType())
6495
0
      return true;
6496
6497
0
    S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
6498
0
        << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
6499
0
        << /*pointer*/ 1;
6500
0
    return false;
6501
0
  };
6502
6503
0
  auto hasIntegerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
6504
0
    QualType RT = getFunctionOrMethodResultType(D);
6505
0
    if (RT->isIntegralType(S.Context))
6506
0
      return true;
6507
6508
0
    S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
6509
0
        << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
6510
0
        << /*integral*/ 0;
6511
0
    return false;
6512
0
  };
6513
6514
0
  if (D->isInvalidDecl())
6515
0
    return;
6516
6517
0
  IdentifierLoc *Loc = AL.getArgAsIdent(0);
6518
0
  SwiftErrorAttr::ConventionKind Convention;
6519
0
  if (!SwiftErrorAttr::ConvertStrToConventionKind(Loc->Ident->getName(),
6520
0
                                                  Convention)) {
6521
0
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
6522
0
        << AL << Loc->Ident;
6523
0
    return;
6524
0
  }
6525
6526
0
  switch (Convention) {
6527
0
  case SwiftErrorAttr::None:
6528
    // No additional validation required.
6529
0
    break;
6530
6531
0
  case SwiftErrorAttr::NonNullError:
6532
0
    if (!hasErrorParameter(S, D, AL))
6533
0
      return;
6534
0
    break;
6535
6536
0
  case SwiftErrorAttr::NullResult:
6537
0
    if (!hasErrorParameter(S, D, AL) || !hasPointerResult(S, D, AL))
6538
0
      return;
6539
0
    break;
6540
6541
0
  case SwiftErrorAttr::NonZeroResult:
6542
0
  case SwiftErrorAttr::ZeroResult:
6543
0
    if (!hasErrorParameter(S, D, AL) || !hasIntegerResult(S, D, AL))
6544
0
      return;
6545
0
    break;
6546
0
  }
6547
6548
0
  D->addAttr(::new (S.Context) SwiftErrorAttr(S.Context, AL, Convention));
6549
0
}
6550
6551
static void checkSwiftAsyncErrorBlock(Sema &S, Decl *D,
6552
                                      const SwiftAsyncErrorAttr *ErrorAttr,
6553
0
                                      const SwiftAsyncAttr *AsyncAttr) {
6554
0
  if (AsyncAttr->getKind() == SwiftAsyncAttr::None) {
6555
0
    if (ErrorAttr->getConvention() != SwiftAsyncErrorAttr::None) {
6556
0
      S.Diag(AsyncAttr->getLocation(),
6557
0
             diag::err_swift_async_error_without_swift_async)
6558
0
          << AsyncAttr << isa<ObjCMethodDecl>(D);
6559
0
    }
6560
0
    return;
6561
0
  }
6562
6563
0
  const ParmVarDecl *HandlerParam = getFunctionOrMethodParam(
6564
0
      D, AsyncAttr->getCompletionHandlerIndex().getASTIndex());
6565
  // handleSwiftAsyncAttr already verified the type is correct, so no need to
6566
  // double-check it here.
6567
0
  const auto *FuncTy = HandlerParam->getType()
6568
0
                           ->castAs<BlockPointerType>()
6569
0
                           ->getPointeeType()
6570
0
                           ->getAs<FunctionProtoType>();
6571
0
  ArrayRef<QualType> BlockParams;
6572
0
  if (FuncTy)
6573
0
    BlockParams = FuncTy->getParamTypes();
6574
6575
0
  switch (ErrorAttr->getConvention()) {
6576
0
  case SwiftAsyncErrorAttr::ZeroArgument:
6577
0
  case SwiftAsyncErrorAttr::NonZeroArgument: {
6578
0
    uint32_t ParamIdx = ErrorAttr->getHandlerParamIdx();
6579
0
    if (ParamIdx == 0 || ParamIdx > BlockParams.size()) {
6580
0
      S.Diag(ErrorAttr->getLocation(),
6581
0
             diag::err_attribute_argument_out_of_bounds) << ErrorAttr << 2;
6582
0
      return;
6583
0
    }
6584
0
    QualType ErrorParam = BlockParams[ParamIdx - 1];
6585
0
    if (!ErrorParam->isIntegralType(S.Context)) {
6586
0
      StringRef ConvStr =
6587
0
          ErrorAttr->getConvention() == SwiftAsyncErrorAttr::ZeroArgument
6588
0
              ? "zero_argument"
6589
0
              : "nonzero_argument";
6590
0
      S.Diag(ErrorAttr->getLocation(), diag::err_swift_async_error_non_integral)
6591
0
          << ErrorAttr << ConvStr << ParamIdx << ErrorParam;
6592
0
      return;
6593
0
    }
6594
0
    break;
6595
0
  }
6596
0
  case SwiftAsyncErrorAttr::NonNullError: {
6597
0
    bool AnyErrorParams = false;
6598
0
    for (QualType Param : BlockParams) {
6599
      // Check for NSError *.
6600
0
      if (const auto *ObjCPtrTy = Param->getAs<ObjCObjectPointerType>()) {
6601
0
        if (const auto *ID = ObjCPtrTy->getInterfaceDecl()) {
6602
0
          if (ID->getIdentifier() == S.getNSErrorIdent()) {
6603
0
            AnyErrorParams = true;
6604
0
            break;
6605
0
          }
6606
0
        }
6607
0
      }
6608
      // Check for CFError *.
6609
0
      if (const auto *PtrTy = Param->getAs<PointerType>()) {
6610
0
        if (const auto *RT = PtrTy->getPointeeType()->getAs<RecordType>()) {
6611
0
          if (S.isCFError(RT->getDecl())) {
6612
0
            AnyErrorParams = true;
6613
0
            break;
6614
0
          }
6615
0
        }
6616
0
      }
6617
0
    }
6618
6619
0
    if (!AnyErrorParams) {
6620
0
      S.Diag(ErrorAttr->getLocation(),
6621
0
             diag::err_swift_async_error_no_error_parameter)
6622
0
          << ErrorAttr << isa<ObjCMethodDecl>(D);
6623
0
      return;
6624
0
    }
6625
0
    break;
6626
0
  }
6627
0
  case SwiftAsyncErrorAttr::None:
6628
0
    break;
6629
0
  }
6630
0
}
6631
6632
0
static void handleSwiftAsyncError(Sema &S, Decl *D, const ParsedAttr &AL) {
6633
0
  IdentifierLoc *IDLoc = AL.getArgAsIdent(0);
6634
0
  SwiftAsyncErrorAttr::ConventionKind ConvKind;
6635
0
  if (!SwiftAsyncErrorAttr::ConvertStrToConventionKind(IDLoc->Ident->getName(),
6636
0
                                                       ConvKind)) {
6637
0
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
6638
0
        << AL << IDLoc->Ident;
6639
0
    return;
6640
0
  }
6641
6642
0
  uint32_t ParamIdx = 0;
6643
0
  switch (ConvKind) {
6644
0
  case SwiftAsyncErrorAttr::ZeroArgument:
6645
0
  case SwiftAsyncErrorAttr::NonZeroArgument: {
6646
0
    if (!AL.checkExactlyNumArgs(S, 2))
6647
0
      return;
6648
6649
0
    Expr *IdxExpr = AL.getArgAsExpr(1);
6650
0
    if (!checkUInt32Argument(S, AL, IdxExpr, ParamIdx))
6651
0
      return;
6652
0
    break;
6653
0
  }
6654
0
  case SwiftAsyncErrorAttr::NonNullError:
6655
0
  case SwiftAsyncErrorAttr::None: {
6656
0
    if (!AL.checkExactlyNumArgs(S, 1))
6657
0
      return;
6658
0
    break;
6659
0
  }
6660
0
  }
6661
6662
0
  auto *ErrorAttr =
6663
0
      ::new (S.Context) SwiftAsyncErrorAttr(S.Context, AL, ConvKind, ParamIdx);
6664
0
  D->addAttr(ErrorAttr);
6665
6666
0
  if (auto *AsyncAttr = D->getAttr<SwiftAsyncAttr>())
6667
0
    checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
6668
0
}
6669
6670
// For a function, this will validate a compound Swift name, e.g.
6671
// <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, and
6672
// the function will output the number of parameter names, and whether this is a
6673
// single-arg initializer.
6674
//
6675
// For a type, enum constant, property, or variable declaration, this will
6676
// validate either a simple identifier, or a qualified
6677
// <code>context.identifier</code> name.
6678
static bool
6679
validateSwiftFunctionName(Sema &S, const ParsedAttr &AL, SourceLocation Loc,
6680
                          StringRef Name, unsigned &SwiftParamCount,
6681
0
                          bool &IsSingleParamInit) {
6682
0
  SwiftParamCount = 0;
6683
0
  IsSingleParamInit = false;
6684
6685
  // Check whether this will be mapped to a getter or setter of a property.
6686
0
  bool IsGetter = false, IsSetter = false;
6687
0
  if (Name.starts_with("getter:")) {
6688
0
    IsGetter = true;
6689
0
    Name = Name.substr(7);
6690
0
  } else if (Name.starts_with("setter:")) {
6691
0
    IsSetter = true;
6692
0
    Name = Name.substr(7);
6693
0
  }
6694
6695
0
  if (Name.back() != ')') {
6696
0
    S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
6697
0
    return false;
6698
0
  }
6699
6700
0
  bool IsMember = false;
6701
0
  StringRef ContextName, BaseName, Parameters;
6702
6703
0
  std::tie(BaseName, Parameters) = Name.split('(');
6704
6705
  // Split at the first '.', if it exists, which separates the context name
6706
  // from the base name.
6707
0
  std::tie(ContextName, BaseName) = BaseName.split('.');
6708
0
  if (BaseName.empty()) {
6709
0
    BaseName = ContextName;
6710
0
    ContextName = StringRef();
6711
0
  } else if (ContextName.empty() || !isValidAsciiIdentifier(ContextName)) {
6712
0
    S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6713
0
        << AL << /*context*/ 1;
6714
0
    return false;
6715
0
  } else {
6716
0
    IsMember = true;
6717
0
  }
6718
6719
0
  if (!isValidAsciiIdentifier(BaseName) || BaseName == "_") {
6720
0
    S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6721
0
        << AL << /*basename*/ 0;
6722
0
    return false;
6723
0
  }
6724
6725
0
  bool IsSubscript = BaseName == "subscript";
6726
  // A subscript accessor must be a getter or setter.
6727
0
  if (IsSubscript && !IsGetter && !IsSetter) {
6728
0
    S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6729
0
        << AL << /* getter or setter */ 0;
6730
0
    return false;
6731
0
  }
6732
6733
0
  if (Parameters.empty()) {
6734
0
    S.Diag(Loc, diag::warn_attr_swift_name_missing_parameters) << AL;
6735
0
    return false;
6736
0
  }
6737
6738
0
  assert(Parameters.back() == ')' && "expected ')'");
6739
0
  Parameters = Parameters.drop_back(); // ')'
6740
6741
0
  if (Parameters.empty()) {
6742
    // Setters and subscripts must have at least one parameter.
6743
0
    if (IsSubscript) {
6744
0
      S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6745
0
          << AL << /* have at least one parameter */1;
6746
0
      return false;
6747
0
    }
6748
6749
0
    if (IsSetter) {
6750
0
      S.Diag(Loc, diag::warn_attr_swift_name_setter_parameters) << AL;
6751
0
      return false;
6752
0
    }
6753
6754
0
    return true;
6755
0
  }
6756
6757
0
  if (Parameters.back() != ':') {
6758
0
    S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
6759
0
    return false;
6760
0
  }
6761
6762
0
  StringRef CurrentParam;
6763
0
  std::optional<unsigned> SelfLocation;
6764
0
  unsigned NewValueCount = 0;
6765
0
  std::optional<unsigned> NewValueLocation;
6766
0
  do {
6767
0
    std::tie(CurrentParam, Parameters) = Parameters.split(':');
6768
6769
0
    if (!isValidAsciiIdentifier(CurrentParam)) {
6770
0
      S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6771
0
          << AL << /*parameter*/2;
6772
0
      return false;
6773
0
    }
6774
6775
0
    if (IsMember && CurrentParam == "self") {
6776
      // "self" indicates the "self" argument for a member.
6777
6778
      // More than one "self"?
6779
0
      if (SelfLocation) {
6780
0
        S.Diag(Loc, diag::warn_attr_swift_name_multiple_selfs) << AL;
6781
0
        return false;
6782
0
      }
6783
6784
      // The "self" location is the current parameter.
6785
0
      SelfLocation = SwiftParamCount;
6786
0
    } else if (CurrentParam == "newValue") {
6787
      // "newValue" indicates the "newValue" argument for a setter.
6788
6789
      // There should only be one 'newValue', but it's only significant for
6790
      // subscript accessors, so don't error right away.
6791
0
      ++NewValueCount;
6792
6793
0
      NewValueLocation = SwiftParamCount;
6794
0
    }
6795
6796
0
    ++SwiftParamCount;
6797
0
  } while (!Parameters.empty());
6798
6799
  // Only instance subscripts are currently supported.
6800
0
  if (IsSubscript && !SelfLocation) {
6801
0
    S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6802
0
        << AL << /*have a 'self:' parameter*/2;
6803
0
    return false;
6804
0
  }
6805
6806
0
  IsSingleParamInit =
6807
0
        SwiftParamCount == 1 && BaseName == "init" && CurrentParam != "_";
6808
6809
  // Check the number of parameters for a getter/setter.
6810
0
  if (IsGetter || IsSetter) {
6811
    // Setters have one parameter for the new value.
6812
0
    unsigned NumExpectedParams = IsGetter ? 0 : 1;
6813
0
    unsigned ParamDiag =
6814
0
        IsGetter ? diag::warn_attr_swift_name_getter_parameters
6815
0
                 : diag::warn_attr_swift_name_setter_parameters;
6816
6817
    // Instance methods have one parameter for "self".
6818
0
    if (SelfLocation)
6819
0
      ++NumExpectedParams;
6820
6821
    // Subscripts may have additional parameters beyond the expected params for
6822
    // the index.
6823
0
    if (IsSubscript) {
6824
0
      if (SwiftParamCount < NumExpectedParams) {
6825
0
        S.Diag(Loc, ParamDiag) << AL;
6826
0
        return false;
6827
0
      }
6828
6829
      // A subscript setter must explicitly label its newValue parameter to
6830
      // distinguish it from index parameters.
6831
0
      if (IsSetter) {
6832
0
        if (!NewValueLocation) {
6833
0
          S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_no_newValue)
6834
0
              << AL;
6835
0
          return false;
6836
0
        }
6837
0
        if (NewValueCount > 1) {
6838
0
          S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_multiple_newValues)
6839
0
              << AL;
6840
0
          return false;
6841
0
        }
6842
0
      } else {
6843
        // Subscript getters should have no 'newValue:' parameter.
6844
0
        if (NewValueLocation) {
6845
0
          S.Diag(Loc, diag::warn_attr_swift_name_subscript_getter_newValue)
6846
0
              << AL;
6847
0
          return false;
6848
0
        }
6849
0
      }
6850
0
    } else {
6851
      // Property accessors must have exactly the number of expected params.
6852
0
      if (SwiftParamCount != NumExpectedParams) {
6853
0
        S.Diag(Loc, ParamDiag) << AL;
6854
0
        return false;
6855
0
      }
6856
0
    }
6857
0
  }
6858
6859
0
  return true;
6860
0
}
6861
6862
bool Sema::DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
6863
0
                             const ParsedAttr &AL, bool IsAsync) {
6864
0
  if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
6865
0
    ArrayRef<ParmVarDecl*> Params;
6866
0
    unsigned ParamCount;
6867
6868
0
    if (const auto *Method = dyn_cast<ObjCMethodDecl>(D)) {
6869
0
      ParamCount = Method->getSelector().getNumArgs();
6870
0
      Params = Method->parameters().slice(0, ParamCount);
6871
0
    } else {
6872
0
      const auto *F = cast<FunctionDecl>(D);
6873
6874
0
      ParamCount = F->getNumParams();
6875
0
      Params = F->parameters();
6876
6877
0
      if (!F->hasWrittenPrototype()) {
6878
0
        Diag(Loc, diag::warn_attribute_wrong_decl_type)
6879
0
            << AL << AL.isRegularKeywordAttribute()
6880
0
            << ExpectedFunctionWithProtoType;
6881
0
        return false;
6882
0
      }
6883
0
    }
6884
6885
    // The async name drops the last callback parameter.
6886
0
    if (IsAsync) {
6887
0
      if (ParamCount == 0) {
6888
0
        Diag(Loc, diag::warn_attr_swift_name_decl_missing_params)
6889
0
            << AL << isa<ObjCMethodDecl>(D);
6890
0
        return false;
6891
0
      }
6892
0
      ParamCount -= 1;
6893
0
    }
6894
6895
0
    unsigned SwiftParamCount;
6896
0
    bool IsSingleParamInit;
6897
0
    if (!validateSwiftFunctionName(*this, AL, Loc, Name,
6898
0
                                   SwiftParamCount, IsSingleParamInit))
6899
0
      return false;
6900
6901
0
    bool ParamCountValid;
6902
0
    if (SwiftParamCount == ParamCount) {
6903
0
      ParamCountValid = true;
6904
0
    } else if (SwiftParamCount > ParamCount) {
6905
0
      ParamCountValid = IsSingleParamInit && ParamCount == 0;
6906
0
    } else {
6907
      // We have fewer Swift parameters than Objective-C parameters, but that
6908
      // might be because we've transformed some of them. Check for potential
6909
      // "out" parameters and err on the side of not warning.
6910
0
      unsigned MaybeOutParamCount =
6911
0
          llvm::count_if(Params, [](const ParmVarDecl *Param) -> bool {
6912
0
            QualType ParamTy = Param->getType();
6913
0
            if (ParamTy->isReferenceType() || ParamTy->isPointerType())
6914
0
              return !ParamTy->getPointeeType().isConstQualified();
6915
0
            return false;
6916
0
          });
6917
6918
0
      ParamCountValid = SwiftParamCount + MaybeOutParamCount >= ParamCount;
6919
0
    }
6920
6921
0
    if (!ParamCountValid) {
6922
0
      Diag(Loc, diag::warn_attr_swift_name_num_params)
6923
0
          << (SwiftParamCount > ParamCount) << AL << ParamCount
6924
0
          << SwiftParamCount;
6925
0
      return false;
6926
0
    }
6927
0
  } else if ((isa<EnumConstantDecl>(D) || isa<ObjCProtocolDecl>(D) ||
6928
0
              isa<ObjCInterfaceDecl>(D) || isa<ObjCPropertyDecl>(D) ||
6929
0
              isa<VarDecl>(D) || isa<TypedefNameDecl>(D) || isa<TagDecl>(D) ||
6930
0
              isa<IndirectFieldDecl>(D) || isa<FieldDecl>(D)) &&
6931
0
             !IsAsync) {
6932
0
    StringRef ContextName, BaseName;
6933
6934
0
    std::tie(ContextName, BaseName) = Name.split('.');
6935
0
    if (BaseName.empty()) {
6936
0
      BaseName = ContextName;
6937
0
      ContextName = StringRef();
6938
0
    } else if (!isValidAsciiIdentifier(ContextName)) {
6939
0
      Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
6940
0
          << /*context*/1;
6941
0
      return false;
6942
0
    }
6943
6944
0
    if (!isValidAsciiIdentifier(BaseName)) {
6945
0
      Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
6946
0
          << /*basename*/0;
6947
0
      return false;
6948
0
    }
6949
0
  } else {
6950
0
    Diag(Loc, diag::warn_attr_swift_name_decl_kind) << AL;
6951
0
    return false;
6952
0
  }
6953
0
  return true;
6954
0
}
6955
6956
0
static void handleSwiftName(Sema &S, Decl *D, const ParsedAttr &AL) {
6957
0
  StringRef Name;
6958
0
  SourceLocation Loc;
6959
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
6960
0
    return;
6961
6962
0
  if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/false))
6963
0
    return;
6964
6965
0
  D->addAttr(::new (S.Context) SwiftNameAttr(S.Context, AL, Name));
6966
0
}
6967
6968
0
static void handleSwiftAsyncName(Sema &S, Decl *D, const ParsedAttr &AL) {
6969
0
  StringRef Name;
6970
0
  SourceLocation Loc;
6971
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
6972
0
    return;
6973
6974
0
  if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/true))
6975
0
    return;
6976
6977
0
  D->addAttr(::new (S.Context) SwiftAsyncNameAttr(S.Context, AL, Name));
6978
0
}
6979
6980
0
static void handleSwiftNewType(Sema &S, Decl *D, const ParsedAttr &AL) {
6981
  // Make sure that there is an identifier as the annotation's single argument.
6982
0
  if (!AL.checkExactlyNumArgs(S, 1))
6983
0
    return;
6984
6985
0
  if (!AL.isArgIdent(0)) {
6986
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6987
0
        << AL << AANT_ArgumentIdentifier;
6988
0
    return;
6989
0
  }
6990
6991
0
  SwiftNewTypeAttr::NewtypeKind Kind;
6992
0
  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
6993
0
  if (!SwiftNewTypeAttr::ConvertStrToNewtypeKind(II->getName(), Kind)) {
6994
0
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
6995
0
    return;
6996
0
  }
6997
6998
0
  if (!isa<TypedefNameDecl>(D)) {
6999
0
    S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
7000
0
        << AL << AL.isRegularKeywordAttribute() << "typedefs";
7001
0
    return;
7002
0
  }
7003
7004
0
  D->addAttr(::new (S.Context) SwiftNewTypeAttr(S.Context, AL, Kind));
7005
0
}
7006
7007
0
static void handleSwiftAsyncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7008
0
  if (!AL.isArgIdent(0)) {
7009
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
7010
0
        << AL << 1 << AANT_ArgumentIdentifier;
7011
0
    return;
7012
0
  }
7013
7014
0
  SwiftAsyncAttr::Kind Kind;
7015
0
  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
7016
0
  if (!SwiftAsyncAttr::ConvertStrToKind(II->getName(), Kind)) {
7017
0
    S.Diag(AL.getLoc(), diag::err_swift_async_no_access) << AL << II;
7018
0
    return;
7019
0
  }
7020
7021
0
  ParamIdx Idx;
7022
0
  if (Kind == SwiftAsyncAttr::None) {
7023
    // If this is 'none', then there shouldn't be any additional arguments.
7024
0
    if (!AL.checkExactlyNumArgs(S, 1))
7025
0
      return;
7026
0
  } else {
7027
    // Non-none swift_async requires a completion handler index argument.
7028
0
    if (!AL.checkExactlyNumArgs(S, 2))
7029
0
      return;
7030
7031
0
    Expr *HandlerIdx = AL.getArgAsExpr(1);
7032
0
    if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, HandlerIdx, Idx))
7033
0
      return;
7034
7035
0
    const ParmVarDecl *CompletionBlock =
7036
0
        getFunctionOrMethodParam(D, Idx.getASTIndex());
7037
0
    QualType CompletionBlockType = CompletionBlock->getType();
7038
0
    if (!CompletionBlockType->isBlockPointerType()) {
7039
0
      S.Diag(CompletionBlock->getLocation(),
7040
0
             diag::err_swift_async_bad_block_type)
7041
0
          << CompletionBlock->getType();
7042
0
      return;
7043
0
    }
7044
0
    QualType BlockTy =
7045
0
        CompletionBlockType->castAs<BlockPointerType>()->getPointeeType();
7046
0
    if (!BlockTy->castAs<FunctionType>()->getReturnType()->isVoidType()) {
7047
0
      S.Diag(CompletionBlock->getLocation(),
7048
0
             diag::err_swift_async_bad_block_type)
7049
0
          << CompletionBlock->getType();
7050
0
      return;
7051
0
    }
7052
0
  }
7053
7054
0
  auto *AsyncAttr =
7055
0
      ::new (S.Context) SwiftAsyncAttr(S.Context, AL, Kind, Idx);
7056
0
  D->addAttr(AsyncAttr);
7057
7058
0
  if (auto *ErrorAttr = D->getAttr<SwiftAsyncErrorAttr>())
7059
0
    checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
7060
0
}
7061
7062
//===----------------------------------------------------------------------===//
7063
// Microsoft specific attribute handlers.
7064
//===----------------------------------------------------------------------===//
7065
7066
UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
7067
0
                              StringRef UuidAsWritten, MSGuidDecl *GuidDecl) {
7068
0
  if (const auto *UA = D->getAttr<UuidAttr>()) {
7069
0
    if (declaresSameEntity(UA->getGuidDecl(), GuidDecl))
7070
0
      return nullptr;
7071
0
    if (!UA->getGuid().empty()) {
7072
0
      Diag(UA->getLocation(), diag::err_mismatched_uuid);
7073
0
      Diag(CI.getLoc(), diag::note_previous_uuid);
7074
0
      D->dropAttr<UuidAttr>();
7075
0
    }
7076
0
  }
7077
7078
0
  return ::new (Context) UuidAttr(Context, CI, UuidAsWritten, GuidDecl);
7079
0
}
7080
7081
0
static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7082
0
  if (!S.LangOpts.CPlusPlus) {
7083
0
    S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
7084
0
        << AL << AttributeLangSupport::C;
7085
0
    return;
7086
0
  }
7087
7088
0
  StringRef OrigStrRef;
7089
0
  SourceLocation LiteralLoc;
7090
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, OrigStrRef, &LiteralLoc))
7091
0
    return;
7092
7093
  // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
7094
  // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
7095
0
  StringRef StrRef = OrigStrRef;
7096
0
  if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
7097
0
    StrRef = StrRef.drop_front().drop_back();
7098
7099
  // Validate GUID length.
7100
0
  if (StrRef.size() != 36) {
7101
0
    S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
7102
0
    return;
7103
0
  }
7104
7105
0
  for (unsigned i = 0; i < 36; ++i) {
7106
0
    if (i == 8 || i == 13 || i == 18 || i == 23) {
7107
0
      if (StrRef[i] != '-') {
7108
0
        S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
7109
0
        return;
7110
0
      }
7111
0
    } else if (!isHexDigit(StrRef[i])) {
7112
0
      S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
7113
0
      return;
7114
0
    }
7115
0
  }
7116
7117
  // Convert to our parsed format and canonicalize.
7118
0
  MSGuidDecl::Parts Parsed;
7119
0
  StrRef.substr(0, 8).getAsInteger(16, Parsed.Part1);
7120
0
  StrRef.substr(9, 4).getAsInteger(16, Parsed.Part2);
7121
0
  StrRef.substr(14, 4).getAsInteger(16, Parsed.Part3);
7122
0
  for (unsigned i = 0; i != 8; ++i)
7123
0
    StrRef.substr(19 + 2 * i + (i >= 2 ? 1 : 0), 2)
7124
0
        .getAsInteger(16, Parsed.Part4And5[i]);
7125
0
  MSGuidDecl *Guid = S.Context.getMSGuidDecl(Parsed);
7126
7127
  // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
7128
  // the only thing in the [] list, the [] too), and add an insertion of
7129
  // __declspec(uuid(...)).  But sadly, neither the SourceLocs of the commas
7130
  // separating attributes nor of the [ and the ] are in the AST.
7131
  // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
7132
  // on cfe-dev.
7133
0
  if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
7134
0
    S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
7135
7136
0
  UuidAttr *UA = S.mergeUuidAttr(D, AL, OrigStrRef, Guid);
7137
0
  if (UA)
7138
0
    D->addAttr(UA);
7139
0
}
7140
7141
0
static void handleHLSLNumThreadsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7142
0
  llvm::VersionTuple SMVersion =
7143
0
      S.Context.getTargetInfo().getTriple().getOSVersion();
7144
0
  uint32_t ZMax = 1024;
7145
0
  uint32_t ThreadMax = 1024;
7146
0
  if (SMVersion.getMajor() <= 4) {
7147
0
    ZMax = 1;
7148
0
    ThreadMax = 768;
7149
0
  } else if (SMVersion.getMajor() == 5) {
7150
0
    ZMax = 64;
7151
0
    ThreadMax = 1024;
7152
0
  }
7153
7154
0
  uint32_t X;
7155
0
  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), X))
7156
0
    return;
7157
0
  if (X > 1024) {
7158
0
    S.Diag(AL.getArgAsExpr(0)->getExprLoc(),
7159
0
           diag::err_hlsl_numthreads_argument_oor) << 0 << 1024;
7160
0
    return;
7161
0
  }
7162
0
  uint32_t Y;
7163
0
  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(1), Y))
7164
0
    return;
7165
0
  if (Y > 1024) {
7166
0
    S.Diag(AL.getArgAsExpr(1)->getExprLoc(),
7167
0
           diag::err_hlsl_numthreads_argument_oor) << 1 << 1024;
7168
0
    return;
7169
0
  }
7170
0
  uint32_t Z;
7171
0
  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(2), Z))
7172
0
    return;
7173
0
  if (Z > ZMax) {
7174
0
    S.Diag(AL.getArgAsExpr(2)->getExprLoc(),
7175
0
           diag::err_hlsl_numthreads_argument_oor) << 2 << ZMax;
7176
0
    return;
7177
0
  }
7178
7179
0
  if (X * Y * Z > ThreadMax) {
7180
0
    S.Diag(AL.getLoc(), diag::err_hlsl_numthreads_invalid) << ThreadMax;
7181
0
    return;
7182
0
  }
7183
7184
0
  HLSLNumThreadsAttr *NewAttr = S.mergeHLSLNumThreadsAttr(D, AL, X, Y, Z);
7185
0
  if (NewAttr)
7186
0
    D->addAttr(NewAttr);
7187
0
}
7188
7189
HLSLNumThreadsAttr *Sema::mergeHLSLNumThreadsAttr(Decl *D,
7190
                                                  const AttributeCommonInfo &AL,
7191
0
                                                  int X, int Y, int Z) {
7192
0
  if (HLSLNumThreadsAttr *NT = D->getAttr<HLSLNumThreadsAttr>()) {
7193
0
    if (NT->getX() != X || NT->getY() != Y || NT->getZ() != Z) {
7194
0
      Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
7195
0
      Diag(AL.getLoc(), diag::note_conflicting_attribute);
7196
0
    }
7197
0
    return nullptr;
7198
0
  }
7199
0
  return ::new (Context) HLSLNumThreadsAttr(Context, AL, X, Y, Z);
7200
0
}
7201
7202
0
static bool isLegalTypeForHLSLSV_DispatchThreadID(QualType T) {
7203
0
  if (!T->hasUnsignedIntegerRepresentation())
7204
0
    return false;
7205
0
  if (const auto *VT = T->getAs<VectorType>())
7206
0
    return VT->getNumElements() <= 3;
7207
0
  return true;
7208
0
}
7209
7210
static void handleHLSLSV_DispatchThreadIDAttr(Sema &S, Decl *D,
7211
0
                                              const ParsedAttr &AL) {
7212
  // FIXME: support semantic on field.
7213
  // See https://github.com/llvm/llvm-project/issues/57889.
7214
0
  if (isa<FieldDecl>(D)) {
7215
0
    S.Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_ast_node)
7216
0
        << AL << "parameter";
7217
0
    return;
7218
0
  }
7219
7220
0
  auto *VD = cast<ValueDecl>(D);
7221
0
  if (!isLegalTypeForHLSLSV_DispatchThreadID(VD->getType())) {
7222
0
    S.Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_type)
7223
0
        << AL << "uint/uint2/uint3";
7224
0
    return;
7225
0
  }
7226
7227
0
  D->addAttr(::new (S.Context) HLSLSV_DispatchThreadIDAttr(S.Context, AL));
7228
0
}
7229
7230
0
static void handleHLSLShaderAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7231
0
  StringRef Str;
7232
0
  SourceLocation ArgLoc;
7233
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7234
0
    return;
7235
7236
0
  HLSLShaderAttr::ShaderType ShaderType;
7237
0
  if (!HLSLShaderAttr::ConvertStrToShaderType(Str, ShaderType)) {
7238
0
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
7239
0
        << AL << Str << ArgLoc;
7240
0
    return;
7241
0
  }
7242
7243
  // FIXME: check function match the shader stage.
7244
7245
0
  HLSLShaderAttr *NewAttr = S.mergeHLSLShaderAttr(D, AL, ShaderType);
7246
0
  if (NewAttr)
7247
0
    D->addAttr(NewAttr);
7248
0
}
7249
7250
HLSLShaderAttr *
7251
Sema::mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
7252
0
                          HLSLShaderAttr::ShaderType ShaderType) {
7253
0
  if (HLSLShaderAttr *NT = D->getAttr<HLSLShaderAttr>()) {
7254
0
    if (NT->getType() != ShaderType) {
7255
0
      Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
7256
0
      Diag(AL.getLoc(), diag::note_conflicting_attribute);
7257
0
    }
7258
0
    return nullptr;
7259
0
  }
7260
0
  return HLSLShaderAttr::Create(Context, ShaderType, AL);
7261
0
}
7262
7263
static void handleHLSLResourceBindingAttr(Sema &S, Decl *D,
7264
0
                                          const ParsedAttr &AL) {
7265
0
  StringRef Space = "space0";
7266
0
  StringRef Slot = "";
7267
7268
0
  if (!AL.isArgIdent(0)) {
7269
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7270
0
        << AL << AANT_ArgumentIdentifier;
7271
0
    return;
7272
0
  }
7273
7274
0
  IdentifierLoc *Loc = AL.getArgAsIdent(0);
7275
0
  StringRef Str = Loc->Ident->getName();
7276
0
  SourceLocation ArgLoc = Loc->Loc;
7277
7278
0
  SourceLocation SpaceArgLoc;
7279
0
  if (AL.getNumArgs() == 2) {
7280
0
    Slot = Str;
7281
0
    if (!AL.isArgIdent(1)) {
7282
0
      S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7283
0
          << AL << AANT_ArgumentIdentifier;
7284
0
      return;
7285
0
    }
7286
7287
0
    IdentifierLoc *Loc = AL.getArgAsIdent(1);
7288
0
    Space = Loc->Ident->getName();
7289
0
    SpaceArgLoc = Loc->Loc;
7290
0
  } else {
7291
0
    Slot = Str;
7292
0
  }
7293
7294
  // Validate.
7295
0
  if (!Slot.empty()) {
7296
0
    switch (Slot[0]) {
7297
0
    case 'u':
7298
0
    case 'b':
7299
0
    case 's':
7300
0
    case 't':
7301
0
      break;
7302
0
    default:
7303
0
      S.Diag(ArgLoc, diag::err_hlsl_unsupported_register_type)
7304
0
          << Slot.substr(0, 1);
7305
0
      return;
7306
0
    }
7307
7308
0
    StringRef SlotNum = Slot.substr(1);
7309
0
    unsigned Num = 0;
7310
0
    if (SlotNum.getAsInteger(10, Num)) {
7311
0
      S.Diag(ArgLoc, diag::err_hlsl_unsupported_register_number);
7312
0
      return;
7313
0
    }
7314
0
  }
7315
7316
0
  if (!Space.starts_with("space")) {
7317
0
    S.Diag(SpaceArgLoc, diag::err_hlsl_expected_space) << Space;
7318
0
    return;
7319
0
  }
7320
0
  StringRef SpaceNum = Space.substr(5);
7321
0
  unsigned Num = 0;
7322
0
  if (SpaceNum.getAsInteger(10, Num)) {
7323
0
    S.Diag(SpaceArgLoc, diag::err_hlsl_expected_space) << Space;
7324
0
    return;
7325
0
  }
7326
7327
  // FIXME: check reg type match decl. Issue
7328
  // https://github.com/llvm/llvm-project/issues/57886.
7329
0
  HLSLResourceBindingAttr *NewAttr =
7330
0
      HLSLResourceBindingAttr::Create(S.getASTContext(), Slot, Space, AL);
7331
0
  if (NewAttr)
7332
0
    D->addAttr(NewAttr);
7333
0
}
7334
7335
static void handleHLSLParamModifierAttr(Sema &S, Decl *D,
7336
0
                                        const ParsedAttr &AL) {
7337
0
  HLSLParamModifierAttr *NewAttr = S.mergeHLSLParamModifierAttr(
7338
0
      D, AL,
7339
0
      static_cast<HLSLParamModifierAttr::Spelling>(AL.getSemanticSpelling()));
7340
0
  if (NewAttr)
7341
0
    D->addAttr(NewAttr);
7342
0
}
7343
7344
HLSLParamModifierAttr *
7345
Sema::mergeHLSLParamModifierAttr(Decl *D, const AttributeCommonInfo &AL,
7346
0
                                 HLSLParamModifierAttr::Spelling Spelling) {
7347
  // We can only merge an `in` attribute with an `out` attribute. All other
7348
  // combinations of duplicated attributes are ill-formed.
7349
0
  if (HLSLParamModifierAttr *PA = D->getAttr<HLSLParamModifierAttr>()) {
7350
0
    if ((PA->isIn() && Spelling == HLSLParamModifierAttr::Keyword_out) ||
7351
0
        (PA->isOut() && Spelling == HLSLParamModifierAttr::Keyword_in)) {
7352
0
      D->dropAttr<HLSLParamModifierAttr>();
7353
0
      SourceRange AdjustedRange = {PA->getLocation(), AL.getRange().getEnd()};
7354
0
      return HLSLParamModifierAttr::Create(
7355
0
          Context, /*MergedSpelling=*/true, AdjustedRange,
7356
0
          HLSLParamModifierAttr::Keyword_inout);
7357
0
    }
7358
0
    Diag(AL.getLoc(), diag::err_hlsl_duplicate_parameter_modifier) << AL;
7359
0
    Diag(PA->getLocation(), diag::note_conflicting_attribute);
7360
0
    return nullptr;
7361
0
  }
7362
0
  return HLSLParamModifierAttr::Create(Context, AL);
7363
0
}
7364
7365
0
static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7366
0
  if (!S.LangOpts.CPlusPlus) {
7367
0
    S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
7368
0
        << AL << AttributeLangSupport::C;
7369
0
    return;
7370
0
  }
7371
0
  MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
7372
0
      D, AL, /*BestCase=*/true, (MSInheritanceModel)AL.getSemanticSpelling());
7373
0
  if (IA) {
7374
0
    D->addAttr(IA);
7375
0
    S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
7376
0
  }
7377
0
}
7378
7379
0
static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7380
0
  const auto *VD = cast<VarDecl>(D);
7381
0
  if (!S.Context.getTargetInfo().isTLSSupported()) {
7382
0
    S.Diag(AL.getLoc(), diag::err_thread_unsupported);
7383
0
    return;
7384
0
  }
7385
0
  if (VD->getTSCSpec() != TSCS_unspecified) {
7386
0
    S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
7387
0
    return;
7388
0
  }
7389
0
  if (VD->hasLocalStorage()) {
7390
0
    S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
7391
0
    return;
7392
0
  }
7393
0
  D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL));
7394
0
}
7395
7396
0
static void handleMSConstexprAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7397
0
  if (!S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2022_3)) {
7398
0
    S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
7399
0
        << AL << AL.getRange();
7400
0
    return;
7401
0
  }
7402
0
  auto *FD = cast<FunctionDecl>(D);
7403
0
  if (FD->isConstexprSpecified() || FD->isConsteval()) {
7404
0
    S.Diag(AL.getLoc(), diag::err_ms_constexpr_cannot_be_applied)
7405
0
        << FD->isConsteval() << FD;
7406
0
    return;
7407
0
  }
7408
0
  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7409
0
    if (!S.getLangOpts().CPlusPlus20 && MD->isVirtual()) {
7410
0
      S.Diag(AL.getLoc(), diag::err_ms_constexpr_cannot_be_applied)
7411
0
          << /*virtual*/ 2 << MD;
7412
0
      return;
7413
0
    }
7414
0
  }
7415
0
  D->addAttr(::new (S.Context) MSConstexprAttr(S.Context, AL));
7416
0
}
7417
7418
0
static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7419
0
  SmallVector<StringRef, 4> Tags;
7420
0
  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
7421
0
    StringRef Tag;
7422
0
    if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
7423
0
      return;
7424
0
    Tags.push_back(Tag);
7425
0
  }
7426
7427
0
  if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
7428
0
    if (!NS->isInline()) {
7429
0
      S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
7430
0
      return;
7431
0
    }
7432
0
    if (NS->isAnonymousNamespace()) {
7433
0
      S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
7434
0
      return;
7435
0
    }
7436
0
    if (AL.getNumArgs() == 0)
7437
0
      Tags.push_back(NS->getName());
7438
0
  } else if (!AL.checkAtLeastNumArgs(S, 1))
7439
0
    return;
7440
7441
  // Store tags sorted and without duplicates.
7442
0
  llvm::sort(Tags);
7443
0
  Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
7444
7445
0
  D->addAttr(::new (S.Context)
7446
0
                 AbiTagAttr(S.Context, AL, Tags.data(), Tags.size()));
7447
0
}
7448
7449
0
static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7450
  // Check the attribute arguments.
7451
0
  if (AL.getNumArgs() > 1) {
7452
0
    S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
7453
0
    return;
7454
0
  }
7455
7456
0
  StringRef Str;
7457
0
  SourceLocation ArgLoc;
7458
7459
0
  if (AL.getNumArgs() == 0)
7460
0
    Str = "";
7461
0
  else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7462
0
    return;
7463
7464
0
  ARMInterruptAttr::InterruptType Kind;
7465
0
  if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
7466
0
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
7467
0
                                                                 << ArgLoc;
7468
0
    return;
7469
0
  }
7470
7471
0
  D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind));
7472
0
}
7473
7474
0
static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7475
  // MSP430 'interrupt' attribute is applied to
7476
  // a function with no parameters and void return type.
7477
0
  if (!isFunctionOrMethod(D)) {
7478
0
    S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7479
0
        << AL << AL.isRegularKeywordAttribute() << ExpectedFunctionOrMethod;
7480
0
    return;
7481
0
  }
7482
7483
0
  if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
7484
0
    S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7485
0
        << /*MSP430*/ 1 << 0;
7486
0
    return;
7487
0
  }
7488
7489
0
  if (!getFunctionOrMethodResultType(D)->isVoidType()) {
7490
0
    S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7491
0
        << /*MSP430*/ 1 << 1;
7492
0
    return;
7493
0
  }
7494
7495
  // The attribute takes one integer argument.
7496
0
  if (!AL.checkExactlyNumArgs(S, 1))
7497
0
    return;
7498
7499
0
  if (!AL.isArgExpr(0)) {
7500
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7501
0
        << AL << AANT_ArgumentIntegerConstant;
7502
0
    return;
7503
0
  }
7504
7505
0
  Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
7506
0
  std::optional<llvm::APSInt> NumParams = llvm::APSInt(32);
7507
0
  if (!(NumParams = NumParamsExpr->getIntegerConstantExpr(S.Context))) {
7508
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7509
0
        << AL << AANT_ArgumentIntegerConstant
7510
0
        << NumParamsExpr->getSourceRange();
7511
0
    return;
7512
0
  }
7513
  // The argument should be in range 0..63.
7514
0
  unsigned Num = NumParams->getLimitedValue(255);
7515
0
  if (Num > 63) {
7516
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
7517
0
        << AL << (int)NumParams->getSExtValue()
7518
0
        << NumParamsExpr->getSourceRange();
7519
0
    return;
7520
0
  }
7521
7522
0
  D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num));
7523
0
  D->addAttr(UsedAttr::CreateImplicit(S.Context));
7524
0
}
7525
7526
0
static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7527
  // Only one optional argument permitted.
7528
0
  if (AL.getNumArgs() > 1) {
7529
0
    S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
7530
0
    return;
7531
0
  }
7532
7533
0
  StringRef Str;
7534
0
  SourceLocation ArgLoc;
7535
7536
0
  if (AL.getNumArgs() == 0)
7537
0
    Str = "";
7538
0
  else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7539
0
    return;
7540
7541
  // Semantic checks for a function with the 'interrupt' attribute for MIPS:
7542
  // a) Must be a function.
7543
  // b) Must have no parameters.
7544
  // c) Must have the 'void' return type.
7545
  // d) Cannot have the 'mips16' attribute, as that instruction set
7546
  //    lacks the 'eret' instruction.
7547
  // e) The attribute itself must either have no argument or one of the
7548
  //    valid interrupt types, see [MipsInterruptDocs].
7549
7550
0
  if (!isFunctionOrMethod(D)) {
7551
0
    S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7552
0
        << AL << AL.isRegularKeywordAttribute() << ExpectedFunctionOrMethod;
7553
0
    return;
7554
0
  }
7555
7556
0
  if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
7557
0
    S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7558
0
        << /*MIPS*/ 0 << 0;
7559
0
    return;
7560
0
  }
7561
7562
0
  if (!getFunctionOrMethodResultType(D)->isVoidType()) {
7563
0
    S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7564
0
        << /*MIPS*/ 0 << 1;
7565
0
    return;
7566
0
  }
7567
7568
  // We still have to do this manually because the Interrupt attributes are
7569
  // a bit special due to sharing their spellings across targets.
7570
0
  if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
7571
0
    return;
7572
7573
0
  MipsInterruptAttr::InterruptType Kind;
7574
0
  if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
7575
0
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
7576
0
        << AL << "'" + std::string(Str) + "'";
7577
0
    return;
7578
0
  }
7579
7580
0
  D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind));
7581
0
}
7582
7583
0
static void handleM68kInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7584
0
  if (!AL.checkExactlyNumArgs(S, 1))
7585
0
    return;
7586
7587
0
  if (!AL.isArgExpr(0)) {
7588
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7589
0
        << AL << AANT_ArgumentIntegerConstant;
7590
0
    return;
7591
0
  }
7592
7593
  // FIXME: Check for decl - it should be void ()(void).
7594
7595
0
  Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
7596
0
  auto MaybeNumParams = NumParamsExpr->getIntegerConstantExpr(S.Context);
7597
0
  if (!MaybeNumParams) {
7598
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7599
0
        << AL << AANT_ArgumentIntegerConstant
7600
0
        << NumParamsExpr->getSourceRange();
7601
0
    return;
7602
0
  }
7603
7604
0
  unsigned Num = MaybeNumParams->getLimitedValue(255);
7605
0
  if ((Num & 1) || Num > 30) {
7606
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
7607
0
        << AL << (int)MaybeNumParams->getSExtValue()
7608
0
        << NumParamsExpr->getSourceRange();
7609
0
    return;
7610
0
  }
7611
7612
0
  D->addAttr(::new (S.Context) M68kInterruptAttr(S.Context, AL, Num));
7613
0
  D->addAttr(UsedAttr::CreateImplicit(S.Context));
7614
0
}
7615
7616
0
static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7617
  // Semantic checks for a function with the 'interrupt' attribute.
7618
  // a) Must be a function.
7619
  // b) Must have the 'void' return type.
7620
  // c) Must take 1 or 2 arguments.
7621
  // d) The 1st argument must be a pointer.
7622
  // e) The 2nd argument (if any) must be an unsigned integer.
7623
0
  if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
7624
0
      CXXMethodDecl::isStaticOverloadedOperator(
7625
0
          cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
7626
0
    S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
7627
0
        << AL << AL.isRegularKeywordAttribute()
7628
0
        << ExpectedFunctionWithProtoType;
7629
0
    return;
7630
0
  }
7631
  // Interrupt handler must have void return type.
7632
0
  if (!getFunctionOrMethodResultType(D)->isVoidType()) {
7633
0
    S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
7634
0
           diag::err_anyx86_interrupt_attribute)
7635
0
        << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7636
0
                ? 0
7637
0
                : 1)
7638
0
        << 0;
7639
0
    return;
7640
0
  }
7641
  // Interrupt handler must have 1 or 2 parameters.
7642
0
  unsigned NumParams = getFunctionOrMethodNumParams(D);
7643
0
  if (NumParams < 1 || NumParams > 2) {
7644
0
    S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
7645
0
        << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7646
0
                ? 0
7647
0
                : 1)
7648
0
        << 1;
7649
0
    return;
7650
0
  }
7651
  // The first argument must be a pointer.
7652
0
  if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
7653
0
    S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
7654
0
           diag::err_anyx86_interrupt_attribute)
7655
0
        << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7656
0
                ? 0
7657
0
                : 1)
7658
0
        << 2;
7659
0
    return;
7660
0
  }
7661
  // The second argument, if present, must be an unsigned integer.
7662
0
  unsigned TypeSize =
7663
0
      S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
7664
0
          ? 64
7665
0
          : 32;
7666
0
  if (NumParams == 2 &&
7667
0
      (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
7668
0
       S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
7669
0
    S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
7670
0
           diag::err_anyx86_interrupt_attribute)
7671
0
        << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7672
0
                ? 0
7673
0
                : 1)
7674
0
        << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
7675
0
    return;
7676
0
  }
7677
0
  D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL));
7678
0
  D->addAttr(UsedAttr::CreateImplicit(S.Context));
7679
0
}
7680
7681
0
static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7682
0
  if (!isFunctionOrMethod(D)) {
7683
0
    S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7684
0
        << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
7685
0
    return;
7686
0
  }
7687
7688
0
  if (!AL.checkExactlyNumArgs(S, 0))
7689
0
    return;
7690
7691
0
  handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
7692
0
}
7693
7694
0
static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7695
0
  if (!isFunctionOrMethod(D)) {
7696
0
    S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7697
0
        << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
7698
0
    return;
7699
0
  }
7700
7701
0
  if (!AL.checkExactlyNumArgs(S, 0))
7702
0
    return;
7703
7704
0
  handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
7705
0
}
7706
7707
0
static void handleBPFPreserveAIRecord(Sema &S, RecordDecl *RD) {
7708
  // Add preserve_access_index attribute to all fields and inner records.
7709
0
  for (auto *D : RD->decls()) {
7710
0
    if (D->hasAttr<BPFPreserveAccessIndexAttr>())
7711
0
      continue;
7712
7713
0
    D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S.Context));
7714
0
    if (auto *Rec = dyn_cast<RecordDecl>(D))
7715
0
      handleBPFPreserveAIRecord(S, Rec);
7716
0
  }
7717
0
}
7718
7719
static void handleBPFPreserveAccessIndexAttr(Sema &S, Decl *D,
7720
0
    const ParsedAttr &AL) {
7721
0
  auto *Rec = cast<RecordDecl>(D);
7722
0
  handleBPFPreserveAIRecord(S, Rec);
7723
0
  Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL));
7724
0
}
7725
7726
0
static bool hasBTFDeclTagAttr(Decl *D, StringRef Tag) {
7727
0
  for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
7728
0
    if (I->getBTFDeclTag() == Tag)
7729
0
      return true;
7730
0
  }
7731
0
  return false;
7732
0
}
7733
7734
0
static void handleBTFDeclTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7735
0
  StringRef Str;
7736
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
7737
0
    return;
7738
0
  if (hasBTFDeclTagAttr(D, Str))
7739
0
    return;
7740
7741
0
  D->addAttr(::new (S.Context) BTFDeclTagAttr(S.Context, AL, Str));
7742
0
}
7743
7744
0
BTFDeclTagAttr *Sema::mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL) {
7745
0
  if (hasBTFDeclTagAttr(D, AL.getBTFDeclTag()))
7746
0
    return nullptr;
7747
0
  return ::new (Context) BTFDeclTagAttr(Context, AL, AL.getBTFDeclTag());
7748
0
}
7749
7750
static void handleWebAssemblyExportNameAttr(Sema &S, Decl *D,
7751
0
                                            const ParsedAttr &AL) {
7752
0
  if (!isFunctionOrMethod(D)) {
7753
0
    S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7754
0
        << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
7755
0
    return;
7756
0
  }
7757
7758
0
  auto *FD = cast<FunctionDecl>(D);
7759
0
  if (FD->isThisDeclarationADefinition()) {
7760
0
    S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
7761
0
    return;
7762
0
  }
7763
7764
0
  StringRef Str;
7765
0
  SourceLocation ArgLoc;
7766
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7767
0
    return;
7768
7769
0
  D->addAttr(::new (S.Context) WebAssemblyExportNameAttr(S.Context, AL, Str));
7770
0
  D->addAttr(UsedAttr::CreateImplicit(S.Context));
7771
0
}
7772
7773
WebAssemblyImportModuleAttr *
7774
0
Sema::mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL) {
7775
0
  auto *FD = cast<FunctionDecl>(D);
7776
7777
0
  if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
7778
0
    if (ExistingAttr->getImportModule() == AL.getImportModule())
7779
0
      return nullptr;
7780
0
    Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 0
7781
0
      << ExistingAttr->getImportModule() << AL.getImportModule();
7782
0
    Diag(AL.getLoc(), diag::note_previous_attribute);
7783
0
    return nullptr;
7784
0
  }
7785
0
  if (FD->hasBody()) {
7786
0
    Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
7787
0
    return nullptr;
7788
0
  }
7789
0
  return ::new (Context) WebAssemblyImportModuleAttr(Context, AL,
7790
0
                                                     AL.getImportModule());
7791
0
}
7792
7793
WebAssemblyImportNameAttr *
7794
0
Sema::mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL) {
7795
0
  auto *FD = cast<FunctionDecl>(D);
7796
7797
0
  if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportNameAttr>()) {
7798
0
    if (ExistingAttr->getImportName() == AL.getImportName())
7799
0
      return nullptr;
7800
0
    Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 1
7801
0
      << ExistingAttr->getImportName() << AL.getImportName();
7802
0
    Diag(AL.getLoc(), diag::note_previous_attribute);
7803
0
    return nullptr;
7804
0
  }
7805
0
  if (FD->hasBody()) {
7806
0
    Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
7807
0
    return nullptr;
7808
0
  }
7809
0
  return ::new (Context) WebAssemblyImportNameAttr(Context, AL,
7810
0
                                                   AL.getImportName());
7811
0
}
7812
7813
static void
7814
0
handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7815
0
  auto *FD = cast<FunctionDecl>(D);
7816
7817
0
  StringRef Str;
7818
0
  SourceLocation ArgLoc;
7819
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7820
0
    return;
7821
0
  if (FD->hasBody()) {
7822
0
    S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
7823
0
    return;
7824
0
  }
7825
7826
0
  FD->addAttr(::new (S.Context)
7827
0
                  WebAssemblyImportModuleAttr(S.Context, AL, Str));
7828
0
}
7829
7830
static void
7831
0
handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7832
0
  auto *FD = cast<FunctionDecl>(D);
7833
7834
0
  StringRef Str;
7835
0
  SourceLocation ArgLoc;
7836
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7837
0
    return;
7838
0
  if (FD->hasBody()) {
7839
0
    S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
7840
0
    return;
7841
0
  }
7842
7843
0
  FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str));
7844
0
}
7845
7846
static void handleRISCVInterruptAttr(Sema &S, Decl *D,
7847
0
                                     const ParsedAttr &AL) {
7848
  // Warn about repeated attributes.
7849
0
  if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
7850
0
    S.Diag(AL.getRange().getBegin(),
7851
0
      diag::warn_riscv_repeated_interrupt_attribute);
7852
0
    S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
7853
0
    return;
7854
0
  }
7855
7856
  // Check the attribute argument. Argument is optional.
7857
0
  if (!AL.checkAtMostNumArgs(S, 1))
7858
0
    return;
7859
7860
0
  StringRef Str;
7861
0
  SourceLocation ArgLoc;
7862
7863
  // 'machine'is the default interrupt mode.
7864
0
  if (AL.getNumArgs() == 0)
7865
0
    Str = "machine";
7866
0
  else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
7867
0
    return;
7868
7869
  // Semantic checks for a function with the 'interrupt' attribute:
7870
  // - Must be a function.
7871
  // - Must have no parameters.
7872
  // - Must have the 'void' return type.
7873
  // - The attribute itself must either have no argument or one of the
7874
  //   valid interrupt types, see [RISCVInterruptDocs].
7875
7876
0
  if (D->getFunctionType() == nullptr) {
7877
0
    S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7878
0
        << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
7879
0
    return;
7880
0
  }
7881
7882
0
  if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
7883
0
    S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7884
0
      << /*RISC-V*/ 2 << 0;
7885
0
    return;
7886
0
  }
7887
7888
0
  if (!getFunctionOrMethodResultType(D)->isVoidType()) {
7889
0
    S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7890
0
      << /*RISC-V*/ 2 << 1;
7891
0
    return;
7892
0
  }
7893
7894
0
  RISCVInterruptAttr::InterruptType Kind;
7895
0
  if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
7896
0
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
7897
0
                                                                 << ArgLoc;
7898
0
    return;
7899
0
  }
7900
7901
0
  D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind));
7902
0
}
7903
7904
0
static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7905
  // Dispatch the interrupt attribute based on the current target.
7906
0
  switch (S.Context.getTargetInfo().getTriple().getArch()) {
7907
0
  case llvm::Triple::msp430:
7908
0
    handleMSP430InterruptAttr(S, D, AL);
7909
0
    break;
7910
0
  case llvm::Triple::mipsel:
7911
0
  case llvm::Triple::mips:
7912
0
    handleMipsInterruptAttr(S, D, AL);
7913
0
    break;
7914
0
  case llvm::Triple::m68k:
7915
0
    handleM68kInterruptAttr(S, D, AL);
7916
0
    break;
7917
0
  case llvm::Triple::x86:
7918
0
  case llvm::Triple::x86_64:
7919
0
    handleAnyX86InterruptAttr(S, D, AL);
7920
0
    break;
7921
0
  case llvm::Triple::avr:
7922
0
    handleAVRInterruptAttr(S, D, AL);
7923
0
    break;
7924
0
  case llvm::Triple::riscv32:
7925
0
  case llvm::Triple::riscv64:
7926
0
    handleRISCVInterruptAttr(S, D, AL);
7927
0
    break;
7928
0
  default:
7929
0
    handleARMInterruptAttr(S, D, AL);
7930
0
    break;
7931
0
  }
7932
0
}
7933
7934
static bool
7935
checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr,
7936
0
                                      const AMDGPUFlatWorkGroupSizeAttr &Attr) {
7937
  // Accept template arguments for now as they depend on something else.
7938
  // We'll get to check them when they eventually get instantiated.
7939
0
  if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
7940
0
    return false;
7941
7942
0
  uint32_t Min = 0;
7943
0
  if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
7944
0
    return true;
7945
7946
0
  uint32_t Max = 0;
7947
0
  if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
7948
0
    return true;
7949
7950
0
  if (Min == 0 && Max != 0) {
7951
0
    S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7952
0
        << &Attr << 0;
7953
0
    return true;
7954
0
  }
7955
0
  if (Min > Max) {
7956
0
    S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7957
0
        << &Attr << 1;
7958
0
    return true;
7959
0
  }
7960
7961
0
  return false;
7962
0
}
7963
7964
AMDGPUFlatWorkGroupSizeAttr *
7965
Sema::CreateAMDGPUFlatWorkGroupSizeAttr(const AttributeCommonInfo &CI,
7966
0
                                        Expr *MinExpr, Expr *MaxExpr) {
7967
0
  AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
7968
7969
0
  if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr))
7970
0
    return nullptr;
7971
0
  return ::new (Context)
7972
0
      AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr);
7973
0
}
7974
7975
void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl *D,
7976
                                          const AttributeCommonInfo &CI,
7977
0
                                          Expr *MinExpr, Expr *MaxExpr) {
7978
0
  if (auto *Attr = CreateAMDGPUFlatWorkGroupSizeAttr(CI, MinExpr, MaxExpr))
7979
0
    D->addAttr(Attr);
7980
0
}
7981
7982
static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
7983
0
                                              const ParsedAttr &AL) {
7984
0
  Expr *MinExpr = AL.getArgAsExpr(0);
7985
0
  Expr *MaxExpr = AL.getArgAsExpr(1);
7986
7987
0
  S.addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr);
7988
0
}
7989
7990
static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
7991
                                           Expr *MaxExpr,
7992
0
                                           const AMDGPUWavesPerEUAttr &Attr) {
7993
0
  if (S.DiagnoseUnexpandedParameterPack(MinExpr) ||
7994
0
      (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr)))
7995
0
    return true;
7996
7997
  // Accept template arguments for now as they depend on something else.
7998
  // We'll get to check them when they eventually get instantiated.
7999
0
  if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
8000
0
    return false;
8001
8002
0
  uint32_t Min = 0;
8003
0
  if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
8004
0
    return true;
8005
8006
0
  uint32_t Max = 0;
8007
0
  if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
8008
0
    return true;
8009
8010
0
  if (Min == 0 && Max != 0) {
8011
0
    S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
8012
0
        << &Attr << 0;
8013
0
    return true;
8014
0
  }
8015
0
  if (Max != 0 && Min > Max) {
8016
0
    S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
8017
0
        << &Attr << 1;
8018
0
    return true;
8019
0
  }
8020
8021
0
  return false;
8022
0
}
8023
8024
AMDGPUWavesPerEUAttr *
8025
Sema::CreateAMDGPUWavesPerEUAttr(const AttributeCommonInfo &CI, Expr *MinExpr,
8026
0
                                 Expr *MaxExpr) {
8027
0
  AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
8028
8029
0
  if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr))
8030
0
    return nullptr;
8031
8032
0
  return ::new (Context) AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr);
8033
0
}
8034
8035
void Sema::addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
8036
0
                                   Expr *MinExpr, Expr *MaxExpr) {
8037
0
  if (auto *Attr = CreateAMDGPUWavesPerEUAttr(CI, MinExpr, MaxExpr))
8038
0
    D->addAttr(Attr);
8039
0
}
8040
8041
0
static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8042
0
  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
8043
0
    return;
8044
8045
0
  Expr *MinExpr = AL.getArgAsExpr(0);
8046
0
  Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
8047
8048
0
  S.addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr);
8049
0
}
8050
8051
0
static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8052
0
  uint32_t NumSGPR = 0;
8053
0
  Expr *NumSGPRExpr = AL.getArgAsExpr(0);
8054
0
  if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
8055
0
    return;
8056
8057
0
  D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR));
8058
0
}
8059
8060
0
static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8061
0
  uint32_t NumVGPR = 0;
8062
0
  Expr *NumVGPRExpr = AL.getArgAsExpr(0);
8063
0
  if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
8064
0
    return;
8065
8066
0
  D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR));
8067
0
}
8068
8069
static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
8070
0
                                              const ParsedAttr &AL) {
8071
  // If we try to apply it to a function pointer, don't warn, but don't
8072
  // do anything, either. It doesn't matter anyway, because there's nothing
8073
  // special about calling a force_align_arg_pointer function.
8074
0
  const auto *VD = dyn_cast<ValueDecl>(D);
8075
0
  if (VD && VD->getType()->isFunctionPointerType())
8076
0
    return;
8077
  // Also don't warn on function pointer typedefs.
8078
0
  const auto *TD = dyn_cast<TypedefNameDecl>(D);
8079
0
  if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
8080
0
    TD->getUnderlyingType()->isFunctionType()))
8081
0
    return;
8082
  // Attribute can only be applied to function types.
8083
0
  if (!isa<FunctionDecl>(D)) {
8084
0
    S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
8085
0
        << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
8086
0
    return;
8087
0
  }
8088
8089
0
  D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL));
8090
0
}
8091
8092
0
static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
8093
0
  uint32_t Version;
8094
0
  Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
8095
0
  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
8096
0
    return;
8097
8098
  // TODO: Investigate what happens with the next major version of MSVC.
8099
0
  if (Version != LangOptions::MSVC2015 / 100) {
8100
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
8101
0
        << AL << Version << VersionExpr->getSourceRange();
8102
0
    return;
8103
0
  }
8104
8105
  // The attribute expects a "major" version number like 19, but new versions of
8106
  // MSVC have moved to updating the "minor", or less significant numbers, so we
8107
  // have to multiply by 100 now.
8108
0
  Version *= 100;
8109
8110
0
  D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version));
8111
0
}
8112
8113
DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D,
8114
0
                                        const AttributeCommonInfo &CI) {
8115
0
  if (D->hasAttr<DLLExportAttr>()) {
8116
0
    Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'";
8117
0
    return nullptr;
8118
0
  }
8119
8120
0
  if (D->hasAttr<DLLImportAttr>())
8121
0
    return nullptr;
8122
8123
0
  return ::new (Context) DLLImportAttr(Context, CI);
8124
0
}
8125
8126
DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D,
8127
0
                                        const AttributeCommonInfo &CI) {
8128
0
  if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
8129
0
    Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
8130
0
    D->dropAttr<DLLImportAttr>();
8131
0
  }
8132
8133
0
  if (D->hasAttr<DLLExportAttr>())
8134
0
    return nullptr;
8135
8136
0
  return ::new (Context) DLLExportAttr(Context, CI);
8137
0
}
8138
8139
0
static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
8140
0
  if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
8141
0
      (S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
8142
0
    S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
8143
0
    return;
8144
0
  }
8145
8146
0
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
8147
0
    if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
8148
0
        !(S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
8149
      // MinGW doesn't allow dllimport on inline functions.
8150
0
      S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
8151
0
          << A;
8152
0
      return;
8153
0
    }
8154
0
  }
8155
8156
0
  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
8157
0
    if ((S.Context.getTargetInfo().shouldDLLImportComdatSymbols()) &&
8158
0
        MD->getParent()->isLambda()) {
8159
0
      S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
8160
0
      return;
8161
0
    }
8162
0
  }
8163
8164
0
  Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
8165
0
                      ? (Attr *)S.mergeDLLExportAttr(D, A)
8166
0
                      : (Attr *)S.mergeDLLImportAttr(D, A);
8167
0
  if (NewAttr)
8168
0
    D->addAttr(NewAttr);
8169
0
}
8170
8171
MSInheritanceAttr *
8172
Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI,
8173
                             bool BestCase,
8174
0
                             MSInheritanceModel Model) {
8175
0
  if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
8176
0
    if (IA->getInheritanceModel() == Model)
8177
0
      return nullptr;
8178
0
    Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
8179
0
        << 1 /*previous declaration*/;
8180
0
    Diag(CI.getLoc(), diag::note_previous_ms_inheritance);
8181
0
    D->dropAttr<MSInheritanceAttr>();
8182
0
  }
8183
8184
0
  auto *RD = cast<CXXRecordDecl>(D);
8185
0
  if (RD->hasDefinition()) {
8186
0
    if (checkMSInheritanceAttrOnDefinition(RD, CI.getRange(), BestCase,
8187
0
                                           Model)) {
8188
0
      return nullptr;
8189
0
    }
8190
0
  } else {
8191
0
    if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
8192
0
      Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
8193
0
          << 1 /*partial specialization*/;
8194
0
      return nullptr;
8195
0
    }
8196
0
    if (RD->getDescribedClassTemplate()) {
8197
0
      Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
8198
0
          << 0 /*primary template*/;
8199
0
      return nullptr;
8200
0
    }
8201
0
  }
8202
8203
0
  return ::new (Context) MSInheritanceAttr(Context, CI, BestCase);
8204
0
}
8205
8206
0
static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8207
  // The capability attributes take a single string parameter for the name of
8208
  // the capability they represent. The lockable attribute does not take any
8209
  // parameters. However, semantically, both attributes represent the same
8210
  // concept, and so they use the same semantic attribute. Eventually, the
8211
  // lockable attribute will be removed.
8212
  //
8213
  // For backward compatibility, any capability which has no specified string
8214
  // literal will be considered a "mutex."
8215
0
  StringRef N("mutex");
8216
0
  SourceLocation LiteralLoc;
8217
0
  if (AL.getKind() == ParsedAttr::AT_Capability &&
8218
0
      !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
8219
0
    return;
8220
8221
0
  D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N));
8222
0
}
8223
8224
0
static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8225
0
  SmallVector<Expr*, 1> Args;
8226
0
  if (!checkLockFunAttrCommon(S, D, AL, Args))
8227
0
    return;
8228
8229
0
  D->addAttr(::new (S.Context)
8230
0
                 AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size()));
8231
0
}
8232
8233
static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
8234
0
                                        const ParsedAttr &AL) {
8235
0
  SmallVector<Expr*, 1> Args;
8236
0
  if (!checkLockFunAttrCommon(S, D, AL, Args))
8237
0
    return;
8238
8239
0
  D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(),
8240
0
                                                     Args.size()));
8241
0
}
8242
8243
static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
8244
0
                                           const ParsedAttr &AL) {
8245
0
  SmallVector<Expr*, 2> Args;
8246
0
  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
8247
0
    return;
8248
8249
0
  D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(
8250
0
      S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
8251
0
}
8252
8253
static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
8254
0
                                        const ParsedAttr &AL) {
8255
  // Check that all arguments are lockable objects.
8256
0
  SmallVector<Expr *, 1> Args;
8257
0
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
8258
8259
0
  D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(),
8260
0
                                                     Args.size()));
8261
0
}
8262
8263
static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
8264
0
                                         const ParsedAttr &AL) {
8265
0
  if (!AL.checkAtLeastNumArgs(S, 1))
8266
0
    return;
8267
8268
  // check that all arguments are lockable objects
8269
0
  SmallVector<Expr*, 1> Args;
8270
0
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
8271
0
  if (Args.empty())
8272
0
    return;
8273
8274
0
  RequiresCapabilityAttr *RCA = ::new (S.Context)
8275
0
      RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size());
8276
8277
0
  D->addAttr(RCA);
8278
0
}
8279
8280
0
static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8281
0
  if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
8282
0
    if (NSD->isAnonymousNamespace()) {
8283
0
      S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
8284
      // Do not want to attach the attribute to the namespace because that will
8285
      // cause confusing diagnostic reports for uses of declarations within the
8286
      // namespace.
8287
0
      return;
8288
0
    }
8289
0
  } else if (isa<UsingDecl, UnresolvedUsingTypenameDecl,
8290
0
                 UnresolvedUsingValueDecl>(D)) {
8291
0
    S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
8292
0
        << AL;
8293
0
    return;
8294
0
  }
8295
8296
  // Handle the cases where the attribute has a text message.
8297
0
  StringRef Str, Replacement;
8298
0
  if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
8299
0
      !S.checkStringLiteralArgumentAttr(AL, 0, Str))
8300
0
    return;
8301
8302
  // Support a single optional message only for Declspec and [[]] spellings.
8303
0
  if (AL.isDeclspecAttribute() || AL.isStandardAttributeSyntax())
8304
0
    AL.checkAtMostNumArgs(S, 1);
8305
0
  else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
8306
0
           !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
8307
0
    return;
8308
8309
0
  if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
8310
0
    S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
8311
8312
0
  D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement));
8313
0
}
8314
8315
0
static bool isGlobalVar(const Decl *D) {
8316
0
  if (const auto *S = dyn_cast<VarDecl>(D))
8317
0
    return S->hasGlobalStorage();
8318
0
  return false;
8319
0
}
8320
8321
0
static bool isSanitizerAttributeAllowedOnGlobals(StringRef Sanitizer) {
8322
0
  return Sanitizer == "address" || Sanitizer == "hwaddress" ||
8323
0
         Sanitizer == "memtag";
8324
0
}
8325
8326
0
static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8327
0
  if (!AL.checkAtLeastNumArgs(S, 1))
8328
0
    return;
8329
8330
0
  std::vector<StringRef> Sanitizers;
8331
8332
0
  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
8333
0
    StringRef SanitizerName;
8334
0
    SourceLocation LiteralLoc;
8335
8336
0
    if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
8337
0
      return;
8338
8339
0
    if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
8340
0
            SanitizerMask() &&
8341
0
        SanitizerName != "coverage")
8342
0
      S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
8343
0
    else if (isGlobalVar(D) && !isSanitizerAttributeAllowedOnGlobals(SanitizerName))
8344
0
      S.Diag(D->getLocation(), diag::warn_attribute_type_not_supported_global)
8345
0
          << AL << SanitizerName;
8346
0
    Sanitizers.push_back(SanitizerName);
8347
0
  }
8348
8349
0
  D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(),
8350
0
                                              Sanitizers.size()));
8351
0
}
8352
8353
static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
8354
0
                                         const ParsedAttr &AL) {
8355
0
  StringRef AttrName = AL.getAttrName()->getName();
8356
0
  normalizeName(AttrName);
8357
0
  StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
8358
0
                                .Case("no_address_safety_analysis", "address")
8359
0
                                .Case("no_sanitize_address", "address")
8360
0
                                .Case("no_sanitize_thread", "thread")
8361
0
                                .Case("no_sanitize_memory", "memory");
8362
0
  if (isGlobalVar(D) && SanitizerName != "address")
8363
0
    S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8364
0
        << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
8365
8366
  // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
8367
  // NoSanitizeAttr object; but we need to calculate the correct spelling list
8368
  // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
8369
  // has the same spellings as the index for NoSanitizeAttr. We don't have a
8370
  // general way to "translate" between the two, so this hack attempts to work
8371
  // around the issue with hard-coded indices. This is critical for calling
8372
  // getSpelling() or prettyPrint() on the resulting semantic attribute object
8373
  // without failing assertions.
8374
0
  unsigned TranslatedSpellingIndex = 0;
8375
0
  if (AL.isStandardAttributeSyntax())
8376
0
    TranslatedSpellingIndex = 1;
8377
8378
0
  AttributeCommonInfo Info = AL;
8379
0
  Info.setAttributeSpellingListIndex(TranslatedSpellingIndex);
8380
0
  D->addAttr(::new (S.Context)
8381
0
                 NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
8382
0
}
8383
8384
0
static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8385
0
  if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
8386
0
    D->addAttr(Internal);
8387
0
}
8388
8389
0
static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8390
0
  if (S.LangOpts.getOpenCLCompatibleVersion() < 200)
8391
0
    S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
8392
0
        << AL << "2.0" << 1;
8393
0
  else
8394
0
    S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
8395
0
        << AL << S.LangOpts.getOpenCLVersionString();
8396
0
}
8397
8398
0
static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8399
0
  if (D->isInvalidDecl())
8400
0
    return;
8401
8402
  // Check if there is only one access qualifier.
8403
0
  if (D->hasAttr<OpenCLAccessAttr>()) {
8404
0
    if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
8405
0
        AL.getSemanticSpelling()) {
8406
0
      S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
8407
0
          << AL.getAttrName()->getName() << AL.getRange();
8408
0
    } else {
8409
0
      S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
8410
0
          << D->getSourceRange();
8411
0
      D->setInvalidDecl(true);
8412
0
      return;
8413
0
    }
8414
0
  }
8415
8416
  // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that
8417
  // an image object can be read and written. OpenCL v2.0 s6.13.6 - A kernel
8418
  // cannot read from and write to the same pipe object. Using the read_write
8419
  // (or __read_write) qualifier with the pipe qualifier is a compilation error.
8420
  // OpenCL v3.0 s6.8 - For OpenCL C 2.0, or with the
8421
  // __opencl_c_read_write_images feature, image objects specified as arguments
8422
  // to a kernel can additionally be declared to be read-write.
8423
  // C++ for OpenCL 1.0 inherits rule from OpenCL C v2.0.
8424
  // C++ for OpenCL 2021 inherits rule from OpenCL C v3.0.
8425
0
  if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
8426
0
    const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
8427
0
    if (AL.getAttrName()->getName().contains("read_write")) {
8428
0
      bool ReadWriteImagesUnsupported =
8429
0
          (S.getLangOpts().getOpenCLCompatibleVersion() < 200) ||
8430
0
          (S.getLangOpts().getOpenCLCompatibleVersion() == 300 &&
8431
0
           !S.getOpenCLOptions().isSupported("__opencl_c_read_write_images",
8432
0
                                             S.getLangOpts()));
8433
0
      if (ReadWriteImagesUnsupported || DeclTy->isPipeType()) {
8434
0
        S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
8435
0
            << AL << PDecl->getType() << DeclTy->isImageType();
8436
0
        D->setInvalidDecl(true);
8437
0
        return;
8438
0
      }
8439
0
    }
8440
0
  }
8441
8442
0
  D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL));
8443
0
}
8444
8445
0
static void handleZeroCallUsedRegsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8446
  // Check that the argument is a string literal.
8447
0
  StringRef KindStr;
8448
0
  SourceLocation LiteralLoc;
8449
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, KindStr, &LiteralLoc))
8450
0
    return;
8451
8452
0
  ZeroCallUsedRegsAttr::ZeroCallUsedRegsKind Kind;
8453
0
  if (!ZeroCallUsedRegsAttr::ConvertStrToZeroCallUsedRegsKind(KindStr, Kind)) {
8454
0
    S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
8455
0
        << AL << KindStr;
8456
0
    return;
8457
0
  }
8458
8459
0
  D->dropAttr<ZeroCallUsedRegsAttr>();
8460
0
  D->addAttr(ZeroCallUsedRegsAttr::Create(S.Context, Kind, AL));
8461
0
}
8462
8463
0
static void handleCountedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8464
0
  if (!AL.isArgIdent(0)) {
8465
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
8466
0
        << AL << AANT_ArgumentIdentifier;
8467
0
    return;
8468
0
  }
8469
8470
0
  IdentifierLoc *IL = AL.getArgAsIdent(0);
8471
0
  CountedByAttr *CBA =
8472
0
      ::new (S.Context) CountedByAttr(S.Context, AL, IL->Ident);
8473
0
  CBA->setCountedByFieldLoc(IL->Loc);
8474
0
  D->addAttr(CBA);
8475
0
}
8476
8477
static const FieldDecl *
8478
FindFieldInTopLevelOrAnonymousStruct(const RecordDecl *RD,
8479
0
                                     const IdentifierInfo *FieldName) {
8480
0
  for (const Decl *D : RD->decls()) {
8481
0
    if (const auto *FD = dyn_cast<FieldDecl>(D))
8482
0
      if (FD->getName() == FieldName->getName())
8483
0
        return FD;
8484
8485
0
    if (const auto *R = dyn_cast<RecordDecl>(D))
8486
0
      if (const FieldDecl *FD =
8487
0
              FindFieldInTopLevelOrAnonymousStruct(R, FieldName))
8488
0
        return FD;
8489
0
  }
8490
8491
0
  return nullptr;
8492
0
}
8493
8494
0
bool Sema::CheckCountedByAttr(Scope *S, const FieldDecl *FD) {
8495
0
  LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
8496
0
      LangOptions::StrictFlexArraysLevelKind::IncompleteOnly;
8497
0
  if (!Decl::isFlexibleArrayMemberLike(Context, FD, FD->getType(),
8498
0
                                       StrictFlexArraysLevel, true)) {
8499
    // The "counted_by" attribute must be on a flexible array member.
8500
0
    SourceRange SR = FD->getLocation();
8501
0
    Diag(SR.getBegin(), diag::err_counted_by_attr_not_on_flexible_array_member)
8502
0
        << SR;
8503
0
    return true;
8504
0
  }
8505
8506
0
  const auto *CBA = FD->getAttr<CountedByAttr>();
8507
0
  const IdentifierInfo *FieldName = CBA->getCountedByField();
8508
8509
0
  auto GetNonAnonStructOrUnion = [](const RecordDecl *RD) {
8510
0
    while (RD && !RD->getDeclName())
8511
0
      if (const auto *R = dyn_cast<RecordDecl>(RD->getDeclContext()))
8512
0
        RD = R;
8513
0
      else
8514
0
        break;
8515
8516
0
    return RD;
8517
0
  };
8518
8519
0
  const RecordDecl *EnclosingRD = GetNonAnonStructOrUnion(FD->getParent());
8520
0
  const FieldDecl *CountFD =
8521
0
      FindFieldInTopLevelOrAnonymousStruct(EnclosingRD, FieldName);
8522
8523
0
  if (!CountFD) {
8524
0
    DeclarationNameInfo NameInfo(FieldName,
8525
0
                                 CBA->getCountedByFieldLoc().getBegin());
8526
0
    LookupResult MemResult(*this, NameInfo, Sema::LookupMemberName);
8527
0
    LookupName(MemResult, S);
8528
8529
0
    if (!MemResult.empty()) {
8530
0
      SourceRange SR = CBA->getCountedByFieldLoc();
8531
0
      Diag(SR.getBegin(), diag::err_flexible_array_count_not_in_same_struct)
8532
0
          << CBA->getCountedByField() << SR;
8533
8534
0
      if (auto *ND = MemResult.getAsSingle<NamedDecl>()) {
8535
0
        SR = ND->getLocation();
8536
0
        Diag(SR.getBegin(), diag::note_flexible_array_counted_by_attr_field)
8537
0
            << ND << SR;
8538
0
      }
8539
8540
0
      return true;
8541
0
    } else {
8542
      // The "counted_by" field needs to exist in the struct.
8543
0
      LookupResult OrdResult(*this, NameInfo, Sema::LookupOrdinaryName);
8544
0
      LookupName(OrdResult, S);
8545
8546
0
      if (!OrdResult.empty()) {
8547
0
        SourceRange SR = FD->getLocation();
8548
0
        Diag(SR.getBegin(), diag::err_counted_by_must_be_in_structure)
8549
0
            << FieldName << SR;
8550
8551
0
        if (auto *ND = OrdResult.getAsSingle<NamedDecl>()) {
8552
0
          SR = ND->getLocation();
8553
0
          Diag(SR.getBegin(), diag::note_flexible_array_counted_by_attr_field)
8554
0
              << ND << SR;
8555
0
        }
8556
8557
0
        return true;
8558
0
      }
8559
0
    }
8560
8561
0
    CXXScopeSpec SS;
8562
0
    DeclFilterCCC<FieldDecl> Filter(FieldName);
8563
0
    return DiagnoseEmptyLookup(S, SS, MemResult, Filter, nullptr, std::nullopt,
8564
0
                               const_cast<DeclContext *>(FD->getDeclContext()));
8565
0
  }
8566
8567
0
  if (CountFD->hasAttr<CountedByAttr>()) {
8568
    // The "counted_by" field can't point to the flexible array member.
8569
0
    SourceRange SR = CBA->getCountedByFieldLoc();
8570
0
    Diag(SR.getBegin(), diag::err_counted_by_attr_refers_to_flexible_array)
8571
0
        << CBA->getCountedByField() << SR;
8572
0
    return true;
8573
0
  }
8574
8575
0
  if (!CountFD->getType()->isIntegerType() ||
8576
0
      CountFD->getType()->isBooleanType()) {
8577
    // The "counted_by" field must have an integer type.
8578
0
    SourceRange SR = CBA->getCountedByFieldLoc();
8579
0
    Diag(SR.getBegin(),
8580
0
         diag::err_flexible_array_counted_by_attr_field_not_integer)
8581
0
        << CBA->getCountedByField() << SR;
8582
8583
0
    SR = CountFD->getLocation();
8584
0
    Diag(SR.getBegin(), diag::note_flexible_array_counted_by_attr_field)
8585
0
        << CountFD << SR;
8586
0
    return true;
8587
0
  }
8588
8589
0
  return false;
8590
0
}
8591
8592
static void handleFunctionReturnThunksAttr(Sema &S, Decl *D,
8593
0
                                           const ParsedAttr &AL) {
8594
0
  StringRef KindStr;
8595
0
  SourceLocation LiteralLoc;
8596
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, KindStr, &LiteralLoc))
8597
0
    return;
8598
8599
0
  FunctionReturnThunksAttr::Kind Kind;
8600
0
  if (!FunctionReturnThunksAttr::ConvertStrToKind(KindStr, Kind)) {
8601
0
    S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
8602
0
        << AL << KindStr;
8603
0
    return;
8604
0
  }
8605
  // FIXME: it would be good to better handle attribute merging rather than
8606
  // silently replacing the existing attribute, so long as it does not break
8607
  // the expected codegen tests.
8608
0
  D->dropAttr<FunctionReturnThunksAttr>();
8609
0
  D->addAttr(FunctionReturnThunksAttr::Create(S.Context, Kind, AL));
8610
0
}
8611
8612
static void handleAvailableOnlyInDefaultEvalMethod(Sema &S, Decl *D,
8613
0
                                                   const ParsedAttr &AL) {
8614
0
  assert(isa<TypedefNameDecl>(D) && "This attribute only applies to a typedef");
8615
0
  handleSimpleAttribute<AvailableOnlyInDefaultEvalMethodAttr>(S, D, AL);
8616
0
}
8617
8618
0
static void handleNoMergeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8619
0
  auto *VDecl = dyn_cast<VarDecl>(D);
8620
0
  if (VDecl && !VDecl->isFunctionPointerType()) {
8621
0
    S.Diag(AL.getLoc(), diag::warn_attribute_ignored_non_function_pointer)
8622
0
        << AL << VDecl;
8623
0
    return;
8624
0
  }
8625
0
  D->addAttr(NoMergeAttr::Create(S.Context, AL));
8626
0
}
8627
8628
0
static void handleNoUniqueAddressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8629
0
  D->addAttr(NoUniqueAddressAttr::Create(S.Context, AL));
8630
0
}
8631
8632
0
static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8633
  // The 'sycl_kernel' attribute applies only to function templates.
8634
0
  const auto *FD = cast<FunctionDecl>(D);
8635
0
  const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate();
8636
0
  assert(FT && "Function template is expected");
8637
8638
  // Function template must have at least two template parameters.
8639
0
  const TemplateParameterList *TL = FT->getTemplateParameters();
8640
0
  if (TL->size() < 2) {
8641
0
    S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params);
8642
0
    return;
8643
0
  }
8644
8645
  // Template parameters must be typenames.
8646
0
  for (unsigned I = 0; I < 2; ++I) {
8647
0
    const NamedDecl *TParam = TL->getParam(I);
8648
0
    if (isa<NonTypeTemplateParmDecl>(TParam)) {
8649
0
      S.Diag(FT->getLocation(),
8650
0
             diag::warn_sycl_kernel_invalid_template_param_type);
8651
0
      return;
8652
0
    }
8653
0
  }
8654
8655
  // Function must have at least one argument.
8656
0
  if (getFunctionOrMethodNumParams(D) != 1) {
8657
0
    S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_function_params);
8658
0
    return;
8659
0
  }
8660
8661
  // Function must return void.
8662
0
  QualType RetTy = getFunctionOrMethodResultType(D);
8663
0
  if (!RetTy->isVoidType()) {
8664
0
    S.Diag(FT->getLocation(), diag::warn_sycl_kernel_return_type);
8665
0
    return;
8666
0
  }
8667
8668
0
  handleSimpleAttribute<SYCLKernelAttr>(S, D, AL);
8669
0
}
8670
8671
0
static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
8672
0
  if (!cast<VarDecl>(D)->hasGlobalStorage()) {
8673
0
    S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
8674
0
        << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
8675
0
    return;
8676
0
  }
8677
8678
0
  if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
8679
0
    handleSimpleAttribute<AlwaysDestroyAttr>(S, D, A);
8680
0
  else
8681
0
    handleSimpleAttribute<NoDestroyAttr>(S, D, A);
8682
0
}
8683
8684
0
static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8685
0
  assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
8686
0
         "uninitialized is only valid on automatic duration variables");
8687
0
  D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL));
8688
0
}
8689
8690
static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
8691
0
                                        bool DiagnoseFailure) {
8692
0
  QualType Ty = VD->getType();
8693
0
  if (!Ty->isObjCRetainableType()) {
8694
0
    if (DiagnoseFailure) {
8695
0
      S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
8696
0
          << 0;
8697
0
    }
8698
0
    return false;
8699
0
  }
8700
8701
0
  Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
8702
8703
  // Sema::inferObjCARCLifetime must run after processing decl attributes
8704
  // (because __block lowers to an attribute), so if the lifetime hasn't been
8705
  // explicitly specified, infer it locally now.
8706
0
  if (LifetimeQual == Qualifiers::OCL_None)
8707
0
    LifetimeQual = Ty->getObjCARCImplicitLifetime();
8708
8709
  // The attributes only really makes sense for __strong variables; ignore any
8710
  // attempts to annotate a parameter with any other lifetime qualifier.
8711
0
  if (LifetimeQual != Qualifiers::OCL_Strong) {
8712
0
    if (DiagnoseFailure) {
8713
0
      S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
8714
0
          << 1;
8715
0
    }
8716
0
    return false;
8717
0
  }
8718
8719
  // Tampering with the type of a VarDecl here is a bit of a hack, but we need
8720
  // to ensure that the variable is 'const' so that we can error on
8721
  // modification, which can otherwise over-release.
8722
0
  VD->setType(Ty.withConst());
8723
0
  VD->setARCPseudoStrong(true);
8724
0
  return true;
8725
0
}
8726
8727
static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
8728
0
                                             const ParsedAttr &AL) {
8729
0
  if (auto *VD = dyn_cast<VarDecl>(D)) {
8730
0
    assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
8731
0
    if (!VD->hasLocalStorage()) {
8732
0
      S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
8733
0
          << 0;
8734
0
      return;
8735
0
    }
8736
8737
0
    if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
8738
0
      return;
8739
8740
0
    handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
8741
0
    return;
8742
0
  }
8743
8744
  // If D is a function-like declaration (method, block, or function), then we
8745
  // make every parameter psuedo-strong.
8746
0
  unsigned NumParams =
8747
0
      hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0;
8748
0
  for (unsigned I = 0; I != NumParams; ++I) {
8749
0
    auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
8750
0
    QualType Ty = PVD->getType();
8751
8752
    // If a user wrote a parameter with __strong explicitly, then assume they
8753
    // want "real" strong semantics for that parameter. This works because if
8754
    // the parameter was written with __strong, then the strong qualifier will
8755
    // be non-local.
8756
0
    if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
8757
0
        Qualifiers::OCL_Strong)
8758
0
      continue;
8759
8760
0
    tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
8761
0
  }
8762
0
  handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
8763
0
}
8764
8765
0
static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8766
  // Check that the return type is a `typedef int kern_return_t` or a typedef
8767
  // around it, because otherwise MIG convention checks make no sense.
8768
  // BlockDecl doesn't store a return type, so it's annoying to check,
8769
  // so let's skip it for now.
8770
0
  if (!isa<BlockDecl>(D)) {
8771
0
    QualType T = getFunctionOrMethodResultType(D);
8772
0
    bool IsKernReturnT = false;
8773
0
    while (const auto *TT = T->getAs<TypedefType>()) {
8774
0
      IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
8775
0
      T = TT->desugar();
8776
0
    }
8777
0
    if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
8778
0
      S.Diag(D->getBeginLoc(),
8779
0
             diag::warn_mig_server_routine_does_not_return_kern_return_t);
8780
0
      return;
8781
0
    }
8782
0
  }
8783
8784
0
  handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL);
8785
0
}
8786
8787
0
static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8788
  // Warn if the return type is not a pointer or reference type.
8789
0
  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8790
0
    QualType RetTy = FD->getReturnType();
8791
0
    if (!RetTy->isPointerType() && !RetTy->isReferenceType()) {
8792
0
      S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer)
8793
0
          << AL.getRange() << RetTy;
8794
0
      return;
8795
0
    }
8796
0
  }
8797
8798
0
  handleSimpleAttribute<MSAllocatorAttr>(S, D, AL);
8799
0
}
8800
8801
0
static void handleAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8802
0
  if (AL.isUsedAsTypeAttr())
8803
0
    return;
8804
  // Warn if the parameter is definitely not an output parameter.
8805
0
  if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
8806
0
    if (PVD->getType()->isIntegerType()) {
8807
0
      S.Diag(AL.getLoc(), diag::err_attribute_output_parameter)
8808
0
          << AL.getRange();
8809
0
      return;
8810
0
    }
8811
0
  }
8812
0
  StringRef Argument;
8813
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
8814
0
    return;
8815
0
  D->addAttr(AcquireHandleAttr::Create(S.Context, Argument, AL));
8816
0
}
8817
8818
template<typename Attr>
8819
0
static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8820
0
  StringRef Argument;
8821
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
8822
0
    return;
8823
0
  D->addAttr(Attr::Create(S.Context, Argument, AL));
8824
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:void handleHandleAttr<clang::ReleaseHandleAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleHandleAttr<clang::UseHandleAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
8825
8826
template<typename Attr>
8827
0
static void handleUnsafeBufferUsage(Sema &S, Decl *D, const ParsedAttr &AL) {
8828
0
  D->addAttr(Attr::Create(S.Context, AL));
8829
0
}
8830
8831
0
static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8832
  // The guard attribute takes a single identifier argument.
8833
8834
0
  if (!AL.isArgIdent(0)) {
8835
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
8836
0
        << AL << AANT_ArgumentIdentifier;
8837
0
    return;
8838
0
  }
8839
8840
0
  CFGuardAttr::GuardArg Arg;
8841
0
  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
8842
0
  if (!CFGuardAttr::ConvertStrToGuardArg(II->getName(), Arg)) {
8843
0
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
8844
0
    return;
8845
0
  }
8846
8847
0
  D->addAttr(::new (S.Context) CFGuardAttr(S.Context, AL, Arg));
8848
0
}
8849
8850
8851
template <typename AttrTy>
8852
0
static const AttrTy *findEnforceTCBAttrByName(Decl *D, StringRef Name) {
8853
0
  auto Attrs = D->specific_attrs<AttrTy>();
8854
0
  auto I = llvm::find_if(Attrs,
8855
0
                         [Name](const AttrTy *A) {
8856
0
                           return A->getTCBName() == Name;
8857
0
                         });
Unexecuted instantiation: SemaDeclAttr.cpp:findEnforceTCBAttrByName<clang::EnforceTCBLeafAttr>(clang::Decl*, llvm::StringRef)::{lambda(clang::EnforceTCBLeafAttr const*)#1}::operator()(clang::EnforceTCBLeafAttr const*) const
Unexecuted instantiation: SemaDeclAttr.cpp:findEnforceTCBAttrByName<clang::EnforceTCBAttr>(clang::Decl*, llvm::StringRef)::{lambda(clang::EnforceTCBAttr const*)#1}::operator()(clang::EnforceTCBAttr const*) const
8858
0
  return I == Attrs.end() ? nullptr : *I;
8859
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:clang::EnforceTCBLeafAttr const* findEnforceTCBAttrByName<clang::EnforceTCBLeafAttr>(clang::Decl*, llvm::StringRef)
Unexecuted instantiation: SemaDeclAttr.cpp:clang::EnforceTCBAttr const* findEnforceTCBAttrByName<clang::EnforceTCBAttr>(clang::Decl*, llvm::StringRef)
8860
8861
template <typename AttrTy, typename ConflictingAttrTy>
8862
0
static void handleEnforceTCBAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8863
0
  StringRef Argument;
8864
0
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
8865
0
    return;
8866
8867
  // A function cannot be have both regular and leaf membership in the same TCB.
8868
0
  if (const ConflictingAttrTy *ConflictingAttr =
8869
0
      findEnforceTCBAttrByName<ConflictingAttrTy>(D, Argument)) {
8870
    // We could attach a note to the other attribute but in this case
8871
    // there's no need given how the two are very close to each other.
8872
0
    S.Diag(AL.getLoc(), diag::err_tcb_conflicting_attributes)
8873
0
      << AL.getAttrName()->getName() << ConflictingAttr->getAttrName()->getName()
8874
0
      << Argument;
8875
8876
    // Error recovery: drop the non-leaf attribute so that to suppress
8877
    // all future warnings caused by erroneous attributes. The leaf attribute
8878
    // needs to be kept because it can only suppresses warnings, not cause them.
8879
0
    D->dropAttr<EnforceTCBAttr>();
8880
0
    return;
8881
0
  }
8882
8883
0
  D->addAttr(AttrTy::Create(S.Context, Argument, AL));
8884
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:void handleEnforceTCBAttr<clang::EnforceTCBAttr, clang::EnforceTCBLeafAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Unexecuted instantiation: SemaDeclAttr.cpp:void handleEnforceTCBAttr<clang::EnforceTCBLeafAttr, clang::EnforceTCBAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
8885
8886
template <typename AttrTy, typename ConflictingAttrTy>
8887
0
static AttrTy *mergeEnforceTCBAttrImpl(Sema &S, Decl *D, const AttrTy &AL) {
8888
  // Check if the new redeclaration has different leaf-ness in the same TCB.
8889
0
  StringRef TCBName = AL.getTCBName();
8890
0
  if (const ConflictingAttrTy *ConflictingAttr =
8891
0
      findEnforceTCBAttrByName<ConflictingAttrTy>(D, TCBName)) {
8892
0
    S.Diag(ConflictingAttr->getLoc(), diag::err_tcb_conflicting_attributes)
8893
0
      << ConflictingAttr->getAttrName()->getName()
8894
0
      << AL.getAttrName()->getName() << TCBName;
8895
8896
    // Add a note so that the user could easily find the conflicting attribute.
8897
0
    S.Diag(AL.getLoc(), diag::note_conflicting_attribute);
8898
8899
    // More error recovery.
8900
0
    D->dropAttr<EnforceTCBAttr>();
8901
0
    return nullptr;
8902
0
  }
8903
8904
0
  ASTContext &Context = S.getASTContext();
8905
0
  return ::new(Context) AttrTy(Context, AL, AL.getTCBName());
8906
0
}
Unexecuted instantiation: SemaDeclAttr.cpp:clang::EnforceTCBAttr* mergeEnforceTCBAttrImpl<clang::EnforceTCBAttr, clang::EnforceTCBLeafAttr>(clang::Sema&, clang::Decl*, clang::EnforceTCBAttr const&)
Unexecuted instantiation: SemaDeclAttr.cpp:clang::EnforceTCBLeafAttr* mergeEnforceTCBAttrImpl<clang::EnforceTCBLeafAttr, clang::EnforceTCBAttr>(clang::Sema&, clang::Decl*, clang::EnforceTCBLeafAttr const&)
8907
8908
0
EnforceTCBAttr *Sema::mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL) {
8909
0
  return mergeEnforceTCBAttrImpl<EnforceTCBAttr, EnforceTCBLeafAttr>(
8910
0
      *this, D, AL);
8911
0
}
8912
8913
EnforceTCBLeafAttr *Sema::mergeEnforceTCBLeafAttr(
8914
0
    Decl *D, const EnforceTCBLeafAttr &AL) {
8915
0
  return mergeEnforceTCBAttrImpl<EnforceTCBLeafAttr, EnforceTCBAttr>(
8916
0
      *this, D, AL);
8917
0
}
8918
8919
//===----------------------------------------------------------------------===//
8920
// Top Level Sema Entry Points
8921
//===----------------------------------------------------------------------===//
8922
8923
// Returns true if the attribute must delay setting its arguments until after
8924
// template instantiation, and false otherwise.
8925
0
static bool MustDelayAttributeArguments(const ParsedAttr &AL) {
8926
  // Only attributes that accept expression parameter packs can delay arguments.
8927
0
  if (!AL.acceptsExprPack())
8928
0
    return false;
8929
8930
0
  bool AttrHasVariadicArg = AL.hasVariadicArg();
8931
0
  unsigned AttrNumArgs = AL.getNumArgMembers();
8932
0
  for (size_t I = 0; I < std::min(AL.getNumArgs(), AttrNumArgs); ++I) {
8933
0
    bool IsLastAttrArg = I == (AttrNumArgs - 1);
8934
    // If the argument is the last argument and it is variadic it can contain
8935
    // any expression.
8936
0
    if (IsLastAttrArg && AttrHasVariadicArg)
8937
0
      return false;
8938
0
    Expr *E = AL.getArgAsExpr(I);
8939
0
    bool ArgMemberCanHoldExpr = AL.isParamExpr(I);
8940
    // If the expression is a pack expansion then arguments must be delayed
8941
    // unless the argument is an expression and it is the last argument of the
8942
    // attribute.
8943
0
    if (isa<PackExpansionExpr>(E))
8944
0
      return !(IsLastAttrArg && ArgMemberCanHoldExpr);
8945
    // Last case is if the expression is value dependent then it must delay
8946
    // arguments unless the corresponding argument is able to hold the
8947
    // expression.
8948
0
    if (E->isValueDependent() && !ArgMemberCanHoldExpr)
8949
0
      return true;
8950
0
  }
8951
0
  return false;
8952
0
}
8953
8954
static bool checkArmNewAttrMutualExclusion(
8955
    Sema &S, const ParsedAttr &AL, const FunctionProtoType *FPT,
8956
0
    FunctionType::ArmStateValue CurrentState, StringRef StateName) {
8957
0
  auto CheckForIncompatibleAttr =
8958
0
      [&](FunctionType::ArmStateValue IncompatibleState,
8959
0
          StringRef IncompatibleStateName) {
8960
0
        if (CurrentState == IncompatibleState) {
8961
0
          S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
8962
0
              << (std::string("'__arm_new(\"") + StateName.str() + "\")'")
8963
0
              << (std::string("'") + IncompatibleStateName.str() + "(\"" +
8964
0
                  StateName.str() + "\")'")
8965
0
              << true;
8966
0
          AL.setInvalid();
8967
0
        }
8968
0
      };
8969
8970
0
  CheckForIncompatibleAttr(FunctionType::ARM_In, "__arm_in");
8971
0
  CheckForIncompatibleAttr(FunctionType::ARM_Out, "__arm_out");
8972
0
  CheckForIncompatibleAttr(FunctionType::ARM_InOut, "__arm_inout");
8973
0
  CheckForIncompatibleAttr(FunctionType::ARM_Preserves, "__arm_preserves");
8974
0
  return AL.isInvalid();
8975
0
}
8976
8977
0
static void handleArmNewAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8978
0
  if (!AL.getNumArgs()) {
8979
0
    S.Diag(AL.getLoc(), diag::err_missing_arm_state) << AL;
8980
0
    AL.setInvalid();
8981
0
    return;
8982
0
  }
8983
8984
0
  std::vector<StringRef> NewState;
8985
0
  if (const auto *ExistingAttr = D->getAttr<ArmNewAttr>()) {
8986
0
    for (StringRef S : ExistingAttr->newArgs())
8987
0
      NewState.push_back(S);
8988
0
  }
8989
8990
0
  bool HasZA = false;
8991
0
  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
8992
0
    StringRef StateName;
8993
0
    SourceLocation LiteralLoc;
8994
0
    if (!S.checkStringLiteralArgumentAttr(AL, I, StateName, &LiteralLoc))
8995
0
      return;
8996
8997
0
    if (StateName == "za")
8998
0
      HasZA = true;
8999
0
    else {
9000
0
      S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
9001
0
      AL.setInvalid();
9002
0
      return;
9003
0
    }
9004
9005
0
    if (std::find(NewState.begin(), NewState.end(), StateName) ==
9006
0
        NewState.end()) { // Avoid adding duplicates.
9007
0
      NewState.push_back(StateName);
9008
0
    }
9009
0
  }
9010
9011
0
  if (auto *FPT = dyn_cast<FunctionProtoType>(D->getFunctionType())) {
9012
0
    FunctionType::ArmStateValue ZAState =
9013
0
        FunctionType::getArmZAState(FPT->getAArch64SMEAttributes());
9014
0
    if (HasZA && ZAState != FunctionType::ARM_None &&
9015
0
        checkArmNewAttrMutualExclusion(S, AL, FPT, ZAState, "za"))
9016
0
      return;
9017
0
  }
9018
9019
0
  D->dropAttr<ArmNewAttr>();
9020
0
  D->addAttr(::new (S.Context)
9021
0
                 ArmNewAttr(S.Context, AL, NewState.data(), NewState.size()));
9022
0
}
9023
9024
/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
9025
/// the attribute applies to decls.  If the attribute is a type attribute, just
9026
/// silently ignore it if a GNU attribute.
9027
static void
9028
ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, const ParsedAttr &AL,
9029
0
                     const Sema::ProcessDeclAttributeOptions &Options) {
9030
0
  if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
9031
0
    return;
9032
9033
  // Ignore C++11 attributes on declarator chunks: they appertain to the type
9034
  // instead.
9035
0
  if (AL.isCXX11Attribute() && !Options.IncludeCXX11Attributes)
9036
0
    return;
9037
9038
  // Unknown attributes are automatically warned on. Target-specific attributes
9039
  // which do not apply to the current target architecture are treated as
9040
  // though they were unknown attributes.
9041
0
  if (AL.getKind() == ParsedAttr::UnknownAttribute ||
9042
0
      !AL.existsInTarget(S.Context.getTargetInfo())) {
9043
0
    S.Diag(AL.getLoc(),
9044
0
           AL.isRegularKeywordAttribute()
9045
0
               ? (unsigned)diag::err_keyword_not_supported_on_target
9046
0
           : AL.isDeclspecAttribute()
9047
0
               ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
9048
0
               : (unsigned)diag::warn_unknown_attribute_ignored)
9049
0
        << AL << AL.getRange();
9050
0
    return;
9051
0
  }
9052
9053
  // Check if argument population must delayed to after template instantiation.
9054
0
  bool MustDelayArgs = MustDelayAttributeArguments(AL);
9055
9056
  // Argument number check must be skipped if arguments are delayed.
9057
0
  if (S.checkCommonAttributeFeatures(D, AL, MustDelayArgs))
9058
0
    return;
9059
9060
0
  if (MustDelayArgs) {
9061
0
    AL.handleAttrWithDelayedArgs(S, D);
9062
0
    return;
9063
0
  }
9064
9065
0
  switch (AL.getKind()) {
9066
0
  default:
9067
0
    if (AL.getInfo().handleDeclAttribute(S, D, AL) != ParsedAttrInfo::NotHandled)
9068
0
      break;
9069
0
    if (!AL.isStmtAttr()) {
9070
0
      assert(AL.isTypeAttr() && "Non-type attribute not handled");
9071
0
    }
9072
0
    if (AL.isTypeAttr()) {
9073
0
      if (Options.IgnoreTypeAttributes)
9074
0
        break;
9075
0
      if (!AL.isStandardAttributeSyntax() && !AL.isRegularKeywordAttribute()) {
9076
        // Non-[[]] type attributes are handled in processTypeAttrs(); silently
9077
        // move on.
9078
0
        break;
9079
0
      }
9080
9081
      // According to the C and C++ standards, we should never see a
9082
      // [[]] type attribute on a declaration. However, we have in the past
9083
      // allowed some type attributes to "slide" to the `DeclSpec`, so we need
9084
      // to continue to support this legacy behavior. We only do this, however,
9085
      // if
9086
      // - we actually have a `DeclSpec`, i.e. if we're looking at a
9087
      //   `DeclaratorDecl`, or
9088
      // - we are looking at an alias-declaration, where historically we have
9089
      //   allowed type attributes after the identifier to slide to the type.
9090
0
      if (AL.slidesFromDeclToDeclSpecLegacyBehavior() &&
9091
0
          isa<DeclaratorDecl, TypeAliasDecl>(D)) {
9092
        // Suggest moving the attribute to the type instead, but only for our
9093
        // own vendor attributes; moving other vendors' attributes might hurt
9094
        // portability.
9095
0
        if (AL.isClangScope()) {
9096
0
          S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
9097
0
              << AL << D->getLocation();
9098
0
        }
9099
9100
        // Allow this type attribute to be handled in processTypeAttrs();
9101
        // silently move on.
9102
0
        break;
9103
0
      }
9104
9105
0
      if (AL.getKind() == ParsedAttr::AT_Regparm) {
9106
        // `regparm` is a special case: It's a type attribute but we still want
9107
        // to treat it as if it had been written on the declaration because that
9108
        // way we'll be able to handle it directly in `processTypeAttr()`.
9109
        // If we treated `regparm` it as if it had been written on the
9110
        // `DeclSpec`, the logic in `distributeFunctionTypeAttrFromDeclSepc()`
9111
        // would try to move it to the declarator, but that doesn't work: We
9112
        // can't remove the attribute from the list of declaration attributes
9113
        // because it might be needed by other declarators in the same
9114
        // declaration.
9115
0
        break;
9116
0
      }
9117
9118
0
      if (AL.getKind() == ParsedAttr::AT_VectorSize) {
9119
        // `vector_size` is a special case: It's a type attribute semantically,
9120
        // but GCC expects the [[]] syntax to be written on the declaration (and
9121
        // warns that the attribute has no effect if it is placed on the
9122
        // decl-specifier-seq).
9123
        // Silently move on and allow the attribute to be handled in
9124
        // processTypeAttr().
9125
0
        break;
9126
0
      }
9127
9128
0
      if (AL.getKind() == ParsedAttr::AT_NoDeref) {
9129
        // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
9130
        // See https://github.com/llvm/llvm-project/issues/55790 for details.
9131
        // We allow processTypeAttrs() to emit a warning and silently move on.
9132
0
        break;
9133
0
      }
9134
0
    }
9135
    // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
9136
    // statement attribute is not written on a declaration, but this code is
9137
    // needed for type attributes as well as statement attributes in Attr.td
9138
    // that do not list any subjects.
9139
0
    S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)
9140
0
        << AL << AL.isRegularKeywordAttribute() << D->getLocation();
9141
0
    break;
9142
0
  case ParsedAttr::AT_Interrupt:
9143
0
    handleInterruptAttr(S, D, AL);
9144
0
    break;
9145
0
  case ParsedAttr::AT_X86ForceAlignArgPointer:
9146
0
    handleX86ForceAlignArgPointerAttr(S, D, AL);
9147
0
    break;
9148
0
  case ParsedAttr::AT_ReadOnlyPlacement:
9149
0
    handleSimpleAttribute<ReadOnlyPlacementAttr>(S, D, AL);
9150
0
    break;
9151
0
  case ParsedAttr::AT_DLLExport:
9152
0
  case ParsedAttr::AT_DLLImport:
9153
0
    handleDLLAttr(S, D, AL);
9154
0
    break;
9155
0
  case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
9156
0
    handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
9157
0
    break;
9158
0
  case ParsedAttr::AT_AMDGPUWavesPerEU:
9159
0
    handleAMDGPUWavesPerEUAttr(S, D, AL);
9160
0
    break;
9161
0
  case ParsedAttr::AT_AMDGPUNumSGPR:
9162
0
    handleAMDGPUNumSGPRAttr(S, D, AL);
9163
0
    break;
9164
0
  case ParsedAttr::AT_AMDGPUNumVGPR:
9165
0
    handleAMDGPUNumVGPRAttr(S, D, AL);
9166
0
    break;
9167
0
  case ParsedAttr::AT_AVRSignal:
9168
0
    handleAVRSignalAttr(S, D, AL);
9169
0
    break;
9170
0
  case ParsedAttr::AT_BPFPreserveAccessIndex:
9171
0
    handleBPFPreserveAccessIndexAttr(S, D, AL);
9172
0
    break;
9173
0
  case ParsedAttr::AT_BPFPreserveStaticOffset:
9174
0
    handleSimpleAttribute<BPFPreserveStaticOffsetAttr>(S, D, AL);
9175
0
    break;
9176
0
  case ParsedAttr::AT_BTFDeclTag:
9177
0
    handleBTFDeclTagAttr(S, D, AL);
9178
0
    break;
9179
0
  case ParsedAttr::AT_WebAssemblyExportName:
9180
0
    handleWebAssemblyExportNameAttr(S, D, AL);
9181
0
    break;
9182
0
  case ParsedAttr::AT_WebAssemblyImportModule:
9183
0
    handleWebAssemblyImportModuleAttr(S, D, AL);
9184
0
    break;
9185
0
  case ParsedAttr::AT_WebAssemblyImportName:
9186
0
    handleWebAssemblyImportNameAttr(S, D, AL);
9187
0
    break;
9188
0
  case ParsedAttr::AT_IBOutlet:
9189
0
    handleIBOutlet(S, D, AL);
9190
0
    break;
9191
0
  case ParsedAttr::AT_IBOutletCollection:
9192
0
    handleIBOutletCollection(S, D, AL);
9193
0
    break;
9194
0
  case ParsedAttr::AT_IFunc:
9195
0
    handleIFuncAttr(S, D, AL);
9196
0
    break;
9197
0
  case ParsedAttr::AT_Alias:
9198
0
    handleAliasAttr(S, D, AL);
9199
0
    break;
9200
0
  case ParsedAttr::AT_Aligned:
9201
0
    handleAlignedAttr(S, D, AL);
9202
0
    break;
9203
0
  case ParsedAttr::AT_AlignValue:
9204
0
    handleAlignValueAttr(S, D, AL);
9205
0
    break;
9206
0
  case ParsedAttr::AT_AllocSize:
9207
0
    handleAllocSizeAttr(S, D, AL);
9208
0
    break;
9209
0
  case ParsedAttr::AT_AlwaysInline:
9210
0
    handleAlwaysInlineAttr(S, D, AL);
9211
0
    break;
9212
0
  case ParsedAttr::AT_AnalyzerNoReturn:
9213
0
    handleAnalyzerNoReturnAttr(S, D, AL);
9214
0
    break;
9215
0
  case ParsedAttr::AT_TLSModel:
9216
0
    handleTLSModelAttr(S, D, AL);
9217
0
    break;
9218
0
  case ParsedAttr::AT_Annotate:
9219
0
    handleAnnotateAttr(S, D, AL);
9220
0
    break;
9221
0
  case ParsedAttr::AT_Availability:
9222
0
    handleAvailabilityAttr(S, D, AL);
9223
0
    break;
9224
0
  case ParsedAttr::AT_CarriesDependency:
9225
0
    handleDependencyAttr(S, scope, D, AL);
9226
0
    break;
9227
0
  case ParsedAttr::AT_CPUDispatch:
9228
0
  case ParsedAttr::AT_CPUSpecific:
9229
0
    handleCPUSpecificAttr(S, D, AL);
9230
0
    break;
9231
0
  case ParsedAttr::AT_Common:
9232
0
    handleCommonAttr(S, D, AL);
9233
0
    break;
9234
0
  case ParsedAttr::AT_CUDAConstant:
9235
0
    handleConstantAttr(S, D, AL);
9236
0
    break;
9237
0
  case ParsedAttr::AT_PassObjectSize:
9238
0
    handlePassObjectSizeAttr(S, D, AL);
9239
0
    break;
9240
0
  case ParsedAttr::AT_Constructor:
9241
0
      handleConstructorAttr(S, D, AL);
9242
0
    break;
9243
0
  case ParsedAttr::AT_Deprecated:
9244
0
    handleDeprecatedAttr(S, D, AL);
9245
0
    break;
9246
0
  case ParsedAttr::AT_Destructor:
9247
0
      handleDestructorAttr(S, D, AL);
9248
0
    break;
9249
0
  case ParsedAttr::AT_EnableIf:
9250
0
    handleEnableIfAttr(S, D, AL);
9251
0
    break;
9252
0
  case ParsedAttr::AT_Error:
9253
0
    handleErrorAttr(S, D, AL);
9254
0
    break;
9255
0
  case ParsedAttr::AT_DiagnoseIf:
9256
0
    handleDiagnoseIfAttr(S, D, AL);
9257
0
    break;
9258
0
  case ParsedAttr::AT_DiagnoseAsBuiltin:
9259
0
    handleDiagnoseAsBuiltinAttr(S, D, AL);
9260
0
    break;
9261
0
  case ParsedAttr::AT_NoBuiltin:
9262
0
    handleNoBuiltinAttr(S, D, AL);
9263
0
    break;
9264
0
  case ParsedAttr::AT_ExtVectorType:
9265
0
    handleExtVectorTypeAttr(S, D, AL);
9266
0
    break;
9267
0
  case ParsedAttr::AT_ExternalSourceSymbol:
9268
0
    handleExternalSourceSymbolAttr(S, D, AL);
9269
0
    break;
9270
0
  case ParsedAttr::AT_MinSize:
9271
0
    handleMinSizeAttr(S, D, AL);
9272
0
    break;
9273
0
  case ParsedAttr::AT_OptimizeNone:
9274
0
    handleOptimizeNoneAttr(S, D, AL);
9275
0
    break;
9276
0
  case ParsedAttr::AT_EnumExtensibility:
9277
0
    handleEnumExtensibilityAttr(S, D, AL);
9278
0
    break;
9279
0
  case ParsedAttr::AT_SYCLKernel:
9280
0
    handleSYCLKernelAttr(S, D, AL);
9281
0
    break;
9282
0
  case ParsedAttr::AT_SYCLSpecialClass:
9283
0
    handleSimpleAttribute<SYCLSpecialClassAttr>(S, D, AL);
9284
0
    break;
9285
0
  case ParsedAttr::AT_Format:
9286
0
    handleFormatAttr(S, D, AL);
9287
0
    break;
9288
0
  case ParsedAttr::AT_FormatArg:
9289
0
    handleFormatArgAttr(S, D, AL);
9290
0
    break;
9291
0
  case ParsedAttr::AT_Callback:
9292
0
    handleCallbackAttr(S, D, AL);
9293
0
    break;
9294
0
  case ParsedAttr::AT_CalledOnce:
9295
0
    handleCalledOnceAttr(S, D, AL);
9296
0
    break;
9297
0
  case ParsedAttr::AT_NVPTXKernel:
9298
0
  case ParsedAttr::AT_CUDAGlobal:
9299
0
    handleGlobalAttr(S, D, AL);
9300
0
    break;
9301
0
  case ParsedAttr::AT_CUDADevice:
9302
0
    handleDeviceAttr(S, D, AL);
9303
0
    break;
9304
0
  case ParsedAttr::AT_HIPManaged:
9305
0
    handleManagedAttr(S, D, AL);
9306
0
    break;
9307
0
  case ParsedAttr::AT_GNUInline:
9308
0
    handleGNUInlineAttr(S, D, AL);
9309
0
    break;
9310
0
  case ParsedAttr::AT_CUDALaunchBounds:
9311
0
    handleLaunchBoundsAttr(S, D, AL);
9312
0
    break;
9313
0
  case ParsedAttr::AT_Restrict:
9314
0
    handleRestrictAttr(S, D, AL);
9315
0
    break;
9316
0
  case ParsedAttr::AT_Mode:
9317
0
    handleModeAttr(S, D, AL);
9318
0
    break;
9319
0
  case ParsedAttr::AT_NonNull:
9320
0
    if (auto *PVD = dyn_cast<ParmVarDecl>(D))
9321
0
      handleNonNullAttrParameter(S, PVD, AL);
9322
0
    else
9323
0
      handleNonNullAttr(S, D, AL);
9324
0
    break;
9325
0
  case ParsedAttr::AT_ReturnsNonNull:
9326
0
    handleReturnsNonNullAttr(S, D, AL);
9327
0
    break;
9328
0
  case ParsedAttr::AT_NoEscape:
9329
0
    handleNoEscapeAttr(S, D, AL);
9330
0
    break;
9331
0
  case ParsedAttr::AT_MaybeUndef:
9332
0
    handleSimpleAttribute<MaybeUndefAttr>(S, D, AL);
9333
0
    break;
9334
0
  case ParsedAttr::AT_AssumeAligned:
9335
0
    handleAssumeAlignedAttr(S, D, AL);
9336
0
    break;
9337
0
  case ParsedAttr::AT_AllocAlign:
9338
0
    handleAllocAlignAttr(S, D, AL);
9339
0
    break;
9340
0
  case ParsedAttr::AT_Ownership:
9341
0
    handleOwnershipAttr(S, D, AL);
9342
0
    break;
9343
0
  case ParsedAttr::AT_Naked:
9344
0
    handleNakedAttr(S, D, AL);
9345
0
    break;
9346
0
  case ParsedAttr::AT_NoReturn:
9347
0
    handleNoReturnAttr(S, D, AL);
9348
0
    break;
9349
0
  case ParsedAttr::AT_CXX11NoReturn:
9350
0
    handleStandardNoReturnAttr(S, D, AL);
9351
0
    break;
9352
0
  case ParsedAttr::AT_AnyX86NoCfCheck:
9353
0
    handleNoCfCheckAttr(S, D, AL);
9354
0
    break;
9355
0
  case ParsedAttr::AT_NoThrow:
9356
0
    if (!AL.isUsedAsTypeAttr())
9357
0
      handleSimpleAttribute<NoThrowAttr>(S, D, AL);
9358
0
    break;
9359
0
  case ParsedAttr::AT_CUDAShared:
9360
0
    handleSharedAttr(S, D, AL);
9361
0
    break;
9362
0
  case ParsedAttr::AT_VecReturn:
9363
0
    handleVecReturnAttr(S, D, AL);
9364
0
    break;
9365
0
  case ParsedAttr::AT_ObjCOwnership:
9366
0
    handleObjCOwnershipAttr(S, D, AL);
9367
0
    break;
9368
0
  case ParsedAttr::AT_ObjCPreciseLifetime:
9369
0
    handleObjCPreciseLifetimeAttr(S, D, AL);
9370
0
    break;
9371
0
  case ParsedAttr::AT_ObjCReturnsInnerPointer:
9372
0
    handleObjCReturnsInnerPointerAttr(S, D, AL);
9373
0
    break;
9374
0
  case ParsedAttr::AT_ObjCRequiresSuper:
9375
0
    handleObjCRequiresSuperAttr(S, D, AL);
9376
0
    break;
9377
0
  case ParsedAttr::AT_ObjCBridge:
9378
0
    handleObjCBridgeAttr(S, D, AL);
9379
0
    break;
9380
0
  case ParsedAttr::AT_ObjCBridgeMutable:
9381
0
    handleObjCBridgeMutableAttr(S, D, AL);
9382
0
    break;
9383
0
  case ParsedAttr::AT_ObjCBridgeRelated:
9384
0
    handleObjCBridgeRelatedAttr(S, D, AL);
9385
0
    break;
9386
0
  case ParsedAttr::AT_ObjCDesignatedInitializer:
9387
0
    handleObjCDesignatedInitializer(S, D, AL);
9388
0
    break;
9389
0
  case ParsedAttr::AT_ObjCRuntimeName:
9390
0
    handleObjCRuntimeName(S, D, AL);
9391
0
    break;
9392
0
  case ParsedAttr::AT_ObjCBoxable:
9393
0
    handleObjCBoxable(S, D, AL);
9394
0
    break;
9395
0
  case ParsedAttr::AT_NSErrorDomain:
9396
0
    handleNSErrorDomain(S, D, AL);
9397
0
    break;
9398
0
  case ParsedAttr::AT_CFConsumed:
9399
0
  case ParsedAttr::AT_NSConsumed:
9400
0
  case ParsedAttr::AT_OSConsumed:
9401
0
    S.AddXConsumedAttr(D, AL, parsedAttrToRetainOwnershipKind(AL),
9402
0
                       /*IsTemplateInstantiation=*/false);
9403
0
    break;
9404
0
  case ParsedAttr::AT_OSReturnsRetainedOnZero:
9405
0
    handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
9406
0
        S, D, AL, isValidOSObjectOutParameter(D),
9407
0
        diag::warn_ns_attribute_wrong_parameter_type,
9408
0
        /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
9409
0
    break;
9410
0
  case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
9411
0
    handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
9412
0
        S, D, AL, isValidOSObjectOutParameter(D),
9413
0
        diag::warn_ns_attribute_wrong_parameter_type,
9414
0
        /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
9415
0
    break;
9416
0
  case ParsedAttr::AT_NSReturnsAutoreleased:
9417
0
  case ParsedAttr::AT_NSReturnsNotRetained:
9418
0
  case ParsedAttr::AT_NSReturnsRetained:
9419
0
  case ParsedAttr::AT_CFReturnsNotRetained:
9420
0
  case ParsedAttr::AT_CFReturnsRetained:
9421
0
  case ParsedAttr::AT_OSReturnsNotRetained:
9422
0
  case ParsedAttr::AT_OSReturnsRetained:
9423
0
    handleXReturnsXRetainedAttr(S, D, AL);
9424
0
    break;
9425
0
  case ParsedAttr::AT_WorkGroupSizeHint:
9426
0
    handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
9427
0
    break;
9428
0
  case ParsedAttr::AT_ReqdWorkGroupSize:
9429
0
    handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
9430
0
    break;
9431
0
  case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
9432
0
    handleSubGroupSize(S, D, AL);
9433
0
    break;
9434
0
  case ParsedAttr::AT_VecTypeHint:
9435
0
    handleVecTypeHint(S, D, AL);
9436
0
    break;
9437
0
  case ParsedAttr::AT_InitPriority:
9438
0
      handleInitPriorityAttr(S, D, AL);
9439
0
    break;
9440
0
  case ParsedAttr::AT_Packed:
9441
0
    handlePackedAttr(S, D, AL);
9442
0
    break;
9443
0
  case ParsedAttr::AT_PreferredName:
9444
0
    handlePreferredName(S, D, AL);
9445
0
    break;
9446
0
  case ParsedAttr::AT_Section:
9447
0
    handleSectionAttr(S, D, AL);
9448
0
    break;
9449
0
  case ParsedAttr::AT_CodeModel:
9450
0
    handleCodeModelAttr(S, D, AL);
9451
0
    break;
9452
0
  case ParsedAttr::AT_RandomizeLayout:
9453
0
    handleRandomizeLayoutAttr(S, D, AL);
9454
0
    break;
9455
0
  case ParsedAttr::AT_NoRandomizeLayout:
9456
0
    handleNoRandomizeLayoutAttr(S, D, AL);
9457
0
    break;
9458
0
  case ParsedAttr::AT_CodeSeg:
9459
0
    handleCodeSegAttr(S, D, AL);
9460
0
    break;
9461
0
  case ParsedAttr::AT_Target:
9462
0
    handleTargetAttr(S, D, AL);
9463
0
    break;
9464
0
  case ParsedAttr::AT_TargetVersion:
9465
0
    handleTargetVersionAttr(S, D, AL);
9466
0
    break;
9467
0
  case ParsedAttr::AT_TargetClones:
9468
0
    handleTargetClonesAttr(S, D, AL);
9469
0
    break;
9470
0
  case ParsedAttr::AT_MinVectorWidth:
9471
0
    handleMinVectorWidthAttr(S, D, AL);
9472
0
    break;
9473
0
  case ParsedAttr::AT_Unavailable:
9474
0
    handleAttrWithMessage<UnavailableAttr>(S, D, AL);
9475
0
    break;
9476
0
  case ParsedAttr::AT_Assumption:
9477
0
    handleAssumumptionAttr(S, D, AL);
9478
0
    break;
9479
0
  case ParsedAttr::AT_ObjCDirect:
9480
0
    handleObjCDirectAttr(S, D, AL);
9481
0
    break;
9482
0
  case ParsedAttr::AT_ObjCDirectMembers:
9483
0
    handleObjCDirectMembersAttr(S, D, AL);
9484
0
    handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
9485
0
    break;
9486
0
  case ParsedAttr::AT_ObjCExplicitProtocolImpl:
9487
0
    handleObjCSuppresProtocolAttr(S, D, AL);
9488
0
    break;
9489
0
  case ParsedAttr::AT_Unused:
9490
0
    handleUnusedAttr(S, D, AL);
9491
0
    break;
9492
0
  case ParsedAttr::AT_Visibility:
9493
0
    handleVisibilityAttr(S, D, AL, false);
9494
0
    break;
9495
0
  case ParsedAttr::AT_TypeVisibility:
9496
0
    handleVisibilityAttr(S, D, AL, true);
9497
0
    break;
9498
0
  case ParsedAttr::AT_WarnUnusedResult:
9499
0
    handleWarnUnusedResult(S, D, AL);
9500
0
    break;
9501
0
  case ParsedAttr::AT_WeakRef:
9502
0
    handleWeakRefAttr(S, D, AL);
9503
0
    break;
9504
0
  case ParsedAttr::AT_WeakImport:
9505
0
    handleWeakImportAttr(S, D, AL);
9506
0
    break;
9507
0
  case ParsedAttr::AT_TransparentUnion:
9508
0
    handleTransparentUnionAttr(S, D, AL);
9509
0
    break;
9510
0
  case ParsedAttr::AT_ObjCMethodFamily:
9511
0
    handleObjCMethodFamilyAttr(S, D, AL);
9512
0
    break;
9513
0
  case ParsedAttr::AT_ObjCNSObject:
9514
0
    handleObjCNSObject(S, D, AL);
9515
0
    break;
9516
0
  case ParsedAttr::AT_ObjCIndependentClass:
9517
0
    handleObjCIndependentClass(S, D, AL);
9518
0
    break;
9519
0
  case ParsedAttr::AT_Blocks:
9520
0
    handleBlocksAttr(S, D, AL);
9521
0
    break;
9522
0
  case ParsedAttr::AT_Sentinel:
9523
0
    handleSentinelAttr(S, D, AL);
9524
0
    break;
9525
0
  case ParsedAttr::AT_Cleanup:
9526
0
    handleCleanupAttr(S, D, AL);
9527
0
    break;
9528
0
  case ParsedAttr::AT_NoDebug:
9529
0
    handleNoDebugAttr(S, D, AL);
9530
0
    break;
9531
0
  case ParsedAttr::AT_CmseNSEntry:
9532
0
    handleCmseNSEntryAttr(S, D, AL);
9533
0
    break;
9534
0
  case ParsedAttr::AT_StdCall:
9535
0
  case ParsedAttr::AT_CDecl:
9536
0
  case ParsedAttr::AT_FastCall:
9537
0
  case ParsedAttr::AT_ThisCall:
9538
0
  case ParsedAttr::AT_Pascal:
9539
0
  case ParsedAttr::AT_RegCall:
9540
0
  case ParsedAttr::AT_SwiftCall:
9541
0
  case ParsedAttr::AT_SwiftAsyncCall:
9542
0
  case ParsedAttr::AT_VectorCall:
9543
0
  case ParsedAttr::AT_MSABI:
9544
0
  case ParsedAttr::AT_SysVABI:
9545
0
  case ParsedAttr::AT_Pcs:
9546
0
  case ParsedAttr::AT_IntelOclBicc:
9547
0
  case ParsedAttr::AT_PreserveMost:
9548
0
  case ParsedAttr::AT_PreserveAll:
9549
0
  case ParsedAttr::AT_AArch64VectorPcs:
9550
0
  case ParsedAttr::AT_AArch64SVEPcs:
9551
0
  case ParsedAttr::AT_AMDGPUKernelCall:
9552
0
  case ParsedAttr::AT_M68kRTD:
9553
0
    handleCallConvAttr(S, D, AL);
9554
0
    break;
9555
0
  case ParsedAttr::AT_Suppress:
9556
0
    handleSuppressAttr(S, D, AL);
9557
0
    break;
9558
0
  case ParsedAttr::AT_Owner:
9559
0
  case ParsedAttr::AT_Pointer:
9560
0
    handleLifetimeCategoryAttr(S, D, AL);
9561
0
    break;
9562
0
  case ParsedAttr::AT_OpenCLAccess:
9563
0
    handleOpenCLAccessAttr(S, D, AL);
9564
0
    break;
9565
0
  case ParsedAttr::AT_OpenCLNoSVM:
9566
0
    handleOpenCLNoSVMAttr(S, D, AL);
9567
0
    break;
9568
0
  case ParsedAttr::AT_SwiftContext:
9569
0
    S.AddParameterABIAttr(D, AL, ParameterABI::SwiftContext);
9570
0
    break;
9571
0
  case ParsedAttr::AT_SwiftAsyncContext:
9572
0
    S.AddParameterABIAttr(D, AL, ParameterABI::SwiftAsyncContext);
9573
0
    break;
9574
0
  case ParsedAttr::AT_SwiftErrorResult:
9575
0
    S.AddParameterABIAttr(D, AL, ParameterABI::SwiftErrorResult);
9576
0
    break;
9577
0
  case ParsedAttr::AT_SwiftIndirectResult:
9578
0
    S.AddParameterABIAttr(D, AL, ParameterABI::SwiftIndirectResult);
9579
0
    break;
9580
0
  case ParsedAttr::AT_InternalLinkage:
9581
0
    handleInternalLinkageAttr(S, D, AL);
9582
0
    break;
9583
0
  case ParsedAttr::AT_ZeroCallUsedRegs:
9584
0
    handleZeroCallUsedRegsAttr(S, D, AL);
9585
0
    break;
9586
0
  case ParsedAttr::AT_FunctionReturnThunks:
9587
0
    handleFunctionReturnThunksAttr(S, D, AL);
9588
0
    break;
9589
0
  case ParsedAttr::AT_NoMerge:
9590
0
    handleNoMergeAttr(S, D, AL);
9591
0
    break;
9592
0
  case ParsedAttr::AT_NoUniqueAddress:
9593
0
    handleNoUniqueAddressAttr(S, D, AL);
9594
0
    break;
9595
9596
0
  case ParsedAttr::AT_AvailableOnlyInDefaultEvalMethod:
9597
0
    handleAvailableOnlyInDefaultEvalMethod(S, D, AL);
9598
0
    break;
9599
9600
0
  case ParsedAttr::AT_CountedBy:
9601
0
    handleCountedByAttr(S, D, AL);
9602
0
    break;
9603
9604
  // Microsoft attributes:
9605
0
  case ParsedAttr::AT_LayoutVersion:
9606
0
    handleLayoutVersion(S, D, AL);
9607
0
    break;
9608
0
  case ParsedAttr::AT_Uuid:
9609
0
    handleUuidAttr(S, D, AL);
9610
0
    break;
9611
0
  case ParsedAttr::AT_MSInheritance:
9612
0
    handleMSInheritanceAttr(S, D, AL);
9613
0
    break;
9614
0
  case ParsedAttr::AT_Thread:
9615
0
    handleDeclspecThreadAttr(S, D, AL);
9616
0
    break;
9617
0
  case ParsedAttr::AT_MSConstexpr:
9618
0
    handleMSConstexprAttr(S, D, AL);
9619
0
    break;
9620
9621
  // HLSL attributes:
9622
0
  case ParsedAttr::AT_HLSLNumThreads:
9623
0
    handleHLSLNumThreadsAttr(S, D, AL);
9624
0
    break;
9625
0
  case ParsedAttr::AT_HLSLSV_GroupIndex:
9626
0
    handleSimpleAttribute<HLSLSV_GroupIndexAttr>(S, D, AL);
9627
0
    break;
9628
0
  case ParsedAttr::AT_HLSLSV_DispatchThreadID:
9629
0
    handleHLSLSV_DispatchThreadIDAttr(S, D, AL);
9630
0
    break;
9631
0
  case ParsedAttr::AT_HLSLShader:
9632
0
    handleHLSLShaderAttr(S, D, AL);
9633
0
    break;
9634
0
  case ParsedAttr::AT_HLSLResourceBinding:
9635
0
    handleHLSLResourceBindingAttr(S, D, AL);
9636
0
    break;
9637
0
  case ParsedAttr::AT_HLSLParamModifier:
9638
0
    handleHLSLParamModifierAttr(S, D, AL);
9639
0
    break;
9640
9641
0
  case ParsedAttr::AT_AbiTag:
9642
0
    handleAbiTagAttr(S, D, AL);
9643
0
    break;
9644
0
  case ParsedAttr::AT_CFGuard:
9645
0
    handleCFGuardAttr(S, D, AL);
9646
0
    break;
9647
9648
  // Thread safety attributes:
9649
0
  case ParsedAttr::AT_AssertExclusiveLock:
9650
0
    handleAssertExclusiveLockAttr(S, D, AL);
9651
0
    break;
9652
0
  case ParsedAttr::AT_AssertSharedLock:
9653
0
    handleAssertSharedLockAttr(S, D, AL);
9654
0
    break;
9655
0
  case ParsedAttr::AT_PtGuardedVar:
9656
0
    handlePtGuardedVarAttr(S, D, AL);
9657
0
    break;
9658
0
  case ParsedAttr::AT_NoSanitize:
9659
0
    handleNoSanitizeAttr(S, D, AL);
9660
0
    break;
9661
0
  case ParsedAttr::AT_NoSanitizeSpecific:
9662
0
    handleNoSanitizeSpecificAttr(S, D, AL);
9663
0
    break;
9664
0
  case ParsedAttr::AT_GuardedBy:
9665
0
    handleGuardedByAttr(S, D, AL);
9666
0
    break;
9667
0
  case ParsedAttr::AT_PtGuardedBy:
9668
0
    handlePtGuardedByAttr(S, D, AL);
9669
0
    break;
9670
0
  case ParsedAttr::AT_ExclusiveTrylockFunction:
9671
0
    handleExclusiveTrylockFunctionAttr(S, D, AL);
9672
0
    break;
9673
0
  case ParsedAttr::AT_LockReturned:
9674
0
    handleLockReturnedAttr(S, D, AL);
9675
0
    break;
9676
0
  case ParsedAttr::AT_LocksExcluded:
9677
0
    handleLocksExcludedAttr(S, D, AL);
9678
0
    break;
9679
0
  case ParsedAttr::AT_SharedTrylockFunction:
9680
0
    handleSharedTrylockFunctionAttr(S, D, AL);
9681
0
    break;
9682
0
  case ParsedAttr::AT_AcquiredBefore:
9683
0
    handleAcquiredBeforeAttr(S, D, AL);
9684
0
    break;
9685
0
  case ParsedAttr::AT_AcquiredAfter:
9686
0
    handleAcquiredAfterAttr(S, D, AL);
9687
0
    break;
9688
9689
  // Capability analysis attributes.
9690
0
  case ParsedAttr::AT_Capability:
9691
0
  case ParsedAttr::AT_Lockable:
9692
0
    handleCapabilityAttr(S, D, AL);
9693
0
    break;
9694
0
  case ParsedAttr::AT_RequiresCapability:
9695
0
    handleRequiresCapabilityAttr(S, D, AL);
9696
0
    break;
9697
9698
0
  case ParsedAttr::AT_AssertCapability:
9699
0
    handleAssertCapabilityAttr(S, D, AL);
9700
0
    break;
9701
0
  case ParsedAttr::AT_AcquireCapability:
9702
0
    handleAcquireCapabilityAttr(S, D, AL);
9703
0
    break;
9704
0
  case ParsedAttr::AT_ReleaseCapability:
9705
0
    handleReleaseCapabilityAttr(S, D, AL);
9706
0
    break;
9707
0
  case ParsedAttr::AT_TryAcquireCapability:
9708
0
    handleTryAcquireCapabilityAttr(S, D, AL);
9709
0
    break;
9710
9711
  // Consumed analysis attributes.
9712
0
  case ParsedAttr::AT_Consumable:
9713
0
    handleConsumableAttr(S, D, AL);
9714
0
    break;
9715
0
  case ParsedAttr::AT_CallableWhen:
9716
0
    handleCallableWhenAttr(S, D, AL);
9717
0
    break;
9718
0
  case ParsedAttr::AT_ParamTypestate:
9719
0
    handleParamTypestateAttr(S, D, AL);
9720
0
    break;
9721
0
  case ParsedAttr::AT_ReturnTypestate:
9722
0
    handleReturnTypestateAttr(S, D, AL);
9723
0
    break;
9724
0
  case ParsedAttr::AT_SetTypestate:
9725
0
    handleSetTypestateAttr(S, D, AL);
9726
0
    break;
9727
0
  case ParsedAttr::AT_TestTypestate:
9728
0
    handleTestTypestateAttr(S, D, AL);
9729
0
    break;
9730
9731
  // Type safety attributes.
9732
0
  case ParsedAttr::AT_ArgumentWithTypeTag:
9733
0
    handleArgumentWithTypeTagAttr(S, D, AL);
9734
0
    break;
9735
0
  case ParsedAttr::AT_TypeTagForDatatype:
9736
0
    handleTypeTagForDatatypeAttr(S, D, AL);
9737
0
    break;
9738
9739
  // Swift attributes.
9740
0
  case ParsedAttr::AT_SwiftAsyncName:
9741
0
    handleSwiftAsyncName(S, D, AL);
9742
0
    break;
9743
0
  case ParsedAttr::AT_SwiftAttr:
9744
0
    handleSwiftAttrAttr(S, D, AL);
9745
0
    break;
9746
0
  case ParsedAttr::AT_SwiftBridge:
9747
0
    handleSwiftBridge(S, D, AL);
9748
0
    break;
9749
0
  case ParsedAttr::AT_SwiftError:
9750
0
    handleSwiftError(S, D, AL);
9751
0
    break;
9752
0
  case ParsedAttr::AT_SwiftName:
9753
0
    handleSwiftName(S, D, AL);
9754
0
    break;
9755
0
  case ParsedAttr::AT_SwiftNewType:
9756
0
    handleSwiftNewType(S, D, AL);
9757
0
    break;
9758
0
  case ParsedAttr::AT_SwiftAsync:
9759
0
    handleSwiftAsyncAttr(S, D, AL);
9760
0
    break;
9761
0
  case ParsedAttr::AT_SwiftAsyncError:
9762
0
    handleSwiftAsyncError(S, D, AL);
9763
0
    break;
9764
9765
  // XRay attributes.
9766
0
  case ParsedAttr::AT_XRayLogArgs:
9767
0
    handleXRayLogArgsAttr(S, D, AL);
9768
0
    break;
9769
9770
0
  case ParsedAttr::AT_PatchableFunctionEntry:
9771
0
    handlePatchableFunctionEntryAttr(S, D, AL);
9772
0
    break;
9773
9774
0
  case ParsedAttr::AT_AlwaysDestroy:
9775
0
  case ParsedAttr::AT_NoDestroy:
9776
0
    handleDestroyAttr(S, D, AL);
9777
0
    break;
9778
9779
0
  case ParsedAttr::AT_Uninitialized:
9780
0
    handleUninitializedAttr(S, D, AL);
9781
0
    break;
9782
9783
0
  case ParsedAttr::AT_ObjCExternallyRetained:
9784
0
    handleObjCExternallyRetainedAttr(S, D, AL);
9785
0
    break;
9786
9787
0
  case ParsedAttr::AT_MIGServerRoutine:
9788
0
    handleMIGServerRoutineAttr(S, D, AL);
9789
0
    break;
9790
9791
0
  case ParsedAttr::AT_MSAllocator:
9792
0
    handleMSAllocatorAttr(S, D, AL);
9793
0
    break;
9794
9795
0
  case ParsedAttr::AT_ArmBuiltinAlias:
9796
0
    handleArmBuiltinAliasAttr(S, D, AL);
9797
0
    break;
9798
9799
0
  case ParsedAttr::AT_ArmLocallyStreaming:
9800
0
    handleSimpleAttribute<ArmLocallyStreamingAttr>(S, D, AL);
9801
0
    break;
9802
9803
0
  case ParsedAttr::AT_ArmNew:
9804
0
    handleArmNewAttr(S, D, AL);
9805
0
    break;
9806
9807
0
  case ParsedAttr::AT_AcquireHandle:
9808
0
    handleAcquireHandleAttr(S, D, AL);
9809
0
    break;
9810
9811
0
  case ParsedAttr::AT_ReleaseHandle:
9812
0
    handleHandleAttr<ReleaseHandleAttr>(S, D, AL);
9813
0
    break;
9814
9815
0
  case ParsedAttr::AT_UnsafeBufferUsage:
9816
0
    handleUnsafeBufferUsage<UnsafeBufferUsageAttr>(S, D, AL);
9817
0
    break;
9818
9819
0
  case ParsedAttr::AT_UseHandle:
9820
0
    handleHandleAttr<UseHandleAttr>(S, D, AL);
9821
0
    break;
9822
9823
0
  case ParsedAttr::AT_EnforceTCB:
9824
0
    handleEnforceTCBAttr<EnforceTCBAttr, EnforceTCBLeafAttr>(S, D, AL);
9825
0
    break;
9826
9827
0
  case ParsedAttr::AT_EnforceTCBLeaf:
9828
0
    handleEnforceTCBAttr<EnforceTCBLeafAttr, EnforceTCBAttr>(S, D, AL);
9829
0
    break;
9830
9831
0
  case ParsedAttr::AT_BuiltinAlias:
9832
0
    handleBuiltinAliasAttr(S, D, AL);
9833
0
    break;
9834
9835
0
  case ParsedAttr::AT_PreferredType:
9836
0
    handlePreferredTypeAttr(S, D, AL);
9837
0
    break;
9838
9839
0
  case ParsedAttr::AT_UsingIfExists:
9840
0
    handleSimpleAttribute<UsingIfExistsAttr>(S, D, AL);
9841
0
    break;
9842
0
  }
9843
0
}
9844
9845
/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
9846
/// attribute list to the specified decl, ignoring any type attributes.
9847
void Sema::ProcessDeclAttributeList(
9848
    Scope *S, Decl *D, const ParsedAttributesView &AttrList,
9849
11.2k
    const ProcessDeclAttributeOptions &Options) {
9850
11.2k
  if (AttrList.empty())
9851
11.2k
    return;
9852
9853
0
  for (const ParsedAttr &AL : AttrList)
9854
0
    ProcessDeclAttribute(*this, S, D, AL, Options);
9855
9856
  // FIXME: We should be able to handle these cases in TableGen.
9857
  // GCC accepts
9858
  // static int a9 __attribute__((weakref));
9859
  // but that looks really pointless. We reject it.
9860
0
  if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
9861
0
    Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
9862
0
        << cast<NamedDecl>(D);
9863
0
    D->dropAttr<WeakRefAttr>();
9864
0
    return;
9865
0
  }
9866
9867
  // FIXME: We should be able to handle this in TableGen as well. It would be
9868
  // good to have a way to specify "these attributes must appear as a group",
9869
  // for these. Additionally, it would be good to have a way to specify "these
9870
  // attribute must never appear as a group" for attributes like cold and hot.
9871
0
  if (!D->hasAttr<OpenCLKernelAttr>()) {
9872
    // These attributes cannot be applied to a non-kernel function.
9873
0
    if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
9874
      // FIXME: This emits a different error message than
9875
      // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
9876
0
      Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
9877
0
      D->setInvalidDecl();
9878
0
    } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
9879
0
      Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
9880
0
      D->setInvalidDecl();
9881
0
    } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
9882
0
      Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
9883
0
      D->setInvalidDecl();
9884
0
    } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
9885
0
      Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
9886
0
      D->setInvalidDecl();
9887
0
    } else if (!D->hasAttr<CUDAGlobalAttr>()) {
9888
0
      if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
9889
0
        Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
9890
0
            << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
9891
0
        D->setInvalidDecl();
9892
0
      } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
9893
0
        Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
9894
0
            << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
9895
0
        D->setInvalidDecl();
9896
0
      } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
9897
0
        Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
9898
0
            << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
9899
0
        D->setInvalidDecl();
9900
0
      } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
9901
0
        Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
9902
0
            << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
9903
0
        D->setInvalidDecl();
9904
0
      }
9905
0
    }
9906
0
  }
9907
9908
  // Do this check after processing D's attributes because the attribute
9909
  // objc_method_family can change whether the given method is in the init
9910
  // family, and it can be applied after objc_designated_initializer. This is a
9911
  // bit of a hack, but we need it to be compatible with versions of clang that
9912
  // processed the attribute list in the wrong order.
9913
0
  if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
9914
0
      cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
9915
0
    Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
9916
0
    D->dropAttr<ObjCDesignatedInitializerAttr>();
9917
0
  }
9918
0
}
9919
9920
// Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr
9921
// attribute.
9922
void Sema::ProcessDeclAttributeDelayed(Decl *D,
9923
0
                                       const ParsedAttributesView &AttrList) {
9924
0
  for (const ParsedAttr &AL : AttrList)
9925
0
    if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
9926
0
      handleTransparentUnionAttr(*this, D, AL);
9927
0
      break;
9928
0
    }
9929
9930
  // For BPFPreserveAccessIndexAttr, we want to populate the attributes
9931
  // to fields and inner records as well.
9932
0
  if (D && D->hasAttr<BPFPreserveAccessIndexAttr>())
9933
0
    handleBPFPreserveAIRecord(*this, cast<RecordDecl>(D));
9934
0
}
9935
9936
// Annotation attributes are the only attributes allowed after an access
9937
// specifier.
9938
bool Sema::ProcessAccessDeclAttributeList(
9939
0
    AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
9940
0
  for (const ParsedAttr &AL : AttrList) {
9941
0
    if (AL.getKind() == ParsedAttr::AT_Annotate) {
9942
0
      ProcessDeclAttribute(*this, nullptr, ASDecl, AL,
9943
0
                           ProcessDeclAttributeOptions());
9944
0
    } else {
9945
0
      Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
9946
0
      return true;
9947
0
    }
9948
0
  }
9949
0
  return false;
9950
0
}
9951
9952
/// checkUnusedDeclAttributes - Check a list of attributes to see if it
9953
/// contains any decl attributes that we should warn about.
9954
0
static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
9955
0
  for (const ParsedAttr &AL : A) {
9956
    // Only warn if the attribute is an unignored, non-type attribute.
9957
0
    if (AL.isUsedAsTypeAttr() || AL.isInvalid())
9958
0
      continue;
9959
0
    if (AL.getKind() == ParsedAttr::IgnoredAttribute)
9960
0
      continue;
9961
9962
0
    if (AL.getKind() == ParsedAttr::UnknownAttribute) {
9963
0
      S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
9964
0
          << AL << AL.getRange();
9965
0
    } else {
9966
0
      S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
9967
0
                                                            << AL.getRange();
9968
0
    }
9969
0
  }
9970
0
}
9971
9972
/// checkUnusedDeclAttributes - Given a declarator which is not being
9973
/// used to build a declaration, complain about any decl attributes
9974
/// which might be lying around on it.
9975
0
void Sema::checkUnusedDeclAttributes(Declarator &D) {
9976
0
  ::checkUnusedDeclAttributes(*this, D.getDeclarationAttributes());
9977
0
  ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
9978
0
  ::checkUnusedDeclAttributes(*this, D.getAttributes());
9979
0
  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
9980
0
    ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
9981
0
}
9982
9983
/// DeclClonePragmaWeak - clone existing decl (maybe definition),
9984
/// \#pragma weak needs a non-definition decl and source may not have one.
9985
NamedDecl *Sema::DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
9986
0
                                     SourceLocation Loc) {
9987
0
  assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
9988
0
  NamedDecl *NewD = nullptr;
9989
0
  if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
9990
0
    FunctionDecl *NewFD;
9991
    // FIXME: Missing call to CheckFunctionDeclaration().
9992
    // FIXME: Mangling?
9993
    // FIXME: Is the qualifier info correct?
9994
    // FIXME: Is the DeclContext correct?
9995
0
    NewFD = FunctionDecl::Create(
9996
0
        FD->getASTContext(), FD->getDeclContext(), Loc, Loc,
9997
0
        DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None,
9998
0
        getCurFPFeatures().isFPConstrained(), false /*isInlineSpecified*/,
9999
0
        FD->hasPrototype(), ConstexprSpecKind::Unspecified,
10000
0
        FD->getTrailingRequiresClause());
10001
0
    NewD = NewFD;
10002
10003
0
    if (FD->getQualifier())
10004
0
      NewFD->setQualifierInfo(FD->getQualifierLoc());
10005
10006
    // Fake up parameter variables; they are declared as if this were
10007
    // a typedef.
10008
0
    QualType FDTy = FD->getType();
10009
0
    if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
10010
0
      SmallVector<ParmVarDecl*, 16> Params;
10011
0
      for (const auto &AI : FT->param_types()) {
10012
0
        ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
10013
0
        Param->setScopeInfo(0, Params.size());
10014
0
        Params.push_back(Param);
10015
0
      }
10016
0
      NewFD->setParams(Params);
10017
0
    }
10018
0
  } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
10019
0
    NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
10020
0
                           VD->getInnerLocStart(), VD->getLocation(), II,
10021
0
                           VD->getType(), VD->getTypeSourceInfo(),
10022
0
                           VD->getStorageClass());
10023
0
    if (VD->getQualifier())
10024
0
      cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
10025
0
  }
10026
0
  return NewD;
10027
0
}
10028
10029
/// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
10030
/// applied to it, possibly with an alias.
10031
0
void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W) {
10032
0
  if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
10033
0
    IdentifierInfo *NDId = ND->getIdentifier();
10034
0
    NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
10035
0
    NewD->addAttr(
10036
0
        AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation()));
10037
0
    NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
10038
0
    WeakTopLevelDecl.push_back(NewD);
10039
    // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
10040
    // to insert Decl at TU scope, sorry.
10041
0
    DeclContext *SavedContext = CurContext;
10042
0
    CurContext = Context.getTranslationUnitDecl();
10043
0
    NewD->setDeclContext(CurContext);
10044
0
    NewD->setLexicalDeclContext(CurContext);
10045
0
    PushOnScopeChains(NewD, S);
10046
0
    CurContext = SavedContext;
10047
0
  } else { // just add weak to existing
10048
0
    ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
10049
0
  }
10050
0
}
10051
10052
5.08k
void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
10053
  // It's valid to "forward-declare" #pragma weak, in which case we
10054
  // have to do this.
10055
5.08k
  LoadExternalWeakUndeclaredIdentifiers();
10056
5.08k
  if (WeakUndeclaredIdentifiers.empty())
10057
5.08k
    return;
10058
0
  NamedDecl *ND = nullptr;
10059
0
  if (auto *VD = dyn_cast<VarDecl>(D))
10060
0
    if (VD->isExternC())
10061
0
      ND = VD;
10062
0
  if (auto *FD = dyn_cast<FunctionDecl>(D))
10063
0
    if (FD->isExternC())
10064
0
      ND = FD;
10065
0
  if (!ND)
10066
0
    return;
10067
0
  if (IdentifierInfo *Id = ND->getIdentifier()) {
10068
0
    auto I = WeakUndeclaredIdentifiers.find(Id);
10069
0
    if (I != WeakUndeclaredIdentifiers.end()) {
10070
0
      auto &WeakInfos = I->second;
10071
0
      for (const auto &W : WeakInfos)
10072
0
        DeclApplyPragmaWeak(S, ND, W);
10073
0
      std::remove_reference_t<decltype(WeakInfos)> EmptyWeakInfos;
10074
0
      WeakInfos.swap(EmptyWeakInfos);
10075
0
    }
10076
0
  }
10077
0
}
10078
10079
/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
10080
/// it, apply them to D.  This is a bit tricky because PD can have attributes
10081
/// specified in many different places, and we need to find and apply them all.
10082
5.13k
void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
10083
  // Ordering of attributes can be important, so we take care to process
10084
  // attributes in the order in which they appeared in the source code.
10085
10086
  // First, process attributes that appeared on the declaration itself (but
10087
  // only if they don't have the legacy behavior of "sliding" to the DeclSepc).
10088
5.13k
  ParsedAttributesView NonSlidingAttrs;
10089
5.13k
  for (ParsedAttr &AL : PD.getDeclarationAttributes()) {
10090
0
    if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
10091
      // Skip processing the attribute, but do check if it appertains to the
10092
      // declaration. This is needed for the `MatrixType` attribute, which,
10093
      // despite being a type attribute, defines a `SubjectList` that only
10094
      // allows it to be used on typedef declarations.
10095
0
      AL.diagnoseAppertainsTo(*this, D);
10096
0
    } else {
10097
0
      NonSlidingAttrs.addAtEnd(&AL);
10098
0
    }
10099
0
  }
10100
5.13k
  ProcessDeclAttributeList(S, D, NonSlidingAttrs);
10101
10102
  // Apply decl attributes from the DeclSpec if present.
10103
5.13k
  if (!PD.getDeclSpec().getAttributes().empty()) {
10104
0
    ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes(),
10105
0
                             ProcessDeclAttributeOptions()
10106
0
                                 .WithIncludeCXX11Attributes(false)
10107
0
                                 .WithIgnoreTypeAttributes(true));
10108
0
  }
10109
10110
  // Walk the declarator structure, applying decl attributes that were in a type
10111
  // position to the decl itself.  This handles cases like:
10112
  //   int *__attr__(x)** D;
10113
  // when X is a decl attribute.
10114
5.64k
  for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) {
10115
512
    ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
10116
512
                             ProcessDeclAttributeOptions()
10117
512
                                 .WithIncludeCXX11Attributes(false)
10118
512
                                 .WithIgnoreTypeAttributes(true));
10119
512
  }
10120
10121
  // Finally, apply any attributes on the decl itself.
10122
5.13k
  ProcessDeclAttributeList(S, D, PD.getAttributes());
10123
10124
  // Apply additional attributes specified by '#pragma clang attribute'.
10125
5.13k
  AddPragmaAttributes(S, D);
10126
5.13k
}
10127
10128
/// Is the given declaration allowed to use a forbidden type?
10129
/// If so, it'll still be annotated with an attribute that makes it
10130
/// illegal to actually use.
10131
static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
10132
                                   const DelayedDiagnostic &diag,
10133
0
                                   UnavailableAttr::ImplicitReason &reason) {
10134
  // Private ivars are always okay.  Unfortunately, people don't
10135
  // always properly make their ivars private, even in system headers.
10136
  // Plus we need to make fields okay, too.
10137
0
  if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
10138
0
      !isa<FunctionDecl>(D))
10139
0
    return false;
10140
10141
  // Silently accept unsupported uses of __weak in both user and system
10142
  // declarations when it's been disabled, for ease of integration with
10143
  // -fno-objc-arc files.  We do have to take some care against attempts
10144
  // to define such things;  for now, we've only done that for ivars
10145
  // and properties.
10146
0
  if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
10147
0
    if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
10148
0
        diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
10149
0
      reason = UnavailableAttr::IR_ForbiddenWeak;
10150
0
      return true;
10151
0
    }
10152
0
  }
10153
10154
  // Allow all sorts of things in system headers.
10155
0
  if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) {
10156
    // Currently, all the failures dealt with this way are due to ARC
10157
    // restrictions.
10158
0
    reason = UnavailableAttr::IR_ARCForbiddenType;
10159
0
    return true;
10160
0
  }
10161
10162
0
  return false;
10163
0
}
10164
10165
/// Handle a delayed forbidden-type diagnostic.
10166
static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
10167
0
                                       Decl *D) {
10168
0
  auto Reason = UnavailableAttr::IR_None;
10169
0
  if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
10170
0
    assert(Reason && "didn't set reason?");
10171
0
    D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
10172
0
    return;
10173
0
  }
10174
0
  if (S.getLangOpts().ObjCAutoRefCount)
10175
0
    if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10176
      // FIXME: we may want to suppress diagnostics for all
10177
      // kind of forbidden type messages on unavailable functions.
10178
0
      if (FD->hasAttr<UnavailableAttr>() &&
10179
0
          DD.getForbiddenTypeDiagnostic() ==
10180
0
              diag::err_arc_array_param_no_ownership) {
10181
0
        DD.Triggered = true;
10182
0
        return;
10183
0
      }
10184
0
    }
10185
10186
0
  S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
10187
0
      << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
10188
0
  DD.Triggered = true;
10189
0
}
10190
10191
10192
47.9k
void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
10193
47.9k
  assert(DelayedDiagnostics.getCurrentPool());
10194
0
  DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
10195
47.9k
  DelayedDiagnostics.popWithoutEmitting(state);
10196
10197
  // When delaying diagnostics to run in the context of a parsed
10198
  // declaration, we only want to actually emit anything if parsing
10199
  // succeeds.
10200
47.9k
  if (!decl) return;
10201
10202
  // We emit all the active diagnostics in this pool or any of its
10203
  // parents.  In general, we'll get one pool for the decl spec
10204
  // and a child pool for each declarator; in a decl group like:
10205
  //   deprecated_typedef foo, *bar, baz();
10206
  // only the declarator pops will be passed decls.  This is correct;
10207
  // we really do need to consider delayed diagnostics from the decl spec
10208
  // for each of the different declarations.
10209
5.08k
  const DelayedDiagnosticPool *pool = &poppedPool;
10210
10.1k
  do {
10211
10.1k
    bool AnyAccessFailures = false;
10212
10.1k
    for (DelayedDiagnosticPool::pool_iterator
10213
10.1k
           i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
10214
      // This const_cast is a bit lame.  Really, Triggered should be mutable.
10215
0
      DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
10216
0
      if (diag.Triggered)
10217
0
        continue;
10218
10219
0
      switch (diag.Kind) {
10220
0
      case DelayedDiagnostic::Availability:
10221
        // Don't bother giving deprecation/unavailable diagnostics if
10222
        // the decl is invalid.
10223
0
        if (!decl->isInvalidDecl())
10224
0
          handleDelayedAvailabilityCheck(diag, decl);
10225
0
        break;
10226
10227
0
      case DelayedDiagnostic::Access:
10228
        // Only produce one access control diagnostic for a structured binding
10229
        // declaration: we don't need to tell the user that all the fields are
10230
        // inaccessible one at a time.
10231
0
        if (AnyAccessFailures && isa<DecompositionDecl>(decl))
10232
0
          continue;
10233
0
        HandleDelayedAccessCheck(diag, decl);
10234
0
        if (diag.Triggered)
10235
0
          AnyAccessFailures = true;
10236
0
        break;
10237
10238
0
      case DelayedDiagnostic::ForbiddenType:
10239
0
        handleDelayedForbiddenType(*this, diag, decl);
10240
0
        break;
10241
0
      }
10242
0
    }
10243
10.1k
  } while ((pool = pool->getParent()));
10244
5.08k
}
10245
10246
/// Given a set of delayed diagnostics, re-emit them as if they had
10247
/// been delayed in the current context instead of in the given pool.
10248
/// Essentially, this just moves them to the current pool.
10249
0
void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
10250
0
  DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
10251
0
  assert(curPool && "re-emitting in undelayed context not supported");
10252
0
  curPool->steal(pool);
10253
0
}