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