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