DeclSpec.h revision 1.1.1.2
1//===--- DeclSpec.h - Parsed declaration specifiers -------------*- C++ -*-===//
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/// \file
10/// This file defines the classes used to store parsed information about
11/// declaration-specifiers and declarators.
12///
13/// \verbatim
14///   static const int volatile x, *y, *(*(*z)[10])(const void *x);
15///   ------------------------- -  --  ---------------------------
16///     declaration-specifiers  \  |   /
17///                            declarators
18/// \endverbatim
19///
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_CLANG_SEMA_DECLSPEC_H
23#define LLVM_CLANG_SEMA_DECLSPEC_H
24
25#include "clang/AST/DeclCXX.h"
26#include "clang/AST/DeclObjCCommon.h"
27#include "clang/AST/NestedNameSpecifier.h"
28#include "clang/Basic/ExceptionSpecificationType.h"
29#include "clang/Basic/Lambda.h"
30#include "clang/Basic/OperatorKinds.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Lex/Token.h"
33#include "clang/Sema/Ownership.h"
34#include "clang/Sema/ParsedAttr.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/ErrorHandling.h"
38
39namespace clang {
40  class ASTContext;
41  class CXXRecordDecl;
42  class TypeLoc;
43  class LangOptions;
44  class IdentifierInfo;
45  class NamespaceAliasDecl;
46  class NamespaceDecl;
47  class ObjCDeclSpec;
48  class Sema;
49  class Declarator;
50  struct TemplateIdAnnotation;
51
52/// Represents a C++ nested-name-specifier or a global scope specifier.
53///
54/// These can be in 3 states:
55///   1) Not present, identified by isEmpty()
56///   2) Present, identified by isNotEmpty()
57///      2.a) Valid, identified by isValid()
58///      2.b) Invalid, identified by isInvalid().
59///
60/// isSet() is deprecated because it mostly corresponded to "valid" but was
61/// often used as if it meant "present".
62///
63/// The actual scope is described by getScopeRep().
64class CXXScopeSpec {
65  SourceRange Range;
66  NestedNameSpecifierLocBuilder Builder;
67
68public:
69  SourceRange getRange() const { return Range; }
70  void setRange(SourceRange R) { Range = R; }
71  void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); }
72  void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); }
73  SourceLocation getBeginLoc() const { return Range.getBegin(); }
74  SourceLocation getEndLoc() const { return Range.getEnd(); }
75
76  /// Retrieve the representation of the nested-name-specifier.
77  NestedNameSpecifier *getScopeRep() const {
78    return Builder.getRepresentation();
79  }
80
81  /// Extend the current nested-name-specifier by another
82  /// nested-name-specifier component of the form 'type::'.
83  ///
84  /// \param Context The AST context in which this nested-name-specifier
85  /// resides.
86  ///
87  /// \param TemplateKWLoc The location of the 'template' keyword, if present.
88  ///
89  /// \param TL The TypeLoc that describes the type preceding the '::'.
90  ///
91  /// \param ColonColonLoc The location of the trailing '::'.
92  void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL,
93              SourceLocation ColonColonLoc);
94
95  /// Extend the current nested-name-specifier by another
96  /// nested-name-specifier component of the form 'identifier::'.
97  ///
98  /// \param Context The AST context in which this nested-name-specifier
99  /// resides.
100  ///
101  /// \param Identifier The identifier.
102  ///
103  /// \param IdentifierLoc The location of the identifier.
104  ///
105  /// \param ColonColonLoc The location of the trailing '::'.
106  void Extend(ASTContext &Context, IdentifierInfo *Identifier,
107              SourceLocation IdentifierLoc, SourceLocation ColonColonLoc);
108
109  /// Extend the current nested-name-specifier by another
110  /// nested-name-specifier component of the form 'namespace::'.
111  ///
112  /// \param Context The AST context in which this nested-name-specifier
113  /// resides.
114  ///
115  /// \param Namespace The namespace.
116  ///
117  /// \param NamespaceLoc The location of the namespace name.
118  ///
119  /// \param ColonColonLoc The location of the trailing '::'.
120  void Extend(ASTContext &Context, NamespaceDecl *Namespace,
121              SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
122
123  /// Extend the current nested-name-specifier by another
124  /// nested-name-specifier component of the form 'namespace-alias::'.
125  ///
126  /// \param Context The AST context in which this nested-name-specifier
127  /// resides.
128  ///
129  /// \param Alias The namespace alias.
130  ///
131  /// \param AliasLoc The location of the namespace alias
132  /// name.
133  ///
134  /// \param ColonColonLoc The location of the trailing '::'.
135  void Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
136              SourceLocation AliasLoc, SourceLocation ColonColonLoc);
137
138  /// Turn this (empty) nested-name-specifier into the global
139  /// nested-name-specifier '::'.
140  void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
141
142  /// Turns this (empty) nested-name-specifier into '__super'
143  /// nested-name-specifier.
144  ///
145  /// \param Context The AST context in which this nested-name-specifier
146  /// resides.
147  ///
148  /// \param RD The declaration of the class in which nested-name-specifier
149  /// appeared.
150  ///
151  /// \param SuperLoc The location of the '__super' keyword.
152  /// name.
153  ///
154  /// \param ColonColonLoc The location of the trailing '::'.
155  void MakeSuper(ASTContext &Context, CXXRecordDecl *RD,
156                 SourceLocation SuperLoc, SourceLocation ColonColonLoc);
157
158  /// Make a new nested-name-specifier from incomplete source-location
159  /// information.
160  ///
161  /// FIXME: This routine should be used very, very rarely, in cases where we
162  /// need to synthesize a nested-name-specifier. Most code should instead use
163  /// \c Adopt() with a proper \c NestedNameSpecifierLoc.
164  void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier,
165                   SourceRange R);
166
167  /// Adopt an existing nested-name-specifier (with source-range
168  /// information).
169  void Adopt(NestedNameSpecifierLoc Other);
170
171  /// Retrieve a nested-name-specifier with location information, copied
172  /// into the given AST context.
173  ///
174  /// \param Context The context into which this nested-name-specifier will be
175  /// copied.
176  NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const;
177
178  /// Retrieve the location of the name in the last qualifier
179  /// in this nested name specifier.
180  ///
181  /// For example, the location of \c bar
182  /// in
183  /// \verbatim
184  ///   \::foo::bar<0>::
185  ///           ^~~
186  /// \endverbatim
187  SourceLocation getLastQualifierNameLoc() const;
188
189  /// No scope specifier.
190  bool isEmpty() const { return Range.isInvalid() && getScopeRep() == nullptr; }
191  /// A scope specifier is present, but may be valid or invalid.
192  bool isNotEmpty() const { return !isEmpty(); }
193
194  /// An error occurred during parsing of the scope specifier.
195  bool isInvalid() const { return Range.isValid() && getScopeRep() == nullptr; }
196  /// A scope specifier is present, and it refers to a real scope.
197  bool isValid() const { return getScopeRep() != nullptr; }
198
199  /// Indicate that this nested-name-specifier is invalid.
200  void SetInvalid(SourceRange R) {
201    assert(R.isValid() && "Must have a valid source range");
202    if (Range.getBegin().isInvalid())
203      Range.setBegin(R.getBegin());
204    Range.setEnd(R.getEnd());
205    Builder.Clear();
206  }
207
208  /// Deprecated.  Some call sites intend isNotEmpty() while others intend
209  /// isValid().
210  bool isSet() const { return getScopeRep() != nullptr; }
211
212  void clear() {
213    Range = SourceRange();
214    Builder.Clear();
215  }
216
217  /// Retrieve the data associated with the source-location information.
218  char *location_data() const { return Builder.getBuffer().first; }
219
220  /// Retrieve the size of the data associated with source-location
221  /// information.
222  unsigned location_size() const { return Builder.getBuffer().second; }
223};
224
225/// Captures information about "declaration specifiers".
226///
227/// "Declaration specifiers" encompasses storage-class-specifiers,
228/// type-specifiers, type-qualifiers, and function-specifiers.
229class DeclSpec {
230public:
231  /// storage-class-specifier
232  /// \note The order of these enumerators is important for diagnostics.
233  enum SCS {
234    SCS_unspecified = 0,
235    SCS_typedef,
236    SCS_extern,
237    SCS_static,
238    SCS_auto,
239    SCS_register,
240    SCS_private_extern,
241    SCS_mutable
242  };
243
244  // Import thread storage class specifier enumeration and constants.
245  // These can be combined with SCS_extern and SCS_static.
246  typedef ThreadStorageClassSpecifier TSCS;
247  static const TSCS TSCS_unspecified = clang::TSCS_unspecified;
248  static const TSCS TSCS___thread = clang::TSCS___thread;
249  static const TSCS TSCS_thread_local = clang::TSCS_thread_local;
250  static const TSCS TSCS__Thread_local = clang::TSCS__Thread_local;
251
252  // Import type specifier width enumeration and constants.
253  typedef TypeSpecifierWidth TSW;
254  static const TSW TSW_unspecified = clang::TSW_unspecified;
255  static const TSW TSW_short = clang::TSW_short;
256  static const TSW TSW_long = clang::TSW_long;
257  static const TSW TSW_longlong = clang::TSW_longlong;
258
259  enum TSC {
260    TSC_unspecified,
261    TSC_imaginary,
262    TSC_complex
263  };
264
265  // Import type specifier sign enumeration and constants.
266  typedef TypeSpecifierSign TSS;
267  static const TSS TSS_unspecified = clang::TSS_unspecified;
268  static const TSS TSS_signed = clang::TSS_signed;
269  static const TSS TSS_unsigned = clang::TSS_unsigned;
270
271  // Import type specifier type enumeration and constants.
272  typedef TypeSpecifierType TST;
273  static const TST TST_unspecified = clang::TST_unspecified;
274  static const TST TST_void = clang::TST_void;
275  static const TST TST_char = clang::TST_char;
276  static const TST TST_wchar = clang::TST_wchar;
277  static const TST TST_char8 = clang::TST_char8;
278  static const TST TST_char16 = clang::TST_char16;
279  static const TST TST_char32 = clang::TST_char32;
280  static const TST TST_int = clang::TST_int;
281  static const TST TST_int128 = clang::TST_int128;
282  static const TST TST_extint = clang::TST_extint;
283  static const TST TST_half = clang::TST_half;
284  static const TST TST_BFloat16 = clang::TST_BFloat16;
285  static const TST TST_float = clang::TST_float;
286  static const TST TST_double = clang::TST_double;
287  static const TST TST_float16 = clang::TST_Float16;
288  static const TST TST_accum = clang::TST_Accum;
289  static const TST TST_fract = clang::TST_Fract;
290  static const TST TST_float128 = clang::TST_float128;
291  static const TST TST_bool = clang::TST_bool;
292  static const TST TST_decimal32 = clang::TST_decimal32;
293  static const TST TST_decimal64 = clang::TST_decimal64;
294  static const TST TST_decimal128 = clang::TST_decimal128;
295  static const TST TST_enum = clang::TST_enum;
296  static const TST TST_union = clang::TST_union;
297  static const TST TST_struct = clang::TST_struct;
298  static const TST TST_interface = clang::TST_interface;
299  static const TST TST_class = clang::TST_class;
300  static const TST TST_typename = clang::TST_typename;
301  static const TST TST_typeofType = clang::TST_typeofType;
302  static const TST TST_typeofExpr = clang::TST_typeofExpr;
303  static const TST TST_decltype = clang::TST_decltype;
304  static const TST TST_decltype_auto = clang::TST_decltype_auto;
305  static const TST TST_underlyingType = clang::TST_underlyingType;
306  static const TST TST_auto = clang::TST_auto;
307  static const TST TST_auto_type = clang::TST_auto_type;
308  static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
309  static const TST TST_atomic = clang::TST_atomic;
310#define GENERIC_IMAGE_TYPE(ImgType, Id) \
311  static const TST TST_##ImgType##_t = clang::TST_##ImgType##_t;
312#include "clang/Basic/OpenCLImageTypes.def"
313  static const TST TST_error = clang::TST_error;
314
315  // type-qualifiers
316  enum TQ {   // NOTE: These flags must be kept in sync with Qualifiers::TQ.
317    TQ_unspecified = 0,
318    TQ_const       = 1,
319    TQ_restrict    = 2,
320    TQ_volatile    = 4,
321    TQ_unaligned   = 8,
322    // This has no corresponding Qualifiers::TQ value, because it's not treated
323    // as a qualifier in our type system.
324    TQ_atomic      = 16
325  };
326
327  /// ParsedSpecifiers - Flags to query which specifiers were applied.  This is
328  /// returned by getParsedSpecifiers.
329  enum ParsedSpecifiers {
330    PQ_None                  = 0,
331    PQ_StorageClassSpecifier = 1,
332    PQ_TypeSpecifier         = 2,
333    PQ_TypeQualifier         = 4,
334    PQ_FunctionSpecifier     = 8
335    // FIXME: Attributes should be included here.
336  };
337
338private:
339  // storage-class-specifier
340  /*SCS*/unsigned StorageClassSpec : 3;
341  /*TSCS*/unsigned ThreadStorageClassSpec : 2;
342  unsigned SCS_extern_in_linkage_spec : 1;
343
344  // type-specifier
345  /*TSW*/unsigned TypeSpecWidth : 2;
346  /*TSC*/unsigned TypeSpecComplex : 2;
347  /*TSS*/unsigned TypeSpecSign : 2;
348  /*TST*/unsigned TypeSpecType : 6;
349  unsigned TypeAltiVecVector : 1;
350  unsigned TypeAltiVecPixel : 1;
351  unsigned TypeAltiVecBool : 1;
352  unsigned TypeSpecOwned : 1;
353  unsigned TypeSpecPipe : 1;
354  unsigned TypeSpecSat : 1;
355  unsigned ConstrainedAuto : 1;
356
357  // type-qualifiers
358  unsigned TypeQualifiers : 5;  // Bitwise OR of TQ.
359
360  // function-specifier
361  unsigned FS_inline_specified : 1;
362  unsigned FS_forceinline_specified: 1;
363  unsigned FS_virtual_specified : 1;
364  unsigned FS_noreturn_specified : 1;
365
366  // friend-specifier
367  unsigned Friend_specified : 1;
368
369  // constexpr-specifier
370  unsigned ConstexprSpecifier : 2;
371
372  union {
373    UnionParsedType TypeRep;
374    Decl *DeclRep;
375    Expr *ExprRep;
376    TemplateIdAnnotation *TemplateIdRep;
377  };
378
379  /// ExplicitSpecifier - Store information about explicit spicifer.
380  ExplicitSpecifier FS_explicit_specifier;
381
382  // attributes.
383  ParsedAttributes Attrs;
384
385  // Scope specifier for the type spec, if applicable.
386  CXXScopeSpec TypeScope;
387
388  // SourceLocation info.  These are null if the item wasn't specified or if
389  // the setting was synthesized.
390  SourceRange Range;
391
392  SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc;
393  SourceRange TSWRange;
394  SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc, TSSatLoc;
395  /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
396  /// typename, then this is the location of the named type (if present);
397  /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
398  /// TSTNameLoc provides source range info for tag types.
399  SourceLocation TSTNameLoc;
400  SourceRange TypeofParensRange;
401  SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc,
402      TQ_unalignedLoc;
403  SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc;
404  SourceLocation FS_explicitCloseParenLoc;
405  SourceLocation FS_forceinlineLoc;
406  SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc;
407  SourceLocation TQ_pipeLoc;
408
409  WrittenBuiltinSpecs writtenBS;
410  void SaveWrittenBuiltinSpecs();
411
412  ObjCDeclSpec *ObjCQualifiers;
413
414  static bool isTypeRep(TST T) {
415    return (T == TST_typename || T == TST_typeofType ||
416            T == TST_underlyingType || T == TST_atomic);
417  }
418  static bool isExprRep(TST T) {
419    return (T == TST_typeofExpr || T == TST_decltype || T == TST_extint);
420  }
421  static bool isTemplateIdRep(TST T) {
422    return (T == TST_auto || T == TST_decltype_auto);
423  }
424
425  DeclSpec(const DeclSpec &) = delete;
426  void operator=(const DeclSpec &) = delete;
427public:
428  static bool isDeclRep(TST T) {
429    return (T == TST_enum || T == TST_struct ||
430            T == TST_interface || T == TST_union ||
431            T == TST_class);
432  }
433
434  DeclSpec(AttributeFactory &attrFactory)
435      : StorageClassSpec(SCS_unspecified),
436        ThreadStorageClassSpec(TSCS_unspecified),
437        SCS_extern_in_linkage_spec(false), TypeSpecWidth(TSW_unspecified),
438        TypeSpecComplex(TSC_unspecified), TypeSpecSign(TSS_unspecified),
439        TypeSpecType(TST_unspecified), TypeAltiVecVector(false),
440        TypeAltiVecPixel(false), TypeAltiVecBool(false), TypeSpecOwned(false),
441        TypeSpecPipe(false), TypeSpecSat(false), ConstrainedAuto(false),
442        TypeQualifiers(TQ_unspecified),
443        FS_inline_specified(false), FS_forceinline_specified(false),
444        FS_virtual_specified(false), FS_noreturn_specified(false),
445        Friend_specified(false), ConstexprSpecifier(CSK_unspecified),
446        FS_explicit_specifier(), Attrs(attrFactory), writtenBS(),
447        ObjCQualifiers(nullptr) {}
448
449  // storage-class-specifier
450  SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
451  TSCS getThreadStorageClassSpec() const {
452    return (TSCS)ThreadStorageClassSpec;
453  }
454  bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
455  void setExternInLinkageSpec(bool Value) {
456    SCS_extern_in_linkage_spec = Value;
457  }
458
459  SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
460  SourceLocation getThreadStorageClassSpecLoc() const {
461    return ThreadStorageClassSpecLoc;
462  }
463
464  void ClearStorageClassSpecs() {
465    StorageClassSpec           = DeclSpec::SCS_unspecified;
466    ThreadStorageClassSpec     = DeclSpec::TSCS_unspecified;
467    SCS_extern_in_linkage_spec = false;
468    StorageClassSpecLoc        = SourceLocation();
469    ThreadStorageClassSpecLoc  = SourceLocation();
470  }
471
472  void ClearTypeSpecType() {
473    TypeSpecType = DeclSpec::TST_unspecified;
474    TypeSpecOwned = false;
475    TSTLoc = SourceLocation();
476  }
477
478  // type-specifier
479  TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; }
480  TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
481  TSS getTypeSpecSign() const { return (TSS)TypeSpecSign; }
482  TST getTypeSpecType() const { return (TST)TypeSpecType; }
483  bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
484  bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
485  bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
486  bool isTypeSpecOwned() const { return TypeSpecOwned; }
487  bool isTypeRep() const { return isTypeRep((TST) TypeSpecType); }
488  bool isTypeSpecPipe() const { return TypeSpecPipe; }
489  bool isTypeSpecSat() const { return TypeSpecSat; }
490  bool isConstrainedAuto() const { return ConstrainedAuto; }
491
492  ParsedType getRepAsType() const {
493    assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type");
494    return TypeRep;
495  }
496  Decl *getRepAsDecl() const {
497    assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl");
498    return DeclRep;
499  }
500  Expr *getRepAsExpr() const {
501    assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr");
502    return ExprRep;
503  }
504  TemplateIdAnnotation *getRepAsTemplateId() const {
505    assert(isTemplateIdRep((TST) TypeSpecType) &&
506           "DeclSpec does not store a template id");
507    return TemplateIdRep;
508  }
509  CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
510  const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
511
512  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
513  SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
514  SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
515
516  SourceLocation getTypeSpecWidthLoc() const { return TSWRange.getBegin(); }
517  SourceRange getTypeSpecWidthRange() const { return TSWRange; }
518  SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
519  SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
520  SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
521  SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
522  SourceLocation getTypeSpecSatLoc() const { return TSSatLoc; }
523
524  SourceLocation getTypeSpecTypeNameLoc() const {
525    assert(isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename);
526    return TSTNameLoc;
527  }
528
529  SourceRange getTypeofParensRange() const { return TypeofParensRange; }
530  void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; }
531
532  bool hasAutoTypeSpec() const {
533    return (TypeSpecType == TST_auto || TypeSpecType == TST_auto_type ||
534            TypeSpecType == TST_decltype_auto);
535  }
536
537  bool hasTagDefinition() const;
538
539  /// Turn a type-specifier-type into a string like "_Bool" or "union".
540  static const char *getSpecifierName(DeclSpec::TST T,
541                                      const PrintingPolicy &Policy);
542  static const char *getSpecifierName(DeclSpec::TQ Q);
543  static const char *getSpecifierName(DeclSpec::TSS S);
544  static const char *getSpecifierName(DeclSpec::TSC C);
545  static const char *getSpecifierName(DeclSpec::TSW W);
546  static const char *getSpecifierName(DeclSpec::SCS S);
547  static const char *getSpecifierName(DeclSpec::TSCS S);
548  static const char *getSpecifierName(ConstexprSpecKind C);
549
550  // type-qualifiers
551
552  /// getTypeQualifiers - Return a set of TQs.
553  unsigned getTypeQualifiers() const { return TypeQualifiers; }
554  SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
555  SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
556  SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
557  SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; }
558  SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; }
559  SourceLocation getPipeLoc() const { return TQ_pipeLoc; }
560
561  /// Clear out all of the type qualifiers.
562  void ClearTypeQualifiers() {
563    TypeQualifiers = 0;
564    TQ_constLoc = SourceLocation();
565    TQ_restrictLoc = SourceLocation();
566    TQ_volatileLoc = SourceLocation();
567    TQ_atomicLoc = SourceLocation();
568    TQ_unalignedLoc = SourceLocation();
569    TQ_pipeLoc = SourceLocation();
570  }
571
572  // function-specifier
573  bool isInlineSpecified() const {
574    return FS_inline_specified | FS_forceinline_specified;
575  }
576  SourceLocation getInlineSpecLoc() const {
577    return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc;
578  }
579
580  ExplicitSpecifier getExplicitSpecifier() const {
581    return FS_explicit_specifier;
582  }
583
584  bool isVirtualSpecified() const { return FS_virtual_specified; }
585  SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
586
587  bool hasExplicitSpecifier() const {
588    return FS_explicit_specifier.isSpecified();
589  }
590  SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
591  SourceRange getExplicitSpecRange() const {
592    return FS_explicit_specifier.getExpr()
593               ? SourceRange(FS_explicitLoc, FS_explicitCloseParenLoc)
594               : SourceRange(FS_explicitLoc);
595  }
596
597  bool isNoreturnSpecified() const { return FS_noreturn_specified; }
598  SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; }
599
600  void ClearFunctionSpecs() {
601    FS_inline_specified = false;
602    FS_inlineLoc = SourceLocation();
603    FS_forceinline_specified = false;
604    FS_forceinlineLoc = SourceLocation();
605    FS_virtual_specified = false;
606    FS_virtualLoc = SourceLocation();
607    FS_explicit_specifier = ExplicitSpecifier();
608    FS_explicitLoc = SourceLocation();
609    FS_explicitCloseParenLoc = SourceLocation();
610    FS_noreturn_specified = false;
611    FS_noreturnLoc = SourceLocation();
612  }
613
614  /// This method calls the passed in handler on each CVRU qual being
615  /// set.
616  /// Handle - a handler to be invoked.
617  void forEachCVRUQualifier(
618      llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
619
620  /// This method calls the passed in handler on each qual being
621  /// set.
622  /// Handle - a handler to be invoked.
623  void forEachQualifier(
624      llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
625
626  /// Return true if any type-specifier has been found.
627  bool hasTypeSpecifier() const {
628    return getTypeSpecType() != DeclSpec::TST_unspecified ||
629           getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
630           getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
631           getTypeSpecSign() != DeclSpec::TSS_unspecified;
632  }
633
634  /// Return a bitmask of which flavors of specifiers this
635  /// DeclSpec includes.
636  unsigned getParsedSpecifiers() const;
637
638  /// isEmpty - Return true if this declaration specifier is completely empty:
639  /// no tokens were parsed in the production of it.
640  bool isEmpty() const {
641    return getParsedSpecifiers() == DeclSpec::PQ_None;
642  }
643
644  void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
645  void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
646
647  /// These methods set the specified attribute of the DeclSpec and
648  /// return false if there was no error.  If an error occurs (for
649  /// example, if we tried to set "auto" on a spec with "extern"
650  /// already set), they return true and set PrevSpec and DiagID
651  /// such that
652  ///   Diag(Loc, DiagID) << PrevSpec;
653  /// will yield a useful result.
654  ///
655  /// TODO: use a more general approach that still allows these
656  /// diagnostics to be ignored when desired.
657  bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
658                           const char *&PrevSpec, unsigned &DiagID,
659                           const PrintingPolicy &Policy);
660  bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
661                                 const char *&PrevSpec, unsigned &DiagID);
662  bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec,
663                        unsigned &DiagID, const PrintingPolicy &Policy);
664  bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
665                          unsigned &DiagID);
666  bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec,
667                       unsigned &DiagID);
668  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
669                       unsigned &DiagID, const PrintingPolicy &Policy);
670  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
671                       unsigned &DiagID, ParsedType Rep,
672                       const PrintingPolicy &Policy);
673  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
674                       unsigned &DiagID, TypeResult Rep,
675                       const PrintingPolicy &Policy) {
676    if (Rep.isInvalid())
677      return SetTypeSpecError();
678    return SetTypeSpecType(T, Loc, PrevSpec, DiagID, Rep.get(), Policy);
679  }
680  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
681                       unsigned &DiagID, Decl *Rep, bool Owned,
682                       const PrintingPolicy &Policy);
683  bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
684                       SourceLocation TagNameLoc, const char *&PrevSpec,
685                       unsigned &DiagID, ParsedType Rep,
686                       const PrintingPolicy &Policy);
687  bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
688                       SourceLocation TagNameLoc, const char *&PrevSpec,
689                       unsigned &DiagID, Decl *Rep, bool Owned,
690                       const PrintingPolicy &Policy);
691  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
692                       unsigned &DiagID, TemplateIdAnnotation *Rep,
693                       const PrintingPolicy &Policy);
694
695  bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
696                       unsigned &DiagID, Expr *Rep,
697                       const PrintingPolicy &policy);
698  bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
699                       const char *&PrevSpec, unsigned &DiagID,
700                       const PrintingPolicy &Policy);
701  bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
702                       const char *&PrevSpec, unsigned &DiagID,
703                       const PrintingPolicy &Policy);
704  bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
705                       const char *&PrevSpec, unsigned &DiagID,
706                       const PrintingPolicy &Policy);
707  bool SetTypePipe(bool isPipe, SourceLocation Loc,
708                       const char *&PrevSpec, unsigned &DiagID,
709                       const PrintingPolicy &Policy);
710  bool SetExtIntType(SourceLocation KWLoc, Expr *BitWidth,
711                     const char *&PrevSpec, unsigned &DiagID,
712                     const PrintingPolicy &Policy);
713  bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec,
714                      unsigned &DiagID);
715  bool SetTypeSpecError();
716  void UpdateDeclRep(Decl *Rep) {
717    assert(isDeclRep((TST) TypeSpecType));
718    DeclRep = Rep;
719  }
720  void UpdateTypeRep(ParsedType Rep) {
721    assert(isTypeRep((TST) TypeSpecType));
722    TypeRep = Rep;
723  }
724  void UpdateExprRep(Expr *Rep) {
725    assert(isExprRep((TST) TypeSpecType));
726    ExprRep = Rep;
727  }
728
729  bool SetTypeQual(TQ T, SourceLocation Loc);
730
731  bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
732                   unsigned &DiagID, const LangOptions &Lang);
733
734  bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
735                             unsigned &DiagID);
736  bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
737                                  unsigned &DiagID);
738  bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
739                              unsigned &DiagID);
740  bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
741                               unsigned &DiagID, ExplicitSpecifier ExplicitSpec,
742                               SourceLocation CloseParenLoc);
743  bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
744                               unsigned &DiagID);
745
746  bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
747                     unsigned &DiagID);
748  bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
749                            unsigned &DiagID);
750  bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc,
751                        const char *&PrevSpec, unsigned &DiagID);
752
753  bool isFriendSpecified() const { return Friend_specified; }
754  SourceLocation getFriendSpecLoc() const { return FriendLoc; }
755
756  bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
757  SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
758
759  ConstexprSpecKind getConstexprSpecifier() const {
760    return ConstexprSpecKind(ConstexprSpecifier);
761  }
762
763  SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
764  bool hasConstexprSpecifier() const {
765    return ConstexprSpecifier != CSK_unspecified;
766  }
767
768  void ClearConstexprSpec() {
769    ConstexprSpecifier = CSK_unspecified;
770    ConstexprLoc = SourceLocation();
771  }
772
773  AttributePool &getAttributePool() const {
774    return Attrs.getPool();
775  }
776
777  /// Concatenates two attribute lists.
778  ///
779  /// The GCC attribute syntax allows for the following:
780  ///
781  /// \code
782  /// short __attribute__(( unused, deprecated ))
783  /// int __attribute__(( may_alias, aligned(16) )) var;
784  /// \endcode
785  ///
786  /// This declares 4 attributes using 2 lists. The following syntax is
787  /// also allowed and equivalent to the previous declaration.
788  ///
789  /// \code
790  /// short __attribute__((unused)) __attribute__((deprecated))
791  /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
792  /// \endcode
793  ///
794  void addAttributes(ParsedAttributesView &AL) {
795    Attrs.addAll(AL.begin(), AL.end());
796  }
797
798  bool hasAttributes() const { return !Attrs.empty(); }
799
800  ParsedAttributes &getAttributes() { return Attrs; }
801  const ParsedAttributes &getAttributes() const { return Attrs; }
802
803  void takeAttributesFrom(ParsedAttributes &attrs) {
804    Attrs.takeAllFrom(attrs);
805  }
806
807  /// Finish - This does final analysis of the declspec, issuing diagnostics for
808  /// things like "_Imaginary" (lacking an FP type).  After calling this method,
809  /// DeclSpec is guaranteed self-consistent, even if an error occurred.
810  void Finish(Sema &S, const PrintingPolicy &Policy);
811
812  const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
813    return writtenBS;
814  }
815
816  ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
817  void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
818
819  /// Checks if this DeclSpec can stand alone, without a Declarator.
820  ///
821  /// Only tag declspecs can stand alone.
822  bool isMissingDeclaratorOk();
823};
824
825/// Captures information about "declaration specifiers" specific to
826/// Objective-C.
827class ObjCDeclSpec {
828public:
829  /// ObjCDeclQualifier - Qualifier used on types in method
830  /// declarations.  Not all combinations are sensible.  Parameters
831  /// can be one of { in, out, inout } with one of { bycopy, byref }.
832  /// Returns can either be { oneway } or not.
833  ///
834  /// This should be kept in sync with Decl::ObjCDeclQualifier.
835  enum ObjCDeclQualifier {
836    DQ_None = 0x0,
837    DQ_In = 0x1,
838    DQ_Inout = 0x2,
839    DQ_Out = 0x4,
840    DQ_Bycopy = 0x8,
841    DQ_Byref = 0x10,
842    DQ_Oneway = 0x20,
843    DQ_CSNullability = 0x40
844  };
845
846  ObjCDeclSpec()
847      : objcDeclQualifier(DQ_None),
848        PropertyAttributes(ObjCPropertyAttribute::kind_noattr), Nullability(0),
849        GetterName(nullptr), SetterName(nullptr) {}
850
851  ObjCDeclQualifier getObjCDeclQualifier() const {
852    return (ObjCDeclQualifier)objcDeclQualifier;
853  }
854  void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
855    objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
856  }
857  void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
858    objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
859  }
860
861  ObjCPropertyAttribute::Kind getPropertyAttributes() const {
862    return ObjCPropertyAttribute::Kind(PropertyAttributes);
863  }
864  void setPropertyAttributes(ObjCPropertyAttribute::Kind PRVal) {
865    PropertyAttributes =
866        (ObjCPropertyAttribute::Kind)(PropertyAttributes | PRVal);
867  }
868
869  NullabilityKind getNullability() const {
870    assert(
871        ((getObjCDeclQualifier() & DQ_CSNullability) ||
872         (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&
873        "Objective-C declspec doesn't have nullability");
874    return static_cast<NullabilityKind>(Nullability);
875  }
876
877  SourceLocation getNullabilityLoc() const {
878    assert(
879        ((getObjCDeclQualifier() & DQ_CSNullability) ||
880         (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&
881        "Objective-C declspec doesn't have nullability");
882    return NullabilityLoc;
883  }
884
885  void setNullability(SourceLocation loc, NullabilityKind kind) {
886    assert(
887        ((getObjCDeclQualifier() & DQ_CSNullability) ||
888         (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&
889        "Set the nullability declspec or property attribute first");
890    Nullability = static_cast<unsigned>(kind);
891    NullabilityLoc = loc;
892  }
893
894  const IdentifierInfo *getGetterName() const { return GetterName; }
895  IdentifierInfo *getGetterName() { return GetterName; }
896  SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
897  void setGetterName(IdentifierInfo *name, SourceLocation loc) {
898    GetterName = name;
899    GetterNameLoc = loc;
900  }
901
902  const IdentifierInfo *getSetterName() const { return SetterName; }
903  IdentifierInfo *getSetterName() { return SetterName; }
904  SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
905  void setSetterName(IdentifierInfo *name, SourceLocation loc) {
906    SetterName = name;
907    SetterNameLoc = loc;
908  }
909
910private:
911  // FIXME: These two are unrelated and mutually exclusive. So perhaps
912  // we can put them in a union to reflect their mutual exclusivity
913  // (space saving is negligible).
914  unsigned objcDeclQualifier : 7;
915
916  // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttribute::Kind
917  unsigned PropertyAttributes : NumObjCPropertyAttrsBits;
918
919  unsigned Nullability : 2;
920
921  SourceLocation NullabilityLoc;
922
923  IdentifierInfo *GetterName;    // getter name or NULL if no getter
924  IdentifierInfo *SetterName;    // setter name or NULL if no setter
925  SourceLocation GetterNameLoc; // location of the getter attribute's value
926  SourceLocation SetterNameLoc; // location of the setter attribute's value
927
928};
929
930/// Describes the kind of unqualified-id parsed.
931enum class UnqualifiedIdKind {
932  /// An identifier.
933  IK_Identifier,
934  /// An overloaded operator name, e.g., operator+.
935  IK_OperatorFunctionId,
936  /// A conversion function name, e.g., operator int.
937  IK_ConversionFunctionId,
938  /// A user-defined literal name, e.g., operator "" _i.
939  IK_LiteralOperatorId,
940  /// A constructor name.
941  IK_ConstructorName,
942  /// A constructor named via a template-id.
943  IK_ConstructorTemplateId,
944  /// A destructor name.
945  IK_DestructorName,
946  /// A template-id, e.g., f<int>.
947  IK_TemplateId,
948  /// An implicit 'self' parameter
949  IK_ImplicitSelfParam,
950  /// A deduction-guide name (a template-name)
951  IK_DeductionGuideName
952};
953
954/// Represents a C++ unqualified-id that has been parsed.
955class UnqualifiedId {
956private:
957  UnqualifiedId(const UnqualifiedId &Other) = delete;
958  const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
959
960public:
961  /// Describes the kind of unqualified-id parsed.
962  UnqualifiedIdKind Kind;
963
964  struct OFI {
965    /// The kind of overloaded operator.
966    OverloadedOperatorKind Operator;
967
968    /// The source locations of the individual tokens that name
969    /// the operator, e.g., the "new", "[", and "]" tokens in
970    /// operator new [].
971    ///
972    /// Different operators have different numbers of tokens in their name,
973    /// up to three. Any remaining source locations in this array will be
974    /// set to an invalid value for operators with fewer than three tokens.
975    unsigned SymbolLocations[3];
976  };
977
978  /// Anonymous union that holds extra data associated with the
979  /// parsed unqualified-id.
980  union {
981    /// When Kind == IK_Identifier, the parsed identifier, or when
982    /// Kind == IK_UserLiteralId, the identifier suffix.
983    IdentifierInfo *Identifier;
984
985    /// When Kind == IK_OperatorFunctionId, the overloaded operator
986    /// that we parsed.
987    struct OFI OperatorFunctionId;
988
989    /// When Kind == IK_ConversionFunctionId, the type that the
990    /// conversion function names.
991    UnionParsedType ConversionFunctionId;
992
993    /// When Kind == IK_ConstructorName, the class-name of the type
994    /// whose constructor is being referenced.
995    UnionParsedType ConstructorName;
996
997    /// When Kind == IK_DestructorName, the type referred to by the
998    /// class-name.
999    UnionParsedType DestructorName;
1000
1001    /// When Kind == IK_DeductionGuideName, the parsed template-name.
1002    UnionParsedTemplateTy TemplateName;
1003
1004    /// When Kind == IK_TemplateId or IK_ConstructorTemplateId,
1005    /// the template-id annotation that contains the template name and
1006    /// template arguments.
1007    TemplateIdAnnotation *TemplateId;
1008  };
1009
1010  /// The location of the first token that describes this unqualified-id,
1011  /// which will be the location of the identifier, "operator" keyword,
1012  /// tilde (for a destructor), or the template name of a template-id.
1013  SourceLocation StartLocation;
1014
1015  /// The location of the last token that describes this unqualified-id.
1016  SourceLocation EndLocation;
1017
1018  UnqualifiedId()
1019      : Kind(UnqualifiedIdKind::IK_Identifier), Identifier(nullptr) {}
1020
1021  /// Clear out this unqualified-id, setting it to default (invalid)
1022  /// state.
1023  void clear() {
1024    Kind = UnqualifiedIdKind::IK_Identifier;
1025    Identifier = nullptr;
1026    StartLocation = SourceLocation();
1027    EndLocation = SourceLocation();
1028  }
1029
1030  /// Determine whether this unqualified-id refers to a valid name.
1031  bool isValid() const { return StartLocation.isValid(); }
1032
1033  /// Determine whether this unqualified-id refers to an invalid name.
1034  bool isInvalid() const { return !isValid(); }
1035
1036  /// Determine what kind of name we have.
1037  UnqualifiedIdKind getKind() const { return Kind; }
1038  void setKind(UnqualifiedIdKind kind) { Kind = kind; }
1039
1040  /// Specify that this unqualified-id was parsed as an identifier.
1041  ///
1042  /// \param Id the parsed identifier.
1043  /// \param IdLoc the location of the parsed identifier.
1044  void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
1045    Kind = UnqualifiedIdKind::IK_Identifier;
1046    Identifier = const_cast<IdentifierInfo *>(Id);
1047    StartLocation = EndLocation = IdLoc;
1048  }
1049
1050  /// Specify that this unqualified-id was parsed as an
1051  /// operator-function-id.
1052  ///
1053  /// \param OperatorLoc the location of the 'operator' keyword.
1054  ///
1055  /// \param Op the overloaded operator.
1056  ///
1057  /// \param SymbolLocations the locations of the individual operator symbols
1058  /// in the operator.
1059  void setOperatorFunctionId(SourceLocation OperatorLoc,
1060                             OverloadedOperatorKind Op,
1061                             SourceLocation SymbolLocations[3]);
1062
1063  /// Specify that this unqualified-id was parsed as a
1064  /// conversion-function-id.
1065  ///
1066  /// \param OperatorLoc the location of the 'operator' keyword.
1067  ///
1068  /// \param Ty the type to which this conversion function is converting.
1069  ///
1070  /// \param EndLoc the location of the last token that makes up the type name.
1071  void setConversionFunctionId(SourceLocation OperatorLoc,
1072                               ParsedType Ty,
1073                               SourceLocation EndLoc) {
1074    Kind = UnqualifiedIdKind::IK_ConversionFunctionId;
1075    StartLocation = OperatorLoc;
1076    EndLocation = EndLoc;
1077    ConversionFunctionId = Ty;
1078  }
1079
1080  /// Specific that this unqualified-id was parsed as a
1081  /// literal-operator-id.
1082  ///
1083  /// \param Id the parsed identifier.
1084  ///
1085  /// \param OpLoc the location of the 'operator' keyword.
1086  ///
1087  /// \param IdLoc the location of the identifier.
1088  void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
1089                              SourceLocation IdLoc) {
1090    Kind = UnqualifiedIdKind::IK_LiteralOperatorId;
1091    Identifier = const_cast<IdentifierInfo *>(Id);
1092    StartLocation = OpLoc;
1093    EndLocation = IdLoc;
1094  }
1095
1096  /// Specify that this unqualified-id was parsed as a constructor name.
1097  ///
1098  /// \param ClassType the class type referred to by the constructor name.
1099  ///
1100  /// \param ClassNameLoc the location of the class name.
1101  ///
1102  /// \param EndLoc the location of the last token that makes up the type name.
1103  void setConstructorName(ParsedType ClassType,
1104                          SourceLocation ClassNameLoc,
1105                          SourceLocation EndLoc) {
1106    Kind = UnqualifiedIdKind::IK_ConstructorName;
1107    StartLocation = ClassNameLoc;
1108    EndLocation = EndLoc;
1109    ConstructorName = ClassType;
1110  }
1111
1112  /// Specify that this unqualified-id was parsed as a
1113  /// template-id that names a constructor.
1114  ///
1115  /// \param TemplateId the template-id annotation that describes the parsed
1116  /// template-id. This UnqualifiedId instance will take ownership of the
1117  /// \p TemplateId and will free it on destruction.
1118  void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
1119
1120  /// Specify that this unqualified-id was parsed as a destructor name.
1121  ///
1122  /// \param TildeLoc the location of the '~' that introduces the destructor
1123  /// name.
1124  ///
1125  /// \param ClassType the name of the class referred to by the destructor name.
1126  void setDestructorName(SourceLocation TildeLoc,
1127                         ParsedType ClassType,
1128                         SourceLocation EndLoc) {
1129    Kind = UnqualifiedIdKind::IK_DestructorName;
1130    StartLocation = TildeLoc;
1131    EndLocation = EndLoc;
1132    DestructorName = ClassType;
1133  }
1134
1135  /// Specify that this unqualified-id was parsed as a template-id.
1136  ///
1137  /// \param TemplateId the template-id annotation that describes the parsed
1138  /// template-id. This UnqualifiedId instance will take ownership of the
1139  /// \p TemplateId and will free it on destruction.
1140  void setTemplateId(TemplateIdAnnotation *TemplateId);
1141
1142  /// Specify that this unqualified-id was parsed as a template-name for
1143  /// a deduction-guide.
1144  ///
1145  /// \param Template The parsed template-name.
1146  /// \param TemplateLoc The location of the parsed template-name.
1147  void setDeductionGuideName(ParsedTemplateTy Template,
1148                             SourceLocation TemplateLoc) {
1149    Kind = UnqualifiedIdKind::IK_DeductionGuideName;
1150    TemplateName = Template;
1151    StartLocation = EndLocation = TemplateLoc;
1152  }
1153
1154  /// Return the source range that covers this unqualified-id.
1155  SourceRange getSourceRange() const LLVM_READONLY {
1156    return SourceRange(StartLocation, EndLocation);
1157  }
1158  SourceLocation getBeginLoc() const LLVM_READONLY { return StartLocation; }
1159  SourceLocation getEndLoc() const LLVM_READONLY { return EndLocation; }
1160};
1161
1162/// A set of tokens that has been cached for later parsing.
1163typedef SmallVector<Token, 4> CachedTokens;
1164
1165/// One instance of this struct is used for each type in a
1166/// declarator that is parsed.
1167///
1168/// This is intended to be a small value object.
1169struct DeclaratorChunk {
1170  enum {
1171    Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe
1172  } Kind;
1173
1174  /// Loc - The place where this type was defined.
1175  SourceLocation Loc;
1176  /// EndLoc - If valid, the place where this chunck ends.
1177  SourceLocation EndLoc;
1178
1179  SourceRange getSourceRange() const {
1180    if (EndLoc.isInvalid())
1181      return SourceRange(Loc, Loc);
1182    return SourceRange(Loc, EndLoc);
1183  }
1184
1185  ParsedAttributesView AttrList;
1186
1187  struct PointerTypeInfo {
1188    /// The type qualifiers: const/volatile/restrict/unaligned/atomic.
1189    unsigned TypeQuals : 5;
1190
1191    /// The location of the const-qualifier, if any.
1192    unsigned ConstQualLoc;
1193
1194    /// The location of the volatile-qualifier, if any.
1195    unsigned VolatileQualLoc;
1196
1197    /// The location of the restrict-qualifier, if any.
1198    unsigned RestrictQualLoc;
1199
1200    /// The location of the _Atomic-qualifier, if any.
1201    unsigned AtomicQualLoc;
1202
1203    /// The location of the __unaligned-qualifier, if any.
1204    unsigned UnalignedQualLoc;
1205
1206    void destroy() {
1207    }
1208  };
1209
1210  struct ReferenceTypeInfo {
1211    /// The type qualifier: restrict. [GNU] C++ extension
1212    bool HasRestrict : 1;
1213    /// True if this is an lvalue reference, false if it's an rvalue reference.
1214    bool LValueRef : 1;
1215    void destroy() {
1216    }
1217  };
1218
1219  struct ArrayTypeInfo {
1220    /// The type qualifiers for the array:
1221    /// const/volatile/restrict/__unaligned/_Atomic.
1222    unsigned TypeQuals : 5;
1223
1224    /// True if this dimension included the 'static' keyword.
1225    unsigned hasStatic : 1;
1226
1227    /// True if this dimension was [*].  In this case, NumElts is null.
1228    unsigned isStar : 1;
1229
1230    /// This is the size of the array, or null if [] or [*] was specified.
1231    /// Since the parser is multi-purpose, and we don't want to impose a root
1232    /// expression class on all clients, NumElts is untyped.
1233    Expr *NumElts;
1234
1235    void destroy() {}
1236  };
1237
1238  /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1239  /// declarator is parsed.  There are two interesting styles of parameters
1240  /// here:
1241  /// K&R-style identifier lists and parameter type lists.  K&R-style identifier
1242  /// lists will have information about the identifier, but no type information.
1243  /// Parameter type lists will have type info (if the actions module provides
1244  /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1245  struct ParamInfo {
1246    IdentifierInfo *Ident;
1247    SourceLocation IdentLoc;
1248    Decl *Param;
1249
1250    /// DefaultArgTokens - When the parameter's default argument
1251    /// cannot be parsed immediately (because it occurs within the
1252    /// declaration of a member function), it will be stored here as a
1253    /// sequence of tokens to be parsed once the class definition is
1254    /// complete. Non-NULL indicates that there is a default argument.
1255    std::unique_ptr<CachedTokens> DefaultArgTokens;
1256
1257    ParamInfo() = default;
1258    ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1259              Decl *param,
1260              std::unique_ptr<CachedTokens> DefArgTokens = nullptr)
1261      : Ident(ident), IdentLoc(iloc), Param(param),
1262        DefaultArgTokens(std::move(DefArgTokens)) {}
1263  };
1264
1265  struct TypeAndRange {
1266    ParsedType Ty;
1267    SourceRange Range;
1268  };
1269
1270  struct FunctionTypeInfo {
1271    /// hasPrototype - This is true if the function had at least one typed
1272    /// parameter.  If the function is () or (a,b,c), then it has no prototype,
1273    /// and is treated as a K&R-style function.
1274    unsigned hasPrototype : 1;
1275
1276    /// isVariadic - If this function has a prototype, and if that
1277    /// proto ends with ',...)', this is true. When true, EllipsisLoc
1278    /// contains the location of the ellipsis.
1279    unsigned isVariadic : 1;
1280
1281    /// Can this declaration be a constructor-style initializer?
1282    unsigned isAmbiguous : 1;
1283
1284    /// Whether the ref-qualifier (if any) is an lvalue reference.
1285    /// Otherwise, it's an rvalue reference.
1286    unsigned RefQualifierIsLValueRef : 1;
1287
1288    /// ExceptionSpecType - An ExceptionSpecificationType value.
1289    unsigned ExceptionSpecType : 4;
1290
1291    /// DeleteParams - If this is true, we need to delete[] Params.
1292    unsigned DeleteParams : 1;
1293
1294    /// HasTrailingReturnType - If this is true, a trailing return type was
1295    /// specified.
1296    unsigned HasTrailingReturnType : 1;
1297
1298    /// The location of the left parenthesis in the source.
1299    unsigned LParenLoc;
1300
1301    /// When isVariadic is true, the location of the ellipsis in the source.
1302    unsigned EllipsisLoc;
1303
1304    /// The location of the right parenthesis in the source.
1305    unsigned RParenLoc;
1306
1307    /// NumParams - This is the number of formal parameters specified by the
1308    /// declarator.
1309    unsigned NumParams;
1310
1311    /// NumExceptionsOrDecls - This is the number of types in the
1312    /// dynamic-exception-decl, if the function has one. In C, this is the
1313    /// number of declarations in the function prototype.
1314    unsigned NumExceptionsOrDecls;
1315
1316    /// The location of the ref-qualifier, if any.
1317    ///
1318    /// If this is an invalid location, there is no ref-qualifier.
1319    unsigned RefQualifierLoc;
1320
1321    /// The location of the 'mutable' qualifer in a lambda-declarator, if
1322    /// any.
1323    unsigned MutableLoc;
1324
1325    /// The beginning location of the exception specification, if any.
1326    unsigned ExceptionSpecLocBeg;
1327
1328    /// The end location of the exception specification, if any.
1329    unsigned ExceptionSpecLocEnd;
1330
1331    /// Params - This is a pointer to a new[]'d array of ParamInfo objects that
1332    /// describe the parameters specified by this function declarator.  null if
1333    /// there are no parameters specified.
1334    ParamInfo *Params;
1335
1336    /// DeclSpec for the function with the qualifier related info.
1337    DeclSpec *MethodQualifiers;
1338
1339    /// AtttibuteFactory for the MethodQualifiers.
1340    AttributeFactory *QualAttrFactory;
1341
1342    union {
1343      /// Pointer to a new[]'d array of TypeAndRange objects that
1344      /// contain the types in the function's dynamic exception specification
1345      /// and their locations, if there is one.
1346      TypeAndRange *Exceptions;
1347
1348      /// Pointer to the expression in the noexcept-specifier of this
1349      /// function, if it has one.
1350      Expr *NoexceptExpr;
1351
1352      /// Pointer to the cached tokens for an exception-specification
1353      /// that has not yet been parsed.
1354      CachedTokens *ExceptionSpecTokens;
1355
1356      /// Pointer to a new[]'d array of declarations that need to be available
1357      /// for lookup inside the function body, if one exists. Does not exist in
1358      /// C++.
1359      NamedDecl **DeclsInPrototype;
1360    };
1361
1362    /// If HasTrailingReturnType is true, this is the trailing return
1363    /// type specified.
1364    UnionParsedType TrailingReturnType;
1365
1366    /// Reset the parameter list to having zero parameters.
1367    ///
1368    /// This is used in various places for error recovery.
1369    void freeParams() {
1370      for (unsigned I = 0; I < NumParams; ++I)
1371        Params[I].DefaultArgTokens.reset();
1372      if (DeleteParams) {
1373        delete[] Params;
1374        DeleteParams = false;
1375      }
1376      NumParams = 0;
1377    }
1378
1379    void destroy() {
1380      freeParams();
1381      delete QualAttrFactory;
1382      delete MethodQualifiers;
1383      switch (getExceptionSpecType()) {
1384      default:
1385        break;
1386      case EST_Dynamic:
1387        delete[] Exceptions;
1388        break;
1389      case EST_Unparsed:
1390        delete ExceptionSpecTokens;
1391        break;
1392      case EST_None:
1393        if (NumExceptionsOrDecls != 0)
1394          delete[] DeclsInPrototype;
1395        break;
1396      }
1397    }
1398
1399    DeclSpec &getOrCreateMethodQualifiers() {
1400      if (!MethodQualifiers) {
1401        QualAttrFactory = new AttributeFactory();
1402        MethodQualifiers = new DeclSpec(*QualAttrFactory);
1403      }
1404      return *MethodQualifiers;
1405    }
1406
1407    /// isKNRPrototype - Return true if this is a K&R style identifier list,
1408    /// like "void foo(a,b,c)".  In a function definition, this will be followed
1409    /// by the parameter type definitions.
1410    bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
1411
1412    SourceLocation getLParenLoc() const {
1413      return SourceLocation::getFromRawEncoding(LParenLoc);
1414    }
1415
1416    SourceLocation getEllipsisLoc() const {
1417      return SourceLocation::getFromRawEncoding(EllipsisLoc);
1418    }
1419
1420    SourceLocation getRParenLoc() const {
1421      return SourceLocation::getFromRawEncoding(RParenLoc);
1422    }
1423
1424    SourceLocation getExceptionSpecLocBeg() const {
1425      return SourceLocation::getFromRawEncoding(ExceptionSpecLocBeg);
1426    }
1427
1428    SourceLocation getExceptionSpecLocEnd() const {
1429      return SourceLocation::getFromRawEncoding(ExceptionSpecLocEnd);
1430    }
1431
1432    SourceRange getExceptionSpecRange() const {
1433      return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd());
1434    }
1435
1436    /// Retrieve the location of the ref-qualifier, if any.
1437    SourceLocation getRefQualifierLoc() const {
1438      return SourceLocation::getFromRawEncoding(RefQualifierLoc);
1439    }
1440
1441    /// Retrieve the location of the 'const' qualifier.
1442    SourceLocation getConstQualifierLoc() const {
1443      assert(MethodQualifiers);
1444      return MethodQualifiers->getConstSpecLoc();
1445    }
1446
1447    /// Retrieve the location of the 'volatile' qualifier.
1448    SourceLocation getVolatileQualifierLoc() const {
1449      assert(MethodQualifiers);
1450      return MethodQualifiers->getVolatileSpecLoc();
1451    }
1452
1453    /// Retrieve the location of the 'restrict' qualifier.
1454    SourceLocation getRestrictQualifierLoc() const {
1455      assert(MethodQualifiers);
1456      return MethodQualifiers->getRestrictSpecLoc();
1457    }
1458
1459    /// Retrieve the location of the 'mutable' qualifier, if any.
1460    SourceLocation getMutableLoc() const {
1461      return SourceLocation::getFromRawEncoding(MutableLoc);
1462    }
1463
1464    /// Determine whether this function declaration contains a
1465    /// ref-qualifier.
1466    bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1467
1468    /// Determine whether this lambda-declarator contains a 'mutable'
1469    /// qualifier.
1470    bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1471
1472    /// Determine whether this method has qualifiers.
1473    bool hasMethodTypeQualifiers() const {
1474      return MethodQualifiers && (MethodQualifiers->getTypeQualifiers() ||
1475                                  MethodQualifiers->getAttributes().size());
1476    }
1477
1478    /// Get the type of exception specification this function has.
1479    ExceptionSpecificationType getExceptionSpecType() const {
1480      return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1481    }
1482
1483    /// Get the number of dynamic exception specifications.
1484    unsigned getNumExceptions() const {
1485      assert(ExceptionSpecType != EST_None);
1486      return NumExceptionsOrDecls;
1487    }
1488
1489    /// Get the non-parameter decls defined within this function
1490    /// prototype. Typically these are tag declarations.
1491    ArrayRef<NamedDecl *> getDeclsInPrototype() const {
1492      assert(ExceptionSpecType == EST_None);
1493      return llvm::makeArrayRef(DeclsInPrototype, NumExceptionsOrDecls);
1494    }
1495
1496    /// Determine whether this function declarator had a
1497    /// trailing-return-type.
1498    bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1499
1500    /// Get the trailing-return-type for this function declarator.
1501    ParsedType getTrailingReturnType() const { return TrailingReturnType; }
1502  };
1503
1504  struct BlockPointerTypeInfo {
1505    /// For now, sema will catch these as invalid.
1506    /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1507    unsigned TypeQuals : 5;
1508
1509    void destroy() {
1510    }
1511  };
1512
1513  struct MemberPointerTypeInfo {
1514    /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1515    unsigned TypeQuals : 5;
1516    /// Location of the '*' token.
1517    unsigned StarLoc;
1518    // CXXScopeSpec has a constructor, so it can't be a direct member.
1519    // So we need some pointer-aligned storage and a bit of trickery.
1520    alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)];
1521    CXXScopeSpec &Scope() {
1522      return *reinterpret_cast<CXXScopeSpec *>(ScopeMem);
1523    }
1524    const CXXScopeSpec &Scope() const {
1525      return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem);
1526    }
1527    void destroy() {
1528      Scope().~CXXScopeSpec();
1529    }
1530  };
1531
1532  struct PipeTypeInfo {
1533    /// The access writes.
1534    unsigned AccessWrites : 3;
1535
1536    void destroy() {}
1537  };
1538
1539  union {
1540    PointerTypeInfo       Ptr;
1541    ReferenceTypeInfo     Ref;
1542    ArrayTypeInfo         Arr;
1543    FunctionTypeInfo      Fun;
1544    BlockPointerTypeInfo  Cls;
1545    MemberPointerTypeInfo Mem;
1546    PipeTypeInfo          PipeInfo;
1547  };
1548
1549  void destroy() {
1550    switch (Kind) {
1551    case DeclaratorChunk::Function:      return Fun.destroy();
1552    case DeclaratorChunk::Pointer:       return Ptr.destroy();
1553    case DeclaratorChunk::BlockPointer:  return Cls.destroy();
1554    case DeclaratorChunk::Reference:     return Ref.destroy();
1555    case DeclaratorChunk::Array:         return Arr.destroy();
1556    case DeclaratorChunk::MemberPointer: return Mem.destroy();
1557    case DeclaratorChunk::Paren:         return;
1558    case DeclaratorChunk::Pipe:          return PipeInfo.destroy();
1559    }
1560  }
1561
1562  /// If there are attributes applied to this declaratorchunk, return
1563  /// them.
1564  const ParsedAttributesView &getAttrs() const { return AttrList; }
1565  ParsedAttributesView &getAttrs() { return AttrList; }
1566
1567  /// Return a DeclaratorChunk for a pointer.
1568  static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1569                                    SourceLocation ConstQualLoc,
1570                                    SourceLocation VolatileQualLoc,
1571                                    SourceLocation RestrictQualLoc,
1572                                    SourceLocation AtomicQualLoc,
1573                                    SourceLocation UnalignedQualLoc) {
1574    DeclaratorChunk I;
1575    I.Kind                = Pointer;
1576    I.Loc                 = Loc;
1577    I.Ptr.TypeQuals       = TypeQuals;
1578    I.Ptr.ConstQualLoc    = ConstQualLoc.getRawEncoding();
1579    I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
1580    I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
1581    I.Ptr.AtomicQualLoc   = AtomicQualLoc.getRawEncoding();
1582    I.Ptr.UnalignedQualLoc = UnalignedQualLoc.getRawEncoding();
1583    return I;
1584  }
1585
1586  /// Return a DeclaratorChunk for a reference.
1587  static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1588                                      bool lvalue) {
1589    DeclaratorChunk I;
1590    I.Kind            = Reference;
1591    I.Loc             = Loc;
1592    I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1593    I.Ref.LValueRef   = lvalue;
1594    return I;
1595  }
1596
1597  /// Return a DeclaratorChunk for an array.
1598  static DeclaratorChunk getArray(unsigned TypeQuals,
1599                                  bool isStatic, bool isStar, Expr *NumElts,
1600                                  SourceLocation LBLoc, SourceLocation RBLoc) {
1601    DeclaratorChunk I;
1602    I.Kind          = Array;
1603    I.Loc           = LBLoc;
1604    I.EndLoc        = RBLoc;
1605    I.Arr.TypeQuals = TypeQuals;
1606    I.Arr.hasStatic = isStatic;
1607    I.Arr.isStar    = isStar;
1608    I.Arr.NumElts   = NumElts;
1609    return I;
1610  }
1611
1612  /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1613  /// "TheDeclarator" is the declarator that this will be added to.
1614  static DeclaratorChunk getFunction(bool HasProto,
1615                                     bool IsAmbiguous,
1616                                     SourceLocation LParenLoc,
1617                                     ParamInfo *Params, unsigned NumParams,
1618                                     SourceLocation EllipsisLoc,
1619                                     SourceLocation RParenLoc,
1620                                     bool RefQualifierIsLvalueRef,
1621                                     SourceLocation RefQualifierLoc,
1622                                     SourceLocation MutableLoc,
1623                                     ExceptionSpecificationType ESpecType,
1624                                     SourceRange ESpecRange,
1625                                     ParsedType *Exceptions,
1626                                     SourceRange *ExceptionRanges,
1627                                     unsigned NumExceptions,
1628                                     Expr *NoexceptExpr,
1629                                     CachedTokens *ExceptionSpecTokens,
1630                                     ArrayRef<NamedDecl *> DeclsInPrototype,
1631                                     SourceLocation LocalRangeBegin,
1632                                     SourceLocation LocalRangeEnd,
1633                                     Declarator &TheDeclarator,
1634                                     TypeResult TrailingReturnType =
1635                                                    TypeResult(),
1636                                     DeclSpec *MethodQualifiers = nullptr);
1637
1638  /// Return a DeclaratorChunk for a block.
1639  static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1640                                         SourceLocation Loc) {
1641    DeclaratorChunk I;
1642    I.Kind          = BlockPointer;
1643    I.Loc           = Loc;
1644    I.Cls.TypeQuals = TypeQuals;
1645    return I;
1646  }
1647
1648  /// Return a DeclaratorChunk for a block.
1649  static DeclaratorChunk getPipe(unsigned TypeQuals,
1650                                 SourceLocation Loc) {
1651    DeclaratorChunk I;
1652    I.Kind          = Pipe;
1653    I.Loc           = Loc;
1654    I.Cls.TypeQuals = TypeQuals;
1655    return I;
1656  }
1657
1658  static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1659                                          unsigned TypeQuals,
1660                                          SourceLocation StarLoc,
1661                                          SourceLocation EndLoc) {
1662    DeclaratorChunk I;
1663    I.Kind          = MemberPointer;
1664    I.Loc           = SS.getBeginLoc();
1665    I.EndLoc = EndLoc;
1666    I.Mem.StarLoc = StarLoc.getRawEncoding();
1667    I.Mem.TypeQuals = TypeQuals;
1668    new (I.Mem.ScopeMem) CXXScopeSpec(SS);
1669    return I;
1670  }
1671
1672  /// Return a DeclaratorChunk for a paren.
1673  static DeclaratorChunk getParen(SourceLocation LParenLoc,
1674                                  SourceLocation RParenLoc) {
1675    DeclaratorChunk I;
1676    I.Kind          = Paren;
1677    I.Loc           = LParenLoc;
1678    I.EndLoc        = RParenLoc;
1679    return I;
1680  }
1681
1682  bool isParen() const {
1683    return Kind == Paren;
1684  }
1685};
1686
1687/// A parsed C++17 decomposition declarator of the form
1688///   '[' identifier-list ']'
1689class DecompositionDeclarator {
1690public:
1691  struct Binding {
1692    IdentifierInfo *Name;
1693    SourceLocation NameLoc;
1694  };
1695
1696private:
1697  /// The locations of the '[' and ']' tokens.
1698  SourceLocation LSquareLoc, RSquareLoc;
1699
1700  /// The bindings.
1701  Binding *Bindings;
1702  unsigned NumBindings : 31;
1703  unsigned DeleteBindings : 1;
1704
1705  friend class Declarator;
1706
1707public:
1708  DecompositionDeclarator()
1709      : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {}
1710  DecompositionDeclarator(const DecompositionDeclarator &G) = delete;
1711  DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete;
1712  ~DecompositionDeclarator() {
1713    if (DeleteBindings)
1714      delete[] Bindings;
1715  }
1716
1717  void clear() {
1718    LSquareLoc = RSquareLoc = SourceLocation();
1719    if (DeleteBindings)
1720      delete[] Bindings;
1721    Bindings = nullptr;
1722    NumBindings = 0;
1723    DeleteBindings = false;
1724  }
1725
1726  ArrayRef<Binding> bindings() const {
1727    return llvm::makeArrayRef(Bindings, NumBindings);
1728  }
1729
1730  bool isSet() const { return LSquareLoc.isValid(); }
1731
1732  SourceLocation getLSquareLoc() const { return LSquareLoc; }
1733  SourceLocation getRSquareLoc() const { return RSquareLoc; }
1734  SourceRange getSourceRange() const {
1735    return SourceRange(LSquareLoc, RSquareLoc);
1736  }
1737};
1738
1739/// Described the kind of function definition (if any) provided for
1740/// a function.
1741enum FunctionDefinitionKind {
1742  FDK_Declaration,
1743  FDK_Definition,
1744  FDK_Defaulted,
1745  FDK_Deleted
1746};
1747
1748enum class DeclaratorContext {
1749    FileContext,         // File scope declaration.
1750    PrototypeContext,    // Within a function prototype.
1751    ObjCResultContext,   // An ObjC method result type.
1752    ObjCParameterContext,// An ObjC method parameter type.
1753    KNRTypeListContext,  // K&R type definition list for formals.
1754    TypeNameContext,     // Abstract declarator for types.
1755    FunctionalCastContext, // Type in a C++ functional cast expression.
1756    MemberContext,       // Struct/Union field.
1757    BlockContext,        // Declaration within a block in a function.
1758    ForContext,          // Declaration within first part of a for loop.
1759    InitStmtContext,     // Declaration within optional init stmt of if/switch.
1760    ConditionContext,    // Condition declaration in a C++ if/switch/while/for.
1761    TemplateParamContext,// Within a template parameter list.
1762    CXXNewContext,       // C++ new-expression.
1763    CXXCatchContext,     // C++ catch exception-declaration
1764    ObjCCatchContext,    // Objective-C catch exception-declaration
1765    BlockLiteralContext, // Block literal declarator.
1766    LambdaExprContext,   // Lambda-expression declarator.
1767    LambdaExprParameterContext, // Lambda-expression parameter declarator.
1768    ConversionIdContext, // C++ conversion-type-id.
1769    TrailingReturnContext, // C++11 trailing-type-specifier.
1770    TrailingReturnVarContext, // C++11 trailing-type-specifier for variable.
1771    TemplateArgContext,  // Any template argument (in template argument list).
1772    TemplateTypeArgContext, // Template type argument (in default argument).
1773    AliasDeclContext,    // C++11 alias-declaration.
1774    AliasTemplateContext, // C++11 alias-declaration template.
1775    RequiresExprContext   // C++2a requires-expression.
1776};
1777
1778
1779/// Information about one declarator, including the parsed type
1780/// information and the identifier.
1781///
1782/// When the declarator is fully formed, this is turned into the appropriate
1783/// Decl object.
1784///
1785/// Declarators come in two types: normal declarators and abstract declarators.
1786/// Abstract declarators are used when parsing types, and don't have an
1787/// identifier.  Normal declarators do have ID's.
1788///
1789/// Instances of this class should be a transient object that lives on the
1790/// stack, not objects that are allocated in large quantities on the heap.
1791class Declarator {
1792
1793private:
1794  const DeclSpec &DS;
1795  CXXScopeSpec SS;
1796  UnqualifiedId Name;
1797  SourceRange Range;
1798
1799  /// Where we are parsing this declarator.
1800  DeclaratorContext Context;
1801
1802  /// The C++17 structured binding, if any. This is an alternative to a Name.
1803  DecompositionDeclarator BindingGroup;
1804
1805  /// DeclTypeInfo - This holds each type that the declarator includes as it is
1806  /// parsed.  This is pushed from the identifier out, which means that element
1807  /// #0 will be the most closely bound to the identifier, and
1808  /// DeclTypeInfo.back() will be the least closely bound.
1809  SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1810
1811  /// InvalidType - Set by Sema::GetTypeForDeclarator().
1812  unsigned InvalidType : 1;
1813
1814  /// GroupingParens - Set by Parser::ParseParenDeclarator().
1815  unsigned GroupingParens : 1;
1816
1817  /// FunctionDefinition - Is this Declarator for a function or member
1818  /// definition and, if so, what kind?
1819  ///
1820  /// Actually a FunctionDefinitionKind.
1821  unsigned FunctionDefinition : 2;
1822
1823  /// Is this Declarator a redeclaration?
1824  unsigned Redeclaration : 1;
1825
1826  /// true if the declaration is preceded by \c __extension__.
1827  unsigned Extension : 1;
1828
1829  /// Indicates whether this is an Objective-C instance variable.
1830  unsigned ObjCIvar : 1;
1831
1832  /// Indicates whether this is an Objective-C 'weak' property.
1833  unsigned ObjCWeakProperty : 1;
1834
1835  /// Indicates whether the InlineParams / InlineBindings storage has been used.
1836  unsigned InlineStorageUsed : 1;
1837
1838  /// Attrs - Attributes.
1839  ParsedAttributes Attrs;
1840
1841  /// The asm label, if specified.
1842  Expr *AsmLabel;
1843
1844  /// \brief The constraint-expression specified by the trailing
1845  /// requires-clause, or null if no such clause was specified.
1846  Expr *TrailingRequiresClause;
1847
1848  /// If this declarator declares a template, its template parameter lists.
1849  ArrayRef<TemplateParameterList *> TemplateParameterLists;
1850
1851  /// If the declarator declares an abbreviated function template, the innermost
1852  /// template parameter list containing the invented and explicit template
1853  /// parameters (if any).
1854  TemplateParameterList *InventedTemplateParameterList;
1855
1856#ifndef _MSC_VER
1857  union {
1858#endif
1859    /// InlineParams - This is a local array used for the first function decl
1860    /// chunk to avoid going to the heap for the common case when we have one
1861    /// function chunk in the declarator.
1862    DeclaratorChunk::ParamInfo InlineParams[16];
1863    DecompositionDeclarator::Binding InlineBindings[16];
1864#ifndef _MSC_VER
1865  };
1866#endif
1867
1868  /// If this is the second or subsequent declarator in this declaration,
1869  /// the location of the comma before this declarator.
1870  SourceLocation CommaLoc;
1871
1872  /// If provided, the source location of the ellipsis used to describe
1873  /// this declarator as a parameter pack.
1874  SourceLocation EllipsisLoc;
1875
1876  friend struct DeclaratorChunk;
1877
1878public:
1879  Declarator(const DeclSpec &ds, DeclaratorContext C)
1880      : DS(ds), Range(ds.getSourceRange()), Context(C),
1881        InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1882        GroupingParens(false), FunctionDefinition(FDK_Declaration),
1883        Redeclaration(false), Extension(false), ObjCIvar(false),
1884        ObjCWeakProperty(false), InlineStorageUsed(false),
1885        Attrs(ds.getAttributePool().getFactory()), AsmLabel(nullptr),
1886        TrailingRequiresClause(nullptr),
1887        InventedTemplateParameterList(nullptr) {}
1888
1889  ~Declarator() {
1890    clear();
1891  }
1892  /// getDeclSpec - Return the declaration-specifier that this declarator was
1893  /// declared with.
1894  const DeclSpec &getDeclSpec() const { return DS; }
1895
1896  /// getMutableDeclSpec - Return a non-const version of the DeclSpec.  This
1897  /// should be used with extreme care: declspecs can often be shared between
1898  /// multiple declarators, so mutating the DeclSpec affects all of the
1899  /// Declarators.  This should only be done when the declspec is known to not
1900  /// be shared or when in error recovery etc.
1901  DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1902
1903  AttributePool &getAttributePool() const {
1904    return Attrs.getPool();
1905  }
1906
1907  /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1908  /// nested-name-specifier) that is part of the declarator-id.
1909  const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1910  CXXScopeSpec &getCXXScopeSpec() { return SS; }
1911
1912  /// Retrieve the name specified by this declarator.
1913  UnqualifiedId &getName() { return Name; }
1914
1915  const DecompositionDeclarator &getDecompositionDeclarator() const {
1916    return BindingGroup;
1917  }
1918
1919  DeclaratorContext getContext() const { return Context; }
1920
1921  bool isPrototypeContext() const {
1922    return (Context == DeclaratorContext::PrototypeContext ||
1923            Context == DeclaratorContext::ObjCParameterContext ||
1924            Context == DeclaratorContext::ObjCResultContext ||
1925            Context == DeclaratorContext::LambdaExprParameterContext);
1926  }
1927
1928  /// Get the source range that spans this declarator.
1929  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1930  SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
1931  SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
1932
1933  void SetSourceRange(SourceRange R) { Range = R; }
1934  /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1935  /// invalid.
1936  void SetRangeBegin(SourceLocation Loc) {
1937    if (!Loc.isInvalid())
1938      Range.setBegin(Loc);
1939  }
1940  /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1941  void SetRangeEnd(SourceLocation Loc) {
1942    if (!Loc.isInvalid())
1943      Range.setEnd(Loc);
1944  }
1945  /// ExtendWithDeclSpec - Extend the declarator source range to include the
1946  /// given declspec, unless its location is invalid. Adopts the range start if
1947  /// the current range start is invalid.
1948  void ExtendWithDeclSpec(const DeclSpec &DS) {
1949    SourceRange SR = DS.getSourceRange();
1950    if (Range.getBegin().isInvalid())
1951      Range.setBegin(SR.getBegin());
1952    if (!SR.getEnd().isInvalid())
1953      Range.setEnd(SR.getEnd());
1954  }
1955
1956  /// Reset the contents of this Declarator.
1957  void clear() {
1958    SS.clear();
1959    Name.clear();
1960    Range = DS.getSourceRange();
1961    BindingGroup.clear();
1962
1963    for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1964      DeclTypeInfo[i].destroy();
1965    DeclTypeInfo.clear();
1966    Attrs.clear();
1967    AsmLabel = nullptr;
1968    InlineStorageUsed = false;
1969    ObjCIvar = false;
1970    ObjCWeakProperty = false;
1971    CommaLoc = SourceLocation();
1972    EllipsisLoc = SourceLocation();
1973  }
1974
1975  /// mayOmitIdentifier - Return true if the identifier is either optional or
1976  /// not allowed.  This is true for typenames, prototypes, and template
1977  /// parameter lists.
1978  bool mayOmitIdentifier() const {
1979    switch (Context) {
1980    case DeclaratorContext::FileContext:
1981    case DeclaratorContext::KNRTypeListContext:
1982    case DeclaratorContext::MemberContext:
1983    case DeclaratorContext::BlockContext:
1984    case DeclaratorContext::ForContext:
1985    case DeclaratorContext::InitStmtContext:
1986    case DeclaratorContext::ConditionContext:
1987      return false;
1988
1989    case DeclaratorContext::TypeNameContext:
1990    case DeclaratorContext::FunctionalCastContext:
1991    case DeclaratorContext::AliasDeclContext:
1992    case DeclaratorContext::AliasTemplateContext:
1993    case DeclaratorContext::PrototypeContext:
1994    case DeclaratorContext::LambdaExprParameterContext:
1995    case DeclaratorContext::ObjCParameterContext:
1996    case DeclaratorContext::ObjCResultContext:
1997    case DeclaratorContext::TemplateParamContext:
1998    case DeclaratorContext::CXXNewContext:
1999    case DeclaratorContext::CXXCatchContext:
2000    case DeclaratorContext::ObjCCatchContext:
2001    case DeclaratorContext::BlockLiteralContext:
2002    case DeclaratorContext::LambdaExprContext:
2003    case DeclaratorContext::ConversionIdContext:
2004    case DeclaratorContext::TemplateArgContext:
2005    case DeclaratorContext::TemplateTypeArgContext:
2006    case DeclaratorContext::TrailingReturnContext:
2007    case DeclaratorContext::TrailingReturnVarContext:
2008    case DeclaratorContext::RequiresExprContext:
2009      return true;
2010    }
2011    llvm_unreachable("unknown context kind!");
2012  }
2013
2014  /// mayHaveIdentifier - Return true if the identifier is either optional or
2015  /// required.  This is true for normal declarators and prototypes, but not
2016  /// typenames.
2017  bool mayHaveIdentifier() const {
2018    switch (Context) {
2019    case DeclaratorContext::FileContext:
2020    case DeclaratorContext::KNRTypeListContext:
2021    case DeclaratorContext::MemberContext:
2022    case DeclaratorContext::BlockContext:
2023    case DeclaratorContext::ForContext:
2024    case DeclaratorContext::InitStmtContext:
2025    case DeclaratorContext::ConditionContext:
2026    case DeclaratorContext::PrototypeContext:
2027    case DeclaratorContext::LambdaExprParameterContext:
2028    case DeclaratorContext::TemplateParamContext:
2029    case DeclaratorContext::CXXCatchContext:
2030    case DeclaratorContext::ObjCCatchContext:
2031    case DeclaratorContext::RequiresExprContext:
2032      return true;
2033
2034    case DeclaratorContext::TypeNameContext:
2035    case DeclaratorContext::FunctionalCastContext:
2036    case DeclaratorContext::CXXNewContext:
2037    case DeclaratorContext::AliasDeclContext:
2038    case DeclaratorContext::AliasTemplateContext:
2039    case DeclaratorContext::ObjCParameterContext:
2040    case DeclaratorContext::ObjCResultContext:
2041    case DeclaratorContext::BlockLiteralContext:
2042    case DeclaratorContext::LambdaExprContext:
2043    case DeclaratorContext::ConversionIdContext:
2044    case DeclaratorContext::TemplateArgContext:
2045    case DeclaratorContext::TemplateTypeArgContext:
2046    case DeclaratorContext::TrailingReturnContext:
2047    case DeclaratorContext::TrailingReturnVarContext:
2048      return false;
2049    }
2050    llvm_unreachable("unknown context kind!");
2051  }
2052
2053  /// Return true if the context permits a C++17 decomposition declarator.
2054  bool mayHaveDecompositionDeclarator() const {
2055    switch (Context) {
2056    case DeclaratorContext::FileContext:
2057      // FIXME: It's not clear that the proposal meant to allow file-scope
2058      // structured bindings, but it does.
2059    case DeclaratorContext::BlockContext:
2060    case DeclaratorContext::ForContext:
2061    case DeclaratorContext::InitStmtContext:
2062    case DeclaratorContext::ConditionContext:
2063      return true;
2064
2065    case DeclaratorContext::MemberContext:
2066    case DeclaratorContext::PrototypeContext:
2067    case DeclaratorContext::TemplateParamContext:
2068    case DeclaratorContext::RequiresExprContext:
2069      // Maybe one day...
2070      return false;
2071
2072    // These contexts don't allow any kind of non-abstract declarator.
2073    case DeclaratorContext::KNRTypeListContext:
2074    case DeclaratorContext::TypeNameContext:
2075    case DeclaratorContext::FunctionalCastContext:
2076    case DeclaratorContext::AliasDeclContext:
2077    case DeclaratorContext::AliasTemplateContext:
2078    case DeclaratorContext::LambdaExprParameterContext:
2079    case DeclaratorContext::ObjCParameterContext:
2080    case DeclaratorContext::ObjCResultContext:
2081    case DeclaratorContext::CXXNewContext:
2082    case DeclaratorContext::CXXCatchContext:
2083    case DeclaratorContext::ObjCCatchContext:
2084    case DeclaratorContext::BlockLiteralContext:
2085    case DeclaratorContext::LambdaExprContext:
2086    case DeclaratorContext::ConversionIdContext:
2087    case DeclaratorContext::TemplateArgContext:
2088    case DeclaratorContext::TemplateTypeArgContext:
2089    case DeclaratorContext::TrailingReturnContext:
2090    case DeclaratorContext::TrailingReturnVarContext:
2091      return false;
2092    }
2093    llvm_unreachable("unknown context kind!");
2094  }
2095
2096  /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
2097  /// followed by a C++ direct initializer, e.g. "int x(1);".
2098  bool mayBeFollowedByCXXDirectInit() const {
2099    if (hasGroupingParens()) return false;
2100
2101    if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2102      return false;
2103
2104    if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
2105        Context != DeclaratorContext::FileContext)
2106      return false;
2107
2108    // Special names can't have direct initializers.
2109    if (Name.getKind() != UnqualifiedIdKind::IK_Identifier)
2110      return false;
2111
2112    switch (Context) {
2113    case DeclaratorContext::FileContext:
2114    case DeclaratorContext::BlockContext:
2115    case DeclaratorContext::ForContext:
2116    case DeclaratorContext::InitStmtContext:
2117    case DeclaratorContext::TrailingReturnVarContext:
2118      return true;
2119
2120    case DeclaratorContext::ConditionContext:
2121      // This may not be followed by a direct initializer, but it can't be a
2122      // function declaration either, and we'd prefer to perform a tentative
2123      // parse in order to produce the right diagnostic.
2124      return true;
2125
2126    case DeclaratorContext::KNRTypeListContext:
2127    case DeclaratorContext::MemberContext:
2128    case DeclaratorContext::PrototypeContext:
2129    case DeclaratorContext::LambdaExprParameterContext:
2130    case DeclaratorContext::ObjCParameterContext:
2131    case DeclaratorContext::ObjCResultContext:
2132    case DeclaratorContext::TemplateParamContext:
2133    case DeclaratorContext::CXXCatchContext:
2134    case DeclaratorContext::ObjCCatchContext:
2135    case DeclaratorContext::TypeNameContext:
2136    case DeclaratorContext::FunctionalCastContext: // FIXME
2137    case DeclaratorContext::CXXNewContext:
2138    case DeclaratorContext::AliasDeclContext:
2139    case DeclaratorContext::AliasTemplateContext:
2140    case DeclaratorContext::BlockLiteralContext:
2141    case DeclaratorContext::LambdaExprContext:
2142    case DeclaratorContext::ConversionIdContext:
2143    case DeclaratorContext::TemplateArgContext:
2144    case DeclaratorContext::TemplateTypeArgContext:
2145    case DeclaratorContext::TrailingReturnContext:
2146    case DeclaratorContext::RequiresExprContext:
2147      return false;
2148    }
2149    llvm_unreachable("unknown context kind!");
2150  }
2151
2152  /// isPastIdentifier - Return true if we have parsed beyond the point where
2153  /// the name would appear. (This may happen even if we haven't actually parsed
2154  /// a name, perhaps because this context doesn't require one.)
2155  bool isPastIdentifier() const { return Name.isValid(); }
2156
2157  /// hasName - Whether this declarator has a name, which might be an
2158  /// identifier (accessible via getIdentifier()) or some kind of
2159  /// special C++ name (constructor, destructor, etc.), or a structured
2160  /// binding (which is not exactly a name, but occupies the same position).
2161  bool hasName() const {
2162    return Name.getKind() != UnqualifiedIdKind::IK_Identifier ||
2163           Name.Identifier || isDecompositionDeclarator();
2164  }
2165
2166  /// Return whether this declarator is a decomposition declarator.
2167  bool isDecompositionDeclarator() const {
2168    return BindingGroup.isSet();
2169  }
2170
2171  IdentifierInfo *getIdentifier() const {
2172    if (Name.getKind() == UnqualifiedIdKind::IK_Identifier)
2173      return Name.Identifier;
2174
2175    return nullptr;
2176  }
2177  SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
2178
2179  /// Set the name of this declarator to be the given identifier.
2180  void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
2181    Name.setIdentifier(Id, IdLoc);
2182  }
2183
2184  /// Set the decomposition bindings for this declarator.
2185  void
2186  setDecompositionBindings(SourceLocation LSquareLoc,
2187                           ArrayRef<DecompositionDeclarator::Binding> Bindings,
2188                           SourceLocation RSquareLoc);
2189
2190  /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2191  /// EndLoc, which should be the last token of the chunk.
2192  /// This function takes attrs by R-Value reference because it takes ownership
2193  /// of those attributes from the parameter.
2194  void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs,
2195                   SourceLocation EndLoc) {
2196    DeclTypeInfo.push_back(TI);
2197    DeclTypeInfo.back().getAttrs().addAll(attrs.begin(), attrs.end());
2198    getAttributePool().takeAllFrom(attrs.getPool());
2199
2200    if (!EndLoc.isInvalid())
2201      SetRangeEnd(EndLoc);
2202  }
2203
2204  /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2205  /// EndLoc, which should be the last token of the chunk.
2206  void AddTypeInfo(const DeclaratorChunk &TI, SourceLocation EndLoc) {
2207    DeclTypeInfo.push_back(TI);
2208
2209    if (!EndLoc.isInvalid())
2210      SetRangeEnd(EndLoc);
2211  }
2212
2213  /// Add a new innermost chunk to this declarator.
2214  void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
2215    DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
2216  }
2217
2218  /// Return the number of types applied to this declarator.
2219  unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
2220
2221  /// Return the specified TypeInfo from this declarator.  TypeInfo #0 is
2222  /// closest to the identifier.
2223  const DeclaratorChunk &getTypeObject(unsigned i) const {
2224    assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2225    return DeclTypeInfo[i];
2226  }
2227  DeclaratorChunk &getTypeObject(unsigned i) {
2228    assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2229    return DeclTypeInfo[i];
2230  }
2231
2232  typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
2233  typedef llvm::iterator_range<type_object_iterator> type_object_range;
2234
2235  /// Returns the range of type objects, from the identifier outwards.
2236  type_object_range type_objects() const {
2237    return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
2238  }
2239
2240  void DropFirstTypeObject() {
2241    assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
2242    DeclTypeInfo.front().destroy();
2243    DeclTypeInfo.erase(DeclTypeInfo.begin());
2244  }
2245
2246  /// Return the innermost (closest to the declarator) chunk of this
2247  /// declarator that is not a parens chunk, or null if there are no
2248  /// non-parens chunks.
2249  const DeclaratorChunk *getInnermostNonParenChunk() const {
2250    for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2251      if (!DeclTypeInfo[i].isParen())
2252        return &DeclTypeInfo[i];
2253    }
2254    return nullptr;
2255  }
2256
2257  /// Return the outermost (furthest from the declarator) chunk of
2258  /// this declarator that is not a parens chunk, or null if there are
2259  /// no non-parens chunks.
2260  const DeclaratorChunk *getOutermostNonParenChunk() const {
2261    for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
2262      if (!DeclTypeInfo[i-1].isParen())
2263        return &DeclTypeInfo[i-1];
2264    }
2265    return nullptr;
2266  }
2267
2268  /// isArrayOfUnknownBound - This method returns true if the declarator
2269  /// is a declarator for an array of unknown bound (looking through
2270  /// parentheses).
2271  bool isArrayOfUnknownBound() const {
2272    const DeclaratorChunk *chunk = getInnermostNonParenChunk();
2273    return (chunk && chunk->Kind == DeclaratorChunk::Array &&
2274            !chunk->Arr.NumElts);
2275  }
2276
2277  /// isFunctionDeclarator - This method returns true if the declarator
2278  /// is a function declarator (looking through parentheses).
2279  /// If true is returned, then the reference type parameter idx is
2280  /// assigned with the index of the declaration chunk.
2281  bool isFunctionDeclarator(unsigned& idx) const {
2282    for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2283      switch (DeclTypeInfo[i].Kind) {
2284      case DeclaratorChunk::Function:
2285        idx = i;
2286        return true;
2287      case DeclaratorChunk::Paren:
2288        continue;
2289      case DeclaratorChunk::Pointer:
2290      case DeclaratorChunk::Reference:
2291      case DeclaratorChunk::Array:
2292      case DeclaratorChunk::BlockPointer:
2293      case DeclaratorChunk::MemberPointer:
2294      case DeclaratorChunk::Pipe:
2295        return false;
2296      }
2297      llvm_unreachable("Invalid type chunk");
2298    }
2299    return false;
2300  }
2301
2302  /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
2303  /// this method returns true if the identifier is a function declarator
2304  /// (looking through parentheses).
2305  bool isFunctionDeclarator() const {
2306    unsigned index;
2307    return isFunctionDeclarator(index);
2308  }
2309
2310  /// getFunctionTypeInfo - Retrieves the function type info object
2311  /// (looking through parentheses).
2312  DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
2313    assert(isFunctionDeclarator() && "Not a function declarator!");
2314    unsigned index = 0;
2315    isFunctionDeclarator(index);
2316    return DeclTypeInfo[index].Fun;
2317  }
2318
2319  /// getFunctionTypeInfo - Retrieves the function type info object
2320  /// (looking through parentheses).
2321  const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
2322    return const_cast<Declarator*>(this)->getFunctionTypeInfo();
2323  }
2324
2325  /// Determine whether the declaration that will be produced from
2326  /// this declaration will be a function.
2327  ///
2328  /// A declaration can declare a function even if the declarator itself
2329  /// isn't a function declarator, if the type specifier refers to a function
2330  /// type. This routine checks for both cases.
2331  bool isDeclarationOfFunction() const;
2332
2333  /// Return true if this declaration appears in a context where a
2334  /// function declarator would be a function declaration.
2335  bool isFunctionDeclarationContext() const {
2336    if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2337      return false;
2338
2339    switch (Context) {
2340    case DeclaratorContext::FileContext:
2341    case DeclaratorContext::MemberContext:
2342    case DeclaratorContext::BlockContext:
2343    case DeclaratorContext::ForContext:
2344    case DeclaratorContext::InitStmtContext:
2345      return true;
2346
2347    case DeclaratorContext::ConditionContext:
2348    case DeclaratorContext::KNRTypeListContext:
2349    case DeclaratorContext::TypeNameContext:
2350    case DeclaratorContext::FunctionalCastContext:
2351    case DeclaratorContext::AliasDeclContext:
2352    case DeclaratorContext::AliasTemplateContext:
2353    case DeclaratorContext::PrototypeContext:
2354    case DeclaratorContext::LambdaExprParameterContext:
2355    case DeclaratorContext::ObjCParameterContext:
2356    case DeclaratorContext::ObjCResultContext:
2357    case DeclaratorContext::TemplateParamContext:
2358    case DeclaratorContext::CXXNewContext:
2359    case DeclaratorContext::CXXCatchContext:
2360    case DeclaratorContext::ObjCCatchContext:
2361    case DeclaratorContext::BlockLiteralContext:
2362    case DeclaratorContext::LambdaExprContext:
2363    case DeclaratorContext::ConversionIdContext:
2364    case DeclaratorContext::TemplateArgContext:
2365    case DeclaratorContext::TemplateTypeArgContext:
2366    case DeclaratorContext::TrailingReturnContext:
2367    case DeclaratorContext::TrailingReturnVarContext:
2368    case DeclaratorContext::RequiresExprContext:
2369      return false;
2370    }
2371    llvm_unreachable("unknown context kind!");
2372  }
2373
2374  /// Determine whether this declaration appears in a context where an
2375  /// expression could appear.
2376  bool isExpressionContext() const {
2377    switch (Context) {
2378    case DeclaratorContext::FileContext:
2379    case DeclaratorContext::KNRTypeListContext:
2380    case DeclaratorContext::MemberContext:
2381
2382    // FIXME: sizeof(...) permits an expression.
2383    case DeclaratorContext::TypeNameContext:
2384
2385    case DeclaratorContext::FunctionalCastContext:
2386    case DeclaratorContext::AliasDeclContext:
2387    case DeclaratorContext::AliasTemplateContext:
2388    case DeclaratorContext::PrototypeContext:
2389    case DeclaratorContext::LambdaExprParameterContext:
2390    case DeclaratorContext::ObjCParameterContext:
2391    case DeclaratorContext::ObjCResultContext:
2392    case DeclaratorContext::TemplateParamContext:
2393    case DeclaratorContext::CXXNewContext:
2394    case DeclaratorContext::CXXCatchContext:
2395    case DeclaratorContext::ObjCCatchContext:
2396    case DeclaratorContext::BlockLiteralContext:
2397    case DeclaratorContext::LambdaExprContext:
2398    case DeclaratorContext::ConversionIdContext:
2399    case DeclaratorContext::TrailingReturnContext:
2400    case DeclaratorContext::TrailingReturnVarContext:
2401    case DeclaratorContext::TemplateTypeArgContext:
2402    case DeclaratorContext::RequiresExprContext:
2403      return false;
2404
2405    case DeclaratorContext::BlockContext:
2406    case DeclaratorContext::ForContext:
2407    case DeclaratorContext::InitStmtContext:
2408    case DeclaratorContext::ConditionContext:
2409    case DeclaratorContext::TemplateArgContext:
2410      return true;
2411    }
2412
2413    llvm_unreachable("unknown context kind!");
2414  }
2415
2416  /// Return true if a function declarator at this position would be a
2417  /// function declaration.
2418  bool isFunctionDeclaratorAFunctionDeclaration() const {
2419    if (!isFunctionDeclarationContext())
2420      return false;
2421
2422    for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2423      if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
2424        return false;
2425
2426    return true;
2427  }
2428
2429  /// Determine whether a trailing return type was written (at any
2430  /// level) within this declarator.
2431  bool hasTrailingReturnType() const {
2432    for (const auto &Chunk : type_objects())
2433      if (Chunk.Kind == DeclaratorChunk::Function &&
2434          Chunk.Fun.hasTrailingReturnType())
2435        return true;
2436    return false;
2437  }
2438
2439  /// \brief Sets a trailing requires clause for this declarator.
2440  void setTrailingRequiresClause(Expr *TRC) {
2441    TrailingRequiresClause = TRC;
2442  }
2443
2444  /// \brief Sets a trailing requires clause for this declarator.
2445  Expr *getTrailingRequiresClause() {
2446    return TrailingRequiresClause;
2447  }
2448
2449  /// \brief Determine whether a trailing requires clause was written in this
2450  /// declarator.
2451  bool hasTrailingRequiresClause() const {
2452    return TrailingRequiresClause != nullptr;
2453  }
2454
2455  /// Sets the template parameter lists that preceded the declarator.
2456  void setTemplateParameterLists(ArrayRef<TemplateParameterList *> TPLs) {
2457    TemplateParameterLists = TPLs;
2458  }
2459
2460  /// The template parameter lists that preceded the declarator.
2461  ArrayRef<TemplateParameterList *> getTemplateParameterLists() const {
2462    return TemplateParameterLists;
2463  }
2464
2465  /// Sets the template parameter list generated from the explicit template
2466  /// parameters along with any invented template parameters from
2467  /// placeholder-typed parameters.
2468  void setInventedTemplateParameterList(TemplateParameterList *Invented) {
2469    InventedTemplateParameterList = Invented;
2470  }
2471
2472  /// The template parameter list generated from the explicit template
2473  /// parameters along with any invented template parameters from
2474  /// placeholder-typed parameters, if there were any such parameters.
2475  TemplateParameterList * getInventedTemplateParameterList() const {
2476    return InventedTemplateParameterList;
2477  }
2478
2479  /// takeAttributes - Takes attributes from the given parsed-attributes
2480  /// set and add them to this declarator.
2481  ///
2482  /// These examples both add 3 attributes to "var":
2483  ///  short int var __attribute__((aligned(16),common,deprecated));
2484  ///  short int x, __attribute__((aligned(16)) var
2485  ///                                 __attribute__((common,deprecated));
2486  ///
2487  /// Also extends the range of the declarator.
2488  void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
2489    Attrs.takeAllFrom(attrs);
2490
2491    if (!lastLoc.isInvalid())
2492      SetRangeEnd(lastLoc);
2493  }
2494
2495  const ParsedAttributes &getAttributes() const { return Attrs; }
2496  ParsedAttributes &getAttributes() { return Attrs; }
2497
2498  /// hasAttributes - do we contain any attributes?
2499  bool hasAttributes() const {
2500    if (!getAttributes().empty() || getDeclSpec().hasAttributes())
2501      return true;
2502    for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2503      if (!getTypeObject(i).getAttrs().empty())
2504        return true;
2505    return false;
2506  }
2507
2508  /// Return a source range list of C++11 attributes associated
2509  /// with the declarator.
2510  void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) {
2511    for (const ParsedAttr &AL : Attrs)
2512      if (AL.isCXX11Attribute())
2513        Ranges.push_back(AL.getRange());
2514  }
2515
2516  void setAsmLabel(Expr *E) { AsmLabel = E; }
2517  Expr *getAsmLabel() const { return AsmLabel; }
2518
2519  void setExtension(bool Val = true) { Extension = Val; }
2520  bool getExtension() const { return Extension; }
2521
2522  void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
2523  bool isObjCIvar() const { return ObjCIvar; }
2524
2525  void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
2526  bool isObjCWeakProperty() const { return ObjCWeakProperty; }
2527
2528  void setInvalidType(bool Val = true) { InvalidType = Val; }
2529  bool isInvalidType() const {
2530    return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
2531  }
2532
2533  void setGroupingParens(bool flag) { GroupingParens = flag; }
2534  bool hasGroupingParens() const { return GroupingParens; }
2535
2536  bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
2537  SourceLocation getCommaLoc() const { return CommaLoc; }
2538  void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2539
2540  bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2541  SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2542  void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2543
2544  void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2545    FunctionDefinition = Val;
2546  }
2547
2548  bool isFunctionDefinition() const {
2549    return getFunctionDefinitionKind() != FDK_Declaration;
2550  }
2551
2552  FunctionDefinitionKind getFunctionDefinitionKind() const {
2553    return (FunctionDefinitionKind)FunctionDefinition;
2554  }
2555
2556  /// Returns true if this declares a real member and not a friend.
2557  bool isFirstDeclarationOfMember() {
2558    return getContext() == DeclaratorContext::MemberContext &&
2559           !getDeclSpec().isFriendSpecified();
2560  }
2561
2562  /// Returns true if this declares a static member.  This cannot be called on a
2563  /// declarator outside of a MemberContext because we won't know until
2564  /// redeclaration time if the decl is static.
2565  bool isStaticMember();
2566
2567  /// Returns true if this declares a constructor or a destructor.
2568  bool isCtorOrDtor();
2569
2570  void setRedeclaration(bool Val) { Redeclaration = Val; }
2571  bool isRedeclaration() const { return Redeclaration; }
2572};
2573
2574/// This little struct is used to capture information about
2575/// structure field declarators, which is basically just a bitfield size.
2576struct FieldDeclarator {
2577  Declarator D;
2578  Expr *BitfieldSize;
2579  explicit FieldDeclarator(const DeclSpec &DS)
2580      : D(DS, DeclaratorContext::MemberContext),
2581        BitfieldSize(nullptr) {}
2582};
2583
2584/// Represents a C++11 virt-specifier-seq.
2585class VirtSpecifiers {
2586public:
2587  enum Specifier {
2588    VS_None = 0,
2589    VS_Override = 1,
2590    VS_Final = 2,
2591    VS_Sealed = 4,
2592    // Represents the __final keyword, which is legal for gcc in pre-C++11 mode.
2593    VS_GNU_Final = 8
2594  };
2595
2596  VirtSpecifiers() : Specifiers(0), LastSpecifier(VS_None) { }
2597
2598  bool SetSpecifier(Specifier VS, SourceLocation Loc,
2599                    const char *&PrevSpec);
2600
2601  bool isUnset() const { return Specifiers == 0; }
2602
2603  bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2604  SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2605
2606  bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); }
2607  bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
2608  SourceLocation getFinalLoc() const { return VS_finalLoc; }
2609
2610  void clear() { Specifiers = 0; }
2611
2612  static const char *getSpecifierName(Specifier VS);
2613
2614  SourceLocation getFirstLocation() const { return FirstLocation; }
2615  SourceLocation getLastLocation() const { return LastLocation; }
2616  Specifier getLastSpecifier() const { return LastSpecifier; }
2617
2618private:
2619  unsigned Specifiers;
2620  Specifier LastSpecifier;
2621
2622  SourceLocation VS_overrideLoc, VS_finalLoc;
2623  SourceLocation FirstLocation;
2624  SourceLocation LastLocation;
2625};
2626
2627enum class LambdaCaptureInitKind {
2628  NoInit,     //!< [a]
2629  CopyInit,   //!< [a = b], [a = {b}]
2630  DirectInit, //!< [a(b)]
2631  ListInit    //!< [a{b}]
2632};
2633
2634/// Represents a complete lambda introducer.
2635struct LambdaIntroducer {
2636  /// An individual capture in a lambda introducer.
2637  struct LambdaCapture {
2638    LambdaCaptureKind Kind;
2639    SourceLocation Loc;
2640    IdentifierInfo *Id;
2641    SourceLocation EllipsisLoc;
2642    LambdaCaptureInitKind InitKind;
2643    ExprResult Init;
2644    ParsedType InitCaptureType;
2645    SourceRange ExplicitRange;
2646
2647    LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2648                  IdentifierInfo *Id, SourceLocation EllipsisLoc,
2649                  LambdaCaptureInitKind InitKind, ExprResult Init,
2650                  ParsedType InitCaptureType,
2651                  SourceRange ExplicitRange)
2652        : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
2653          InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType),
2654          ExplicitRange(ExplicitRange) {}
2655  };
2656
2657  SourceRange Range;
2658  SourceLocation DefaultLoc;
2659  LambdaCaptureDefault Default;
2660  SmallVector<LambdaCapture, 4> Captures;
2661
2662  LambdaIntroducer()
2663    : Default(LCD_None) {}
2664
2665  /// Append a capture in a lambda introducer.
2666  void addCapture(LambdaCaptureKind Kind,
2667                  SourceLocation Loc,
2668                  IdentifierInfo* Id,
2669                  SourceLocation EllipsisLoc,
2670                  LambdaCaptureInitKind InitKind,
2671                  ExprResult Init,
2672                  ParsedType InitCaptureType,
2673                  SourceRange ExplicitRange) {
2674    Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
2675                                     InitCaptureType, ExplicitRange));
2676  }
2677};
2678
2679struct InventedTemplateParameterInfo {
2680  /// The number of parameters in the template parameter list that were
2681  /// explicitly specified by the user, as opposed to being invented by use
2682  /// of an auto parameter.
2683  unsigned NumExplicitTemplateParams = 0;
2684
2685  /// If this is a generic lambda or abbreviated function template, use this
2686  /// as the depth of each 'auto' parameter, during initial AST construction.
2687  unsigned AutoTemplateParameterDepth = 0;
2688
2689  /// Store the list of the template parameters for a generic lambda or an
2690  /// abbreviated function template.
2691  /// If this is a generic lambda or abbreviated function template, this holds
2692  /// the explicit template parameters followed by the auto parameters
2693  /// converted into TemplateTypeParmDecls.
2694  /// It can be used to construct the generic lambda or abbreviated template's
2695  /// template parameter list during initial AST construction.
2696  SmallVector<NamedDecl*, 4> TemplateParams;
2697};
2698
2699} // end namespace clang
2700
2701#endif // LLVM_CLANG_SEMA_DECLSPEC_H
2702