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