]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - include/clang/Sema/DeclSpec.h
Vendor import of clang trunk r338150:
[FreeBSD/FreeBSD.git] / 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 getLocStart() const LLVM_READONLY { return Range.getBegin(); }
509   SourceLocation getLocEnd() 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   /// Return true if any type-specifier has been found.
597   bool hasTypeSpecifier() const {
598     return getTypeSpecType() != DeclSpec::TST_unspecified ||
599            getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
600            getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
601            getTypeSpecSign() != DeclSpec::TSS_unspecified;
602   }
603
604   /// Return a bitmask of which flavors of specifiers this
605   /// DeclSpec includes.
606   unsigned getParsedSpecifiers() const;
607
608   /// isEmpty - Return true if this declaration specifier is completely empty:
609   /// no tokens were parsed in the production of it.
610   bool isEmpty() const {
611     return getParsedSpecifiers() == DeclSpec::PQ_None;
612   }
613
614   void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
615   void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
616
617   /// These methods set the specified attribute of the DeclSpec and
618   /// return false if there was no error.  If an error occurs (for
619   /// example, if we tried to set "auto" on a spec with "extern"
620   /// already set), they return true and set PrevSpec and DiagID
621   /// such that
622   ///   Diag(Loc, DiagID) << PrevSpec;
623   /// will yield a useful result.
624   ///
625   /// TODO: use a more general approach that still allows these
626   /// diagnostics to be ignored when desired.
627   bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
628                            const char *&PrevSpec, unsigned &DiagID,
629                            const PrintingPolicy &Policy);
630   bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
631                                  const char *&PrevSpec, unsigned &DiagID);
632   bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec,
633                         unsigned &DiagID, const PrintingPolicy &Policy);
634   bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
635                           unsigned &DiagID);
636   bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec,
637                        unsigned &DiagID);
638   bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
639                        unsigned &DiagID, const PrintingPolicy &Policy);
640   bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
641                        unsigned &DiagID, ParsedType Rep,
642                        const PrintingPolicy &Policy);
643   bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
644                        unsigned &DiagID, Decl *Rep, bool Owned,
645                        const PrintingPolicy &Policy);
646   bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
647                        SourceLocation TagNameLoc, const char *&PrevSpec,
648                        unsigned &DiagID, ParsedType Rep,
649                        const PrintingPolicy &Policy);
650   bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
651                        SourceLocation TagNameLoc, const char *&PrevSpec,
652                        unsigned &DiagID, Decl *Rep, bool Owned,
653                        const PrintingPolicy &Policy);
654
655   bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
656                        unsigned &DiagID, Expr *Rep,
657                        const PrintingPolicy &policy);
658   bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
659                        const char *&PrevSpec, unsigned &DiagID,
660                        const PrintingPolicy &Policy);
661   bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
662                        const char *&PrevSpec, unsigned &DiagID,
663                        const PrintingPolicy &Policy);
664   bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
665                        const char *&PrevSpec, unsigned &DiagID,
666                        const PrintingPolicy &Policy);
667   bool SetTypePipe(bool isPipe, SourceLocation Loc,
668                        const char *&PrevSpec, unsigned &DiagID,
669                        const PrintingPolicy &Policy);
670   bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec,
671                       unsigned &DiagID);
672   bool SetTypeSpecError();
673   void UpdateDeclRep(Decl *Rep) {
674     assert(isDeclRep((TST) TypeSpecType));
675     DeclRep = Rep;
676   }
677   void UpdateTypeRep(ParsedType Rep) {
678     assert(isTypeRep((TST) TypeSpecType));
679     TypeRep = Rep;
680   }
681   void UpdateExprRep(Expr *Rep) {
682     assert(isExprRep((TST) TypeSpecType));
683     ExprRep = Rep;
684   }
685
686   bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
687                    unsigned &DiagID, const LangOptions &Lang);
688
689   bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
690                              unsigned &DiagID);
691   bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
692                                   unsigned &DiagID);
693   bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
694                               unsigned &DiagID);
695   bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
696                                unsigned &DiagID);
697   bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
698                                unsigned &DiagID);
699
700   bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
701                      unsigned &DiagID);
702   bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
703                             unsigned &DiagID);
704   bool SetConstexprSpec(SourceLocation Loc, const char *&PrevSpec,
705                         unsigned &DiagID);
706
707   bool isFriendSpecified() const { return Friend_specified; }
708   SourceLocation getFriendSpecLoc() const { return FriendLoc; }
709
710   bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
711   SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
712   
713   bool isConstexprSpecified() const { return Constexpr_specified; }
714   SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
715
716   void ClearConstexprSpec() {
717     Constexpr_specified = false;
718     ConstexprLoc = SourceLocation();
719   }
720
721   AttributePool &getAttributePool() const {
722     return Attrs.getPool();
723   }
724
725   /// Concatenates two attribute lists.
726   ///
727   /// The GCC attribute syntax allows for the following:
728   ///
729   /// \code
730   /// short __attribute__(( unused, deprecated ))
731   /// int __attribute__(( may_alias, aligned(16) )) var;
732   /// \endcode
733   ///
734   /// This declares 4 attributes using 2 lists. The following syntax is
735   /// also allowed and equivalent to the previous declaration.
736   ///
737   /// \code
738   /// short __attribute__((unused)) __attribute__((deprecated))
739   /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
740   /// \endcode
741   ///
742   void addAttributes(ParsedAttributesView &AL) {
743     Attrs.addAll(AL.begin(), AL.end());
744   }
745
746   bool hasAttributes() const { return !Attrs.empty(); }
747
748   ParsedAttributes &getAttributes() { return Attrs; }
749   const ParsedAttributes &getAttributes() const { return Attrs; }
750
751   void takeAttributesFrom(ParsedAttributes &attrs) {
752     Attrs.takeAllFrom(attrs);
753   }
754
755   /// Finish - This does final analysis of the declspec, issuing diagnostics for
756   /// things like "_Imaginary" (lacking an FP type).  After calling this method,
757   /// DeclSpec is guaranteed self-consistent, even if an error occurred.
758   void Finish(Sema &S, const PrintingPolicy &Policy);
759
760   const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
761     return writtenBS;
762   }
763
764   ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
765   void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
766
767   /// Checks if this DeclSpec can stand alone, without a Declarator.
768   ///
769   /// Only tag declspecs can stand alone.
770   bool isMissingDeclaratorOk();
771 };
772
773 /// Captures information about "declaration specifiers" specific to
774 /// Objective-C.
775 class ObjCDeclSpec {
776 public:
777   /// ObjCDeclQualifier - Qualifier used on types in method
778   /// declarations.  Not all combinations are sensible.  Parameters
779   /// can be one of { in, out, inout } with one of { bycopy, byref }.
780   /// Returns can either be { oneway } or not.
781   ///
782   /// This should be kept in sync with Decl::ObjCDeclQualifier.
783   enum ObjCDeclQualifier {
784     DQ_None = 0x0,
785     DQ_In = 0x1,
786     DQ_Inout = 0x2,
787     DQ_Out = 0x4,
788     DQ_Bycopy = 0x8,
789     DQ_Byref = 0x10,
790     DQ_Oneway = 0x20,
791     DQ_CSNullability = 0x40
792   };
793
794   /// PropertyAttributeKind - list of property attributes.
795   /// Keep this list in sync with LLVM's Dwarf.h ApplePropertyAttributes.
796   enum ObjCPropertyAttributeKind {
797     DQ_PR_noattr = 0x0,
798     DQ_PR_readonly = 0x01,
799     DQ_PR_getter = 0x02,
800     DQ_PR_assign = 0x04,
801     DQ_PR_readwrite = 0x08,
802     DQ_PR_retain = 0x10,
803     DQ_PR_copy = 0x20,
804     DQ_PR_nonatomic = 0x40,
805     DQ_PR_setter = 0x80,
806     DQ_PR_atomic = 0x100,
807     DQ_PR_weak =   0x200,
808     DQ_PR_strong = 0x400,
809     DQ_PR_unsafe_unretained = 0x800,
810     DQ_PR_nullability = 0x1000,
811     DQ_PR_null_resettable = 0x2000,
812     DQ_PR_class = 0x4000
813   };
814
815   ObjCDeclSpec()
816     : objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr),
817       Nullability(0), GetterName(nullptr), SetterName(nullptr) { }
818
819   ObjCDeclQualifier getObjCDeclQualifier() const {
820     return (ObjCDeclQualifier)objcDeclQualifier;
821   }
822   void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
823     objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
824   }
825   void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
826     objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
827   }
828
829   ObjCPropertyAttributeKind getPropertyAttributes() const {
830     return ObjCPropertyAttributeKind(PropertyAttributes);
831   }
832   void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) {
833     PropertyAttributes =
834       (ObjCPropertyAttributeKind)(PropertyAttributes | PRVal);
835   }
836
837   NullabilityKind getNullability() const {
838     assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
839             (getPropertyAttributes() & DQ_PR_nullability)) &&
840            "Objective-C declspec doesn't have nullability");
841     return static_cast<NullabilityKind>(Nullability);
842   }
843
844   SourceLocation getNullabilityLoc() const {
845     assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
846             (getPropertyAttributes() & DQ_PR_nullability)) &&
847            "Objective-C declspec doesn't have nullability");
848     return NullabilityLoc;
849   }
850
851   void setNullability(SourceLocation loc, NullabilityKind kind) {
852     assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
853             (getPropertyAttributes() & DQ_PR_nullability)) &&
854            "Set the nullability declspec or property attribute first");
855     Nullability = static_cast<unsigned>(kind);
856     NullabilityLoc = loc;
857   }
858
859   const IdentifierInfo *getGetterName() const { return GetterName; }
860   IdentifierInfo *getGetterName() { return GetterName; }
861   SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
862   void setGetterName(IdentifierInfo *name, SourceLocation loc) {
863     GetterName = name;
864     GetterNameLoc = loc;
865   }
866
867   const IdentifierInfo *getSetterName() const { return SetterName; }
868   IdentifierInfo *getSetterName() { return SetterName; }
869   SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
870   void setSetterName(IdentifierInfo *name, SourceLocation loc) {
871     SetterName = name;
872     SetterNameLoc = loc;
873   }
874
875 private:
876   // FIXME: These two are unrelated and mutually exclusive. So perhaps
877   // we can put them in a union to reflect their mutual exclusivity
878   // (space saving is negligible).
879   unsigned objcDeclQualifier : 7;
880
881   // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind
882   unsigned PropertyAttributes : 15;
883
884   unsigned Nullability : 2;
885
886   SourceLocation NullabilityLoc;
887
888   IdentifierInfo *GetterName;    // getter name or NULL if no getter
889   IdentifierInfo *SetterName;    // setter name or NULL if no setter
890   SourceLocation GetterNameLoc; // location of the getter attribute's value
891   SourceLocation SetterNameLoc; // location of the setter attribute's value
892
893 };
894
895 /// Describes the kind of unqualified-id parsed.
896 enum class UnqualifiedIdKind {
897   /// An identifier.
898   IK_Identifier,
899   /// An overloaded operator name, e.g., operator+.
900   IK_OperatorFunctionId,
901   /// A conversion function name, e.g., operator int.
902   IK_ConversionFunctionId,
903   /// A user-defined literal name, e.g., operator "" _i.
904   IK_LiteralOperatorId,
905   /// A constructor name.
906   IK_ConstructorName,
907   /// A constructor named via a template-id.
908   IK_ConstructorTemplateId,
909   /// A destructor name.
910   IK_DestructorName,
911   /// A template-id, e.g., f<int>.
912   IK_TemplateId,
913   /// An implicit 'self' parameter
914   IK_ImplicitSelfParam,
915   /// A deduction-guide name (a template-name)
916   IK_DeductionGuideName
917 };
918
919 /// Represents a C++ unqualified-id that has been parsed. 
920 class UnqualifiedId {
921 private:
922   UnqualifiedId(const UnqualifiedId &Other) = delete;
923   const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
924
925 public:
926   /// Describes the kind of unqualified-id parsed.
927   UnqualifiedIdKind Kind;
928
929   struct OFI {
930     /// The kind of overloaded operator.
931     OverloadedOperatorKind Operator;
932
933     /// The source locations of the individual tokens that name
934     /// the operator, e.g., the "new", "[", and "]" tokens in 
935     /// operator new []. 
936     ///
937     /// Different operators have different numbers of tokens in their name,
938     /// up to three. Any remaining source locations in this array will be
939     /// set to an invalid value for operators with fewer than three tokens.
940     unsigned SymbolLocations[3];
941   };
942
943   /// Anonymous union that holds extra data associated with the
944   /// parsed unqualified-id.
945   union {
946     /// When Kind == IK_Identifier, the parsed identifier, or when
947     /// Kind == IK_UserLiteralId, the identifier suffix.
948     IdentifierInfo *Identifier;
949     
950     /// When Kind == IK_OperatorFunctionId, the overloaded operator
951     /// that we parsed.
952     struct OFI OperatorFunctionId;
953     
954     /// When Kind == IK_ConversionFunctionId, the type that the 
955     /// conversion function names.
956     UnionParsedType ConversionFunctionId;
957
958     /// When Kind == IK_ConstructorName, the class-name of the type
959     /// whose constructor is being referenced.
960     UnionParsedType ConstructorName;
961     
962     /// When Kind == IK_DestructorName, the type referred to by the
963     /// class-name.
964     UnionParsedType DestructorName;
965
966     /// When Kind == IK_DeductionGuideName, the parsed template-name.
967     UnionParsedTemplateTy TemplateName;
968     
969     /// When Kind == IK_TemplateId or IK_ConstructorTemplateId,
970     /// the template-id annotation that contains the template name and
971     /// template arguments.
972     TemplateIdAnnotation *TemplateId;
973   };
974   
975   /// The location of the first token that describes this unqualified-id,
976   /// which will be the location of the identifier, "operator" keyword,
977   /// tilde (for a destructor), or the template name of a template-id.
978   SourceLocation StartLocation;
979   
980   /// The location of the last token that describes this unqualified-id.
981   SourceLocation EndLocation;
982
983   UnqualifiedId()
984       : Kind(UnqualifiedIdKind::IK_Identifier), Identifier(nullptr) {}
985
986   /// Clear out this unqualified-id, setting it to default (invalid) 
987   /// state.
988   void clear() {
989     Kind = UnqualifiedIdKind::IK_Identifier;
990     Identifier = nullptr;
991     StartLocation = SourceLocation();
992     EndLocation = SourceLocation();
993   }
994   
995   /// Determine whether this unqualified-id refers to a valid name.
996   bool isValid() const { return StartLocation.isValid(); }
997
998   /// Determine whether this unqualified-id refers to an invalid name.
999   bool isInvalid() const { return !isValid(); }
1000   
1001   /// Determine what kind of name we have.
1002   UnqualifiedIdKind getKind() const { return Kind; }
1003   void setKind(UnqualifiedIdKind kind) { Kind = kind; } 
1004   
1005   /// Specify that this unqualified-id was parsed as an identifier.
1006   ///
1007   /// \param Id the parsed identifier.
1008   /// \param IdLoc the location of the parsed identifier.
1009   void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
1010     Kind = UnqualifiedIdKind::IK_Identifier;
1011     Identifier = const_cast<IdentifierInfo *>(Id);
1012     StartLocation = EndLocation = IdLoc;
1013   }
1014   
1015   /// Specify that this unqualified-id was parsed as an 
1016   /// operator-function-id.
1017   ///
1018   /// \param OperatorLoc the location of the 'operator' keyword.
1019   ///
1020   /// \param Op the overloaded operator.
1021   ///
1022   /// \param SymbolLocations the locations of the individual operator symbols
1023   /// in the operator.
1024   void setOperatorFunctionId(SourceLocation OperatorLoc, 
1025                              OverloadedOperatorKind Op,
1026                              SourceLocation SymbolLocations[3]);
1027   
1028   /// Specify that this unqualified-id was parsed as a 
1029   /// conversion-function-id.
1030   ///
1031   /// \param OperatorLoc the location of the 'operator' keyword.
1032   ///
1033   /// \param Ty the type to which this conversion function is converting.
1034   ///
1035   /// \param EndLoc the location of the last token that makes up the type name.
1036   void setConversionFunctionId(SourceLocation OperatorLoc, 
1037                                ParsedType Ty,
1038                                SourceLocation EndLoc) {
1039     Kind = UnqualifiedIdKind::IK_ConversionFunctionId;
1040     StartLocation = OperatorLoc;
1041     EndLocation = EndLoc;
1042     ConversionFunctionId = Ty;
1043   }
1044
1045   /// Specific that this unqualified-id was parsed as a
1046   /// literal-operator-id.
1047   ///
1048   /// \param Id the parsed identifier.
1049   ///
1050   /// \param OpLoc the location of the 'operator' keyword.
1051   ///
1052   /// \param IdLoc the location of the identifier.
1053   void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
1054                               SourceLocation IdLoc) {
1055     Kind = UnqualifiedIdKind::IK_LiteralOperatorId;
1056     Identifier = const_cast<IdentifierInfo *>(Id);
1057     StartLocation = OpLoc;
1058     EndLocation = IdLoc;
1059   }
1060   
1061   /// Specify that this unqualified-id was parsed as a constructor name.
1062   ///
1063   /// \param ClassType the class type referred to by the constructor name.
1064   ///
1065   /// \param ClassNameLoc the location of the class name.
1066   ///
1067   /// \param EndLoc the location of the last token that makes up the type name.
1068   void setConstructorName(ParsedType ClassType, 
1069                           SourceLocation ClassNameLoc,
1070                           SourceLocation EndLoc) {
1071     Kind = UnqualifiedIdKind::IK_ConstructorName;
1072     StartLocation = ClassNameLoc;
1073     EndLocation = EndLoc;
1074     ConstructorName = ClassType;
1075   }
1076
1077   /// Specify that this unqualified-id was parsed as a
1078   /// template-id that names a constructor.
1079   ///
1080   /// \param TemplateId the template-id annotation that describes the parsed
1081   /// template-id. This UnqualifiedId instance will take ownership of the
1082   /// \p TemplateId and will free it on destruction.
1083   void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
1084
1085   /// Specify that this unqualified-id was parsed as a destructor name.
1086   ///
1087   /// \param TildeLoc the location of the '~' that introduces the destructor
1088   /// name.
1089   ///
1090   /// \param ClassType the name of the class referred to by the destructor name.
1091   void setDestructorName(SourceLocation TildeLoc,
1092                          ParsedType ClassType,
1093                          SourceLocation EndLoc) {
1094     Kind = UnqualifiedIdKind::IK_DestructorName;
1095     StartLocation = TildeLoc;
1096     EndLocation = EndLoc;
1097     DestructorName = ClassType;
1098   }
1099   
1100   /// Specify that this unqualified-id was parsed as a template-id.
1101   ///
1102   /// \param TemplateId the template-id annotation that describes the parsed
1103   /// template-id. This UnqualifiedId instance will take ownership of the
1104   /// \p TemplateId and will free it on destruction.
1105   void setTemplateId(TemplateIdAnnotation *TemplateId);
1106
1107   /// Specify that this unqualified-id was parsed as a template-name for
1108   /// a deduction-guide.
1109   ///
1110   /// \param Template The parsed template-name.
1111   /// \param TemplateLoc The location of the parsed template-name.
1112   void setDeductionGuideName(ParsedTemplateTy Template,
1113                              SourceLocation TemplateLoc) {
1114     Kind = UnqualifiedIdKind::IK_DeductionGuideName;
1115     TemplateName = Template;
1116     StartLocation = EndLocation = TemplateLoc;
1117   }
1118   
1119   /// Return the source range that covers this unqualified-id.
1120   SourceRange getSourceRange() const LLVM_READONLY { 
1121     return SourceRange(StartLocation, EndLocation); 
1122   }
1123   SourceLocation getLocStart() const LLVM_READONLY { return StartLocation; }
1124   SourceLocation getLocEnd() const LLVM_READONLY { return EndLocation; }
1125 };
1126
1127 /// A set of tokens that has been cached for later parsing.
1128 typedef SmallVector<Token, 4> CachedTokens;
1129
1130 /// One instance of this struct is used for each type in a
1131 /// declarator that is parsed.
1132 ///
1133 /// This is intended to be a small value object.
1134 struct DeclaratorChunk {
1135   enum {
1136     Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe
1137   } Kind;
1138
1139   /// Loc - The place where this type was defined.
1140   SourceLocation Loc;
1141   /// EndLoc - If valid, the place where this chunck ends.
1142   SourceLocation EndLoc;
1143
1144   SourceRange getSourceRange() const {
1145     if (EndLoc.isInvalid())
1146       return SourceRange(Loc, Loc);
1147     return SourceRange(Loc, EndLoc);
1148   }
1149
1150   ParsedAttributesView AttrList;
1151
1152   struct PointerTypeInfo {
1153     /// The type qualifiers: const/volatile/restrict/unaligned/atomic.
1154     unsigned TypeQuals : 5;
1155
1156     /// The location of the const-qualifier, if any.
1157     unsigned ConstQualLoc;
1158
1159     /// The location of the volatile-qualifier, if any.
1160     unsigned VolatileQualLoc;
1161
1162     /// The location of the restrict-qualifier, if any.
1163     unsigned RestrictQualLoc;
1164
1165     /// The location of the _Atomic-qualifier, if any.
1166     unsigned AtomicQualLoc;
1167
1168     /// The location of the __unaligned-qualifier, if any.
1169     unsigned UnalignedQualLoc;
1170
1171     void destroy() {
1172     }
1173   };
1174
1175   struct ReferenceTypeInfo {
1176     /// The type qualifier: restrict. [GNU] C++ extension
1177     bool HasRestrict : 1;
1178     /// True if this is an lvalue reference, false if it's an rvalue reference.
1179     bool LValueRef : 1;
1180     void destroy() {
1181     }
1182   };
1183
1184   struct ArrayTypeInfo {
1185     /// The type qualifiers for the array:
1186     /// const/volatile/restrict/__unaligned/_Atomic.
1187     unsigned TypeQuals : 5;
1188
1189     /// True if this dimension included the 'static' keyword.
1190     unsigned hasStatic : 1;
1191
1192     /// True if this dimension was [*].  In this case, NumElts is null.
1193     unsigned isStar : 1;
1194
1195     /// This is the size of the array, or null if [] or [*] was specified.
1196     /// Since the parser is multi-purpose, and we don't want to impose a root
1197     /// expression class on all clients, NumElts is untyped.
1198     Expr *NumElts;
1199
1200     void destroy() {}
1201   };
1202
1203   /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1204   /// declarator is parsed.  There are two interesting styles of parameters
1205   /// here:
1206   /// K&R-style identifier lists and parameter type lists.  K&R-style identifier
1207   /// lists will have information about the identifier, but no type information.
1208   /// Parameter type lists will have type info (if the actions module provides
1209   /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1210   struct ParamInfo {
1211     IdentifierInfo *Ident;
1212     SourceLocation IdentLoc;
1213     Decl *Param;
1214
1215     /// DefaultArgTokens - When the parameter's default argument
1216     /// cannot be parsed immediately (because it occurs within the
1217     /// declaration of a member function), it will be stored here as a
1218     /// sequence of tokens to be parsed once the class definition is
1219     /// complete. Non-NULL indicates that there is a default argument.
1220     std::unique_ptr<CachedTokens> DefaultArgTokens;
1221
1222     ParamInfo() = default;
1223     ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1224               Decl *param,
1225               std::unique_ptr<CachedTokens> DefArgTokens = nullptr)
1226       : Ident(ident), IdentLoc(iloc), Param(param),
1227         DefaultArgTokens(std::move(DefArgTokens)) {}
1228   };
1229
1230   struct TypeAndRange {
1231     ParsedType Ty;
1232     SourceRange Range;
1233   };
1234
1235   struct FunctionTypeInfo {
1236     /// hasPrototype - This is true if the function had at least one typed
1237     /// parameter.  If the function is () or (a,b,c), then it has no prototype,
1238     /// and is treated as a K&R-style function.
1239     unsigned hasPrototype : 1;
1240
1241     /// isVariadic - If this function has a prototype, and if that
1242     /// proto ends with ',...)', this is true. When true, EllipsisLoc
1243     /// contains the location of the ellipsis.
1244     unsigned isVariadic : 1;
1245
1246     /// Can this declaration be a constructor-style initializer?
1247     unsigned isAmbiguous : 1;
1248
1249     /// Whether the ref-qualifier (if any) is an lvalue reference.
1250     /// Otherwise, it's an rvalue reference.
1251     unsigned RefQualifierIsLValueRef : 1;
1252
1253     /// The type qualifiers: const/volatile/restrict/__unaligned
1254     /// The qualifier bitmask values are the same as in QualType.
1255     unsigned TypeQuals : 4;
1256
1257     /// ExceptionSpecType - An ExceptionSpecificationType value.
1258     unsigned ExceptionSpecType : 4;
1259
1260     /// DeleteParams - If this is true, we need to delete[] Params.
1261     unsigned DeleteParams : 1;
1262
1263     /// HasTrailingReturnType - If this is true, a trailing return type was
1264     /// specified.
1265     unsigned HasTrailingReturnType : 1;
1266
1267     /// The location of the left parenthesis in the source.
1268     unsigned LParenLoc;
1269
1270     /// When isVariadic is true, the location of the ellipsis in the source.
1271     unsigned EllipsisLoc;
1272
1273     /// The location of the right parenthesis in the source.
1274     unsigned RParenLoc;
1275
1276     /// NumParams - This is the number of formal parameters specified by the
1277     /// declarator.
1278     unsigned NumParams;
1279
1280     /// NumExceptionsOrDecls - This is the number of types in the
1281     /// dynamic-exception-decl, if the function has one. In C, this is the
1282     /// number of declarations in the function prototype.
1283     unsigned NumExceptionsOrDecls;
1284
1285     /// The location of the ref-qualifier, if any.
1286     ///
1287     /// If this is an invalid location, there is no ref-qualifier.
1288     unsigned RefQualifierLoc;
1289
1290     /// The location of the const-qualifier, if any.
1291     ///
1292     /// If this is an invalid location, there is no const-qualifier.
1293     unsigned ConstQualifierLoc;
1294
1295     /// The location of the volatile-qualifier, if any.
1296     ///
1297     /// If this is an invalid location, there is no volatile-qualifier.
1298     unsigned VolatileQualifierLoc;
1299
1300     /// The location of the restrict-qualifier, if any.
1301     ///
1302     /// If this is an invalid location, there is no restrict-qualifier.
1303     unsigned RestrictQualifierLoc;
1304
1305     /// The location of the 'mutable' qualifer in a lambda-declarator, if
1306     /// any.
1307     unsigned MutableLoc;
1308
1309     /// The beginning location of the exception specification, if any.
1310     unsigned ExceptionSpecLocBeg;
1311
1312     /// The end location of the exception specification, if any.
1313     unsigned ExceptionSpecLocEnd;
1314
1315     /// Params - This is a pointer to a new[]'d array of ParamInfo objects that
1316     /// describe the parameters specified by this function declarator.  null if
1317     /// there are no parameters specified.
1318     ParamInfo *Params;
1319
1320     union {
1321       /// Pointer to a new[]'d array of TypeAndRange objects that
1322       /// contain the types in the function's dynamic exception specification
1323       /// and their locations, if there is one.
1324       TypeAndRange *Exceptions;
1325
1326       /// Pointer to the expression in the noexcept-specifier of this
1327       /// function, if it has one.
1328       Expr *NoexceptExpr;
1329   
1330       /// Pointer to the cached tokens for an exception-specification
1331       /// that has not yet been parsed.
1332       CachedTokens *ExceptionSpecTokens;
1333
1334       /// Pointer to a new[]'d array of declarations that need to be available
1335       /// for lookup inside the function body, if one exists. Does not exist in
1336       /// C++.
1337       NamedDecl **DeclsInPrototype;
1338     };
1339
1340     /// If HasTrailingReturnType is true, this is the trailing return
1341     /// type specified.
1342     UnionParsedType TrailingReturnType;
1343
1344     /// Reset the parameter list to having zero parameters.
1345     ///
1346     /// This is used in various places for error recovery.
1347     void freeParams() {
1348       for (unsigned I = 0; I < NumParams; ++I)
1349         Params[I].DefaultArgTokens.reset();
1350       if (DeleteParams) {
1351         delete[] Params;
1352         DeleteParams = false;
1353       }
1354       NumParams = 0;
1355     }
1356
1357     void destroy() {
1358       freeParams();
1359       switch (getExceptionSpecType()) {
1360       default:
1361         break;
1362       case EST_Dynamic:
1363         delete[] Exceptions;
1364         break;
1365       case EST_Unparsed:
1366         delete ExceptionSpecTokens;
1367         break;
1368       case EST_None:
1369         if (NumExceptionsOrDecls != 0)
1370           delete[] DeclsInPrototype;
1371         break;
1372       }
1373     }
1374
1375     /// isKNRPrototype - Return true if this is a K&R style identifier list,
1376     /// like "void foo(a,b,c)".  In a function definition, this will be followed
1377     /// by the parameter type definitions.
1378     bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
1379
1380     SourceLocation getLParenLoc() const {
1381       return SourceLocation::getFromRawEncoding(LParenLoc);
1382     }
1383
1384     SourceLocation getEllipsisLoc() const {
1385       return SourceLocation::getFromRawEncoding(EllipsisLoc);
1386     }
1387
1388     SourceLocation getRParenLoc() const {
1389       return SourceLocation::getFromRawEncoding(RParenLoc);
1390     }
1391
1392     SourceLocation getExceptionSpecLocBeg() const {
1393       return SourceLocation::getFromRawEncoding(ExceptionSpecLocBeg);
1394     }
1395
1396     SourceLocation getExceptionSpecLocEnd() const {
1397       return SourceLocation::getFromRawEncoding(ExceptionSpecLocEnd);
1398     }
1399
1400     SourceRange getExceptionSpecRange() const {
1401       return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd());
1402     }
1403
1404     /// Retrieve the location of the ref-qualifier, if any.
1405     SourceLocation getRefQualifierLoc() const {
1406       return SourceLocation::getFromRawEncoding(RefQualifierLoc);
1407     }
1408
1409     /// Retrieve the location of the 'const' qualifier, if any.
1410     SourceLocation getConstQualifierLoc() const {
1411       return SourceLocation::getFromRawEncoding(ConstQualifierLoc);
1412     }
1413
1414     /// Retrieve the location of the 'volatile' qualifier, if any.
1415     SourceLocation getVolatileQualifierLoc() const {
1416       return SourceLocation::getFromRawEncoding(VolatileQualifierLoc);
1417     }
1418
1419     /// Retrieve the location of the 'restrict' qualifier, if any.
1420     SourceLocation getRestrictQualifierLoc() const {
1421       return SourceLocation::getFromRawEncoding(RestrictQualifierLoc);
1422     }
1423
1424     /// Retrieve the location of the 'mutable' qualifier, if any.
1425     SourceLocation getMutableLoc() const {
1426       return SourceLocation::getFromRawEncoding(MutableLoc);
1427     }
1428
1429     /// Determine whether this function declaration contains a 
1430     /// ref-qualifier.
1431     bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1432
1433     /// Determine whether this lambda-declarator contains a 'mutable'
1434     /// qualifier.
1435     bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1436
1437     /// Get the type of exception specification this function has.
1438     ExceptionSpecificationType getExceptionSpecType() const {
1439       return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1440     }
1441
1442     /// Get the number of dynamic exception specifications.
1443     unsigned getNumExceptions() const {
1444       assert(ExceptionSpecType != EST_None);
1445       return NumExceptionsOrDecls;
1446     }
1447
1448     /// Get the non-parameter decls defined within this function
1449     /// prototype. Typically these are tag declarations.
1450     ArrayRef<NamedDecl *> getDeclsInPrototype() const {
1451       assert(ExceptionSpecType == EST_None);
1452       return llvm::makeArrayRef(DeclsInPrototype, NumExceptionsOrDecls);
1453     }
1454
1455     /// Determine whether this function declarator had a
1456     /// trailing-return-type.
1457     bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1458
1459     /// Get the trailing-return-type for this function declarator.
1460     ParsedType getTrailingReturnType() const { return TrailingReturnType; }
1461   };
1462
1463   struct BlockPointerTypeInfo {
1464     /// For now, sema will catch these as invalid.
1465     /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1466     unsigned TypeQuals : 5;
1467
1468     void destroy() {
1469     }
1470   };
1471
1472   struct MemberPointerTypeInfo {
1473     /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1474     unsigned TypeQuals : 5;
1475     // CXXScopeSpec has a constructor, so it can't be a direct member.
1476     // So we need some pointer-aligned storage and a bit of trickery.
1477     alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)];
1478     CXXScopeSpec &Scope() {
1479       return *reinterpret_cast<CXXScopeSpec *>(ScopeMem);
1480     }
1481     const CXXScopeSpec &Scope() const {
1482       return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem);
1483     }
1484     void destroy() {
1485       Scope().~CXXScopeSpec();
1486     }
1487   };
1488
1489   struct PipeTypeInfo {
1490     /// The access writes.
1491     unsigned AccessWrites : 3;
1492
1493     void destroy() {}
1494   };
1495
1496   union {
1497     PointerTypeInfo       Ptr;
1498     ReferenceTypeInfo     Ref;
1499     ArrayTypeInfo         Arr;
1500     FunctionTypeInfo      Fun;
1501     BlockPointerTypeInfo  Cls;
1502     MemberPointerTypeInfo Mem;
1503     PipeTypeInfo          PipeInfo;
1504   };
1505
1506   void destroy() {
1507     switch (Kind) {
1508     case DeclaratorChunk::Function:      return Fun.destroy();
1509     case DeclaratorChunk::Pointer:       return Ptr.destroy();
1510     case DeclaratorChunk::BlockPointer:  return Cls.destroy();
1511     case DeclaratorChunk::Reference:     return Ref.destroy();
1512     case DeclaratorChunk::Array:         return Arr.destroy();
1513     case DeclaratorChunk::MemberPointer: return Mem.destroy();
1514     case DeclaratorChunk::Paren:         return;
1515     case DeclaratorChunk::Pipe:          return PipeInfo.destroy();
1516     }
1517   }
1518
1519   /// If there are attributes applied to this declaratorchunk, return
1520   /// them.
1521   const ParsedAttributesView &getAttrs() const { return AttrList; }
1522   ParsedAttributesView &getAttrs() { return AttrList; }
1523
1524   /// Return a DeclaratorChunk for a pointer.
1525   static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1526                                     SourceLocation ConstQualLoc,
1527                                     SourceLocation VolatileQualLoc,
1528                                     SourceLocation RestrictQualLoc,
1529                                     SourceLocation AtomicQualLoc,
1530                                     SourceLocation UnalignedQualLoc) {
1531     DeclaratorChunk I;
1532     I.Kind                = Pointer;
1533     I.Loc                 = Loc;
1534     I.Ptr.TypeQuals       = TypeQuals;
1535     I.Ptr.ConstQualLoc    = ConstQualLoc.getRawEncoding();
1536     I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
1537     I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
1538     I.Ptr.AtomicQualLoc   = AtomicQualLoc.getRawEncoding();
1539     I.Ptr.UnalignedQualLoc = UnalignedQualLoc.getRawEncoding();
1540     return I;
1541   }
1542
1543   /// Return a DeclaratorChunk for a reference.
1544   static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1545                                       bool lvalue) {
1546     DeclaratorChunk I;
1547     I.Kind            = Reference;
1548     I.Loc             = Loc;
1549     I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1550     I.Ref.LValueRef   = lvalue;
1551     return I;
1552   }
1553
1554   /// Return a DeclaratorChunk for an array.
1555   static DeclaratorChunk getArray(unsigned TypeQuals,
1556                                   bool isStatic, bool isStar, Expr *NumElts,
1557                                   SourceLocation LBLoc, SourceLocation RBLoc) {
1558     DeclaratorChunk I;
1559     I.Kind          = Array;
1560     I.Loc           = LBLoc;
1561     I.EndLoc        = RBLoc;
1562     I.Arr.TypeQuals = TypeQuals;
1563     I.Arr.hasStatic = isStatic;
1564     I.Arr.isStar    = isStar;
1565     I.Arr.NumElts   = NumElts;
1566     return I;
1567   }
1568
1569   /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1570   /// "TheDeclarator" is the declarator that this will be added to.
1571   static DeclaratorChunk getFunction(bool HasProto,
1572                                      bool IsAmbiguous,
1573                                      SourceLocation LParenLoc,
1574                                      ParamInfo *Params, unsigned NumParams,
1575                                      SourceLocation EllipsisLoc,
1576                                      SourceLocation RParenLoc,
1577                                      unsigned TypeQuals,
1578                                      bool RefQualifierIsLvalueRef,
1579                                      SourceLocation RefQualifierLoc,
1580                                      SourceLocation ConstQualifierLoc,
1581                                      SourceLocation VolatileQualifierLoc,
1582                                      SourceLocation RestrictQualifierLoc,
1583                                      SourceLocation MutableLoc,
1584                                      ExceptionSpecificationType ESpecType,
1585                                      SourceRange ESpecRange,
1586                                      ParsedType *Exceptions,
1587                                      SourceRange *ExceptionRanges,
1588                                      unsigned NumExceptions,
1589                                      Expr *NoexceptExpr,
1590                                      CachedTokens *ExceptionSpecTokens,
1591                                      ArrayRef<NamedDecl *> DeclsInPrototype,
1592                                      SourceLocation LocalRangeBegin,
1593                                      SourceLocation LocalRangeEnd,
1594                                      Declarator &TheDeclarator,
1595                                      TypeResult TrailingReturnType =
1596                                                     TypeResult());
1597
1598   /// Return a DeclaratorChunk for a block.
1599   static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1600                                          SourceLocation Loc) {
1601     DeclaratorChunk I;
1602     I.Kind          = BlockPointer;
1603     I.Loc           = Loc;
1604     I.Cls.TypeQuals = TypeQuals;
1605     return I;
1606   }
1607
1608   /// Return a DeclaratorChunk for a block.
1609   static DeclaratorChunk getPipe(unsigned TypeQuals,
1610                                  SourceLocation Loc) {
1611     DeclaratorChunk I;
1612     I.Kind          = Pipe;
1613     I.Loc           = Loc;
1614     I.Cls.TypeQuals = TypeQuals;
1615     return I;
1616   }
1617
1618   static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1619                                           unsigned TypeQuals,
1620                                           SourceLocation Loc) {
1621     DeclaratorChunk I;
1622     I.Kind          = MemberPointer;
1623     I.Loc           = SS.getBeginLoc();
1624     I.EndLoc        = Loc;
1625     I.Mem.TypeQuals = TypeQuals;
1626     new (I.Mem.ScopeMem) CXXScopeSpec(SS);
1627     return I;
1628   }
1629
1630   /// Return a DeclaratorChunk for a paren.
1631   static DeclaratorChunk getParen(SourceLocation LParenLoc,
1632                                   SourceLocation RParenLoc) {
1633     DeclaratorChunk I;
1634     I.Kind          = Paren;
1635     I.Loc           = LParenLoc;
1636     I.EndLoc        = RParenLoc;
1637     return I;
1638   }
1639
1640   bool isParen() const {
1641     return Kind == Paren;
1642   }
1643 };
1644
1645 /// A parsed C++17 decomposition declarator of the form
1646 ///   '[' identifier-list ']'
1647 class DecompositionDeclarator {
1648 public:
1649   struct Binding {
1650     IdentifierInfo *Name;
1651     SourceLocation NameLoc;
1652   };
1653
1654 private:
1655   /// The locations of the '[' and ']' tokens.
1656   SourceLocation LSquareLoc, RSquareLoc;
1657
1658   /// The bindings.
1659   Binding *Bindings;
1660   unsigned NumBindings : 31;
1661   unsigned DeleteBindings : 1;
1662
1663   friend class Declarator;
1664
1665 public:
1666   DecompositionDeclarator()
1667       : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {}
1668   DecompositionDeclarator(const DecompositionDeclarator &G) = delete;
1669   DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete;
1670   ~DecompositionDeclarator() {
1671     if (DeleteBindings)
1672       delete[] Bindings;
1673   }
1674
1675   void clear() {
1676     LSquareLoc = RSquareLoc = SourceLocation();
1677     if (DeleteBindings)
1678       delete[] Bindings;
1679     Bindings = nullptr;
1680     NumBindings = 0;
1681     DeleteBindings = false;
1682   }
1683
1684   ArrayRef<Binding> bindings() const {
1685     return llvm::makeArrayRef(Bindings, NumBindings);
1686   }
1687
1688   bool isSet() const { return LSquareLoc.isValid(); }
1689
1690   SourceLocation getLSquareLoc() const { return LSquareLoc; }
1691   SourceLocation getRSquareLoc() const { return RSquareLoc; }
1692   SourceRange getSourceRange() const {
1693     return SourceRange(LSquareLoc, RSquareLoc);
1694   }
1695 };
1696
1697 /// Described the kind of function definition (if any) provided for
1698 /// a function.
1699 enum FunctionDefinitionKind {
1700   FDK_Declaration,
1701   FDK_Definition,
1702   FDK_Defaulted,
1703   FDK_Deleted
1704 };
1705
1706 enum class DeclaratorContext {
1707     FileContext,         // File scope declaration.
1708     PrototypeContext,    // Within a function prototype.
1709     ObjCResultContext,   // An ObjC method result type.
1710     ObjCParameterContext,// An ObjC method parameter type.
1711     KNRTypeListContext,  // K&R type definition list for formals.
1712     TypeNameContext,     // Abstract declarator for types.
1713     FunctionalCastContext, // Type in a C++ functional cast expression.
1714     MemberContext,       // Struct/Union field.
1715     BlockContext,        // Declaration within a block in a function.
1716     ForContext,          // Declaration within first part of a for loop.
1717     InitStmtContext,     // Declaration within optional init stmt of if/switch.
1718     ConditionContext,    // Condition declaration in a C++ if/switch/while/for.
1719     TemplateParamContext,// Within a template parameter list.
1720     CXXNewContext,       // C++ new-expression.
1721     CXXCatchContext,     // C++ catch exception-declaration
1722     ObjCCatchContext,    // Objective-C catch exception-declaration
1723     BlockLiteralContext, // Block literal declarator.
1724     LambdaExprContext,   // Lambda-expression declarator.
1725     LambdaExprParameterContext, // Lambda-expression parameter declarator.
1726     ConversionIdContext, // C++ conversion-type-id.
1727     TrailingReturnContext, // C++11 trailing-type-specifier.
1728     TrailingReturnVarContext, // C++11 trailing-type-specifier for variable.
1729     TemplateArgContext,  // Any template argument (in template argument list).
1730     TemplateTypeArgContext, // Template type argument (in default argument).
1731     AliasDeclContext,    // C++11 alias-declaration.
1732     AliasTemplateContext // C++11 alias-declaration template.
1733 };
1734
1735
1736 /// Information about one declarator, including the parsed type
1737 /// information and the identifier.
1738 ///
1739 /// When the declarator is fully formed, this is turned into the appropriate
1740 /// Decl object.
1741 ///
1742 /// Declarators come in two types: normal declarators and abstract declarators.
1743 /// Abstract declarators are used when parsing types, and don't have an
1744 /// identifier.  Normal declarators do have ID's.
1745 ///
1746 /// Instances of this class should be a transient object that lives on the
1747 /// stack, not objects that are allocated in large quantities on the heap.
1748 class Declarator {
1749   
1750 private:
1751   const DeclSpec &DS;
1752   CXXScopeSpec SS;
1753   UnqualifiedId Name;
1754   SourceRange Range;
1755
1756   /// Where we are parsing this declarator.
1757   DeclaratorContext Context;
1758
1759   /// The C++17 structured binding, if any. This is an alternative to a Name.
1760   DecompositionDeclarator BindingGroup;
1761
1762   /// DeclTypeInfo - This holds each type that the declarator includes as it is
1763   /// parsed.  This is pushed from the identifier out, which means that element
1764   /// #0 will be the most closely bound to the identifier, and
1765   /// DeclTypeInfo.back() will be the least closely bound.
1766   SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1767
1768   /// InvalidType - Set by Sema::GetTypeForDeclarator().
1769   unsigned InvalidType : 1;
1770
1771   /// GroupingParens - Set by Parser::ParseParenDeclarator().
1772   unsigned GroupingParens : 1;
1773
1774   /// FunctionDefinition - Is this Declarator for a function or member 
1775   /// definition and, if so, what kind?
1776   ///
1777   /// Actually a FunctionDefinitionKind.
1778   unsigned FunctionDefinition : 2;
1779
1780   /// Is this Declarator a redeclaration?
1781   unsigned Redeclaration : 1;
1782
1783   /// true if the declaration is preceded by \c __extension__.
1784   unsigned Extension : 1;
1785
1786   /// Indicates whether this is an Objective-C instance variable.
1787   unsigned ObjCIvar : 1;
1788     
1789   /// Indicates whether this is an Objective-C 'weak' property.
1790   unsigned ObjCWeakProperty : 1;
1791
1792   /// Indicates whether the InlineParams / InlineBindings storage has been used.
1793   unsigned InlineStorageUsed : 1;
1794
1795   /// Attrs - Attributes.
1796   ParsedAttributes Attrs;
1797
1798   /// The asm label, if specified.
1799   Expr *AsmLabel;
1800
1801 #ifndef _MSC_VER
1802   union {
1803 #endif
1804     /// InlineParams - This is a local array used for the first function decl
1805     /// chunk to avoid going to the heap for the common case when we have one
1806     /// function chunk in the declarator.
1807     DeclaratorChunk::ParamInfo InlineParams[16];
1808     DecompositionDeclarator::Binding InlineBindings[16];
1809 #ifndef _MSC_VER
1810   };
1811 #endif
1812
1813   /// If this is the second or subsequent declarator in this declaration,
1814   /// the location of the comma before this declarator.
1815   SourceLocation CommaLoc;
1816
1817   /// If provided, the source location of the ellipsis used to describe
1818   /// this declarator as a parameter pack.
1819   SourceLocation EllipsisLoc;
1820   
1821   friend struct DeclaratorChunk;
1822
1823 public:
1824   Declarator(const DeclSpec &ds, DeclaratorContext C)
1825       : DS(ds), Range(ds.getSourceRange()), Context(C),
1826         InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1827         GroupingParens(false), FunctionDefinition(FDK_Declaration),
1828         Redeclaration(false), Extension(false), ObjCIvar(false),
1829         ObjCWeakProperty(false), InlineStorageUsed(false),
1830         Attrs(ds.getAttributePool().getFactory()), AsmLabel(nullptr) {}
1831
1832   ~Declarator() {
1833     clear();
1834   }
1835   /// getDeclSpec - Return the declaration-specifier that this declarator was
1836   /// declared with.
1837   const DeclSpec &getDeclSpec() const { return DS; }
1838
1839   /// getMutableDeclSpec - Return a non-const version of the DeclSpec.  This
1840   /// should be used with extreme care: declspecs can often be shared between
1841   /// multiple declarators, so mutating the DeclSpec affects all of the
1842   /// Declarators.  This should only be done when the declspec is known to not
1843   /// be shared or when in error recovery etc.
1844   DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1845
1846   AttributePool &getAttributePool() const {
1847     return Attrs.getPool();
1848   }
1849
1850   /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1851   /// nested-name-specifier) that is part of the declarator-id.
1852   const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1853   CXXScopeSpec &getCXXScopeSpec() { return SS; }
1854
1855   /// Retrieve the name specified by this declarator.
1856   UnqualifiedId &getName() { return Name; }
1857
1858   const DecompositionDeclarator &getDecompositionDeclarator() const {
1859     return BindingGroup;
1860   }
1861   
1862   DeclaratorContext getContext() const { return Context; }
1863
1864   bool isPrototypeContext() const {
1865     return (Context == DeclaratorContext::PrototypeContext ||
1866             Context == DeclaratorContext::ObjCParameterContext ||
1867             Context == DeclaratorContext::ObjCResultContext ||
1868             Context == DeclaratorContext::LambdaExprParameterContext);
1869   }
1870
1871   /// Get the source range that spans this declarator.
1872   SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1873   SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1874   SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1875
1876   void SetSourceRange(SourceRange R) { Range = R; }
1877   /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1878   /// invalid.
1879   void SetRangeBegin(SourceLocation Loc) {
1880     if (!Loc.isInvalid())
1881       Range.setBegin(Loc);
1882   }
1883   /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1884   void SetRangeEnd(SourceLocation Loc) {
1885     if (!Loc.isInvalid())
1886       Range.setEnd(Loc);
1887   }
1888   /// ExtendWithDeclSpec - Extend the declarator source range to include the
1889   /// given declspec, unless its location is invalid. Adopts the range start if
1890   /// the current range start is invalid.
1891   void ExtendWithDeclSpec(const DeclSpec &DS) {
1892     SourceRange SR = DS.getSourceRange();
1893     if (Range.getBegin().isInvalid())
1894       Range.setBegin(SR.getBegin());
1895     if (!SR.getEnd().isInvalid())
1896       Range.setEnd(SR.getEnd());
1897   }
1898
1899   /// Reset the contents of this Declarator.
1900   void clear() {
1901     SS.clear();
1902     Name.clear();
1903     Range = DS.getSourceRange();
1904     BindingGroup.clear();
1905
1906     for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1907       DeclTypeInfo[i].destroy();
1908     DeclTypeInfo.clear();
1909     Attrs.clear();
1910     AsmLabel = nullptr;
1911     InlineStorageUsed = false;
1912     ObjCIvar = false;
1913     ObjCWeakProperty = false;
1914     CommaLoc = SourceLocation();
1915     EllipsisLoc = SourceLocation();
1916   }
1917
1918   /// mayOmitIdentifier - Return true if the identifier is either optional or
1919   /// not allowed.  This is true for typenames, prototypes, and template
1920   /// parameter lists.
1921   bool mayOmitIdentifier() const {
1922     switch (Context) {
1923     case DeclaratorContext::FileContext:
1924     case DeclaratorContext::KNRTypeListContext:
1925     case DeclaratorContext::MemberContext:
1926     case DeclaratorContext::BlockContext:
1927     case DeclaratorContext::ForContext:
1928     case DeclaratorContext::InitStmtContext:
1929     case DeclaratorContext::ConditionContext:
1930       return false;
1931
1932     case DeclaratorContext::TypeNameContext:
1933     case DeclaratorContext::FunctionalCastContext:
1934     case DeclaratorContext::AliasDeclContext:
1935     case DeclaratorContext::AliasTemplateContext:
1936     case DeclaratorContext::PrototypeContext:
1937     case DeclaratorContext::LambdaExprParameterContext:
1938     case DeclaratorContext::ObjCParameterContext:
1939     case DeclaratorContext::ObjCResultContext:
1940     case DeclaratorContext::TemplateParamContext:
1941     case DeclaratorContext::CXXNewContext:
1942     case DeclaratorContext::CXXCatchContext:
1943     case DeclaratorContext::ObjCCatchContext:
1944     case DeclaratorContext::BlockLiteralContext:
1945     case DeclaratorContext::LambdaExprContext:
1946     case DeclaratorContext::ConversionIdContext:
1947     case DeclaratorContext::TemplateArgContext:
1948     case DeclaratorContext::TemplateTypeArgContext:
1949     case DeclaratorContext::TrailingReturnContext:
1950     case DeclaratorContext::TrailingReturnVarContext:
1951       return true;
1952     }
1953     llvm_unreachable("unknown context kind!");
1954   }
1955
1956   /// mayHaveIdentifier - Return true if the identifier is either optional or
1957   /// required.  This is true for normal declarators and prototypes, but not
1958   /// typenames.
1959   bool mayHaveIdentifier() const {
1960     switch (Context) {
1961     case DeclaratorContext::FileContext:
1962     case DeclaratorContext::KNRTypeListContext:
1963     case DeclaratorContext::MemberContext:
1964     case DeclaratorContext::BlockContext:
1965     case DeclaratorContext::ForContext:
1966     case DeclaratorContext::InitStmtContext:
1967     case DeclaratorContext::ConditionContext:
1968     case DeclaratorContext::PrototypeContext:
1969     case DeclaratorContext::LambdaExprParameterContext:
1970     case DeclaratorContext::TemplateParamContext:
1971     case DeclaratorContext::CXXCatchContext:
1972     case DeclaratorContext::ObjCCatchContext:
1973       return true;
1974
1975     case DeclaratorContext::TypeNameContext:
1976     case DeclaratorContext::FunctionalCastContext:
1977     case DeclaratorContext::CXXNewContext:
1978     case DeclaratorContext::AliasDeclContext:
1979     case DeclaratorContext::AliasTemplateContext:
1980     case DeclaratorContext::ObjCParameterContext:
1981     case DeclaratorContext::ObjCResultContext:
1982     case DeclaratorContext::BlockLiteralContext:
1983     case DeclaratorContext::LambdaExprContext:
1984     case DeclaratorContext::ConversionIdContext:
1985     case DeclaratorContext::TemplateArgContext:
1986     case DeclaratorContext::TemplateTypeArgContext:
1987     case DeclaratorContext::TrailingReturnContext:
1988     case DeclaratorContext::TrailingReturnVarContext:
1989       return false;
1990     }
1991     llvm_unreachable("unknown context kind!");
1992   }
1993
1994   /// Return true if the context permits a C++17 decomposition declarator.
1995   bool mayHaveDecompositionDeclarator() const {
1996     switch (Context) {
1997     case DeclaratorContext::FileContext:
1998       // FIXME: It's not clear that the proposal meant to allow file-scope
1999       // structured bindings, but it does.
2000     case DeclaratorContext::BlockContext:
2001     case DeclaratorContext::ForContext:
2002     case DeclaratorContext::InitStmtContext:
2003     case DeclaratorContext::ConditionContext:
2004       return true;
2005
2006     case DeclaratorContext::MemberContext:
2007     case DeclaratorContext::PrototypeContext:
2008     case DeclaratorContext::TemplateParamContext:
2009       // Maybe one day...
2010       return false;
2011
2012     // These contexts don't allow any kind of non-abstract declarator.
2013     case DeclaratorContext::KNRTypeListContext:
2014     case DeclaratorContext::TypeNameContext:
2015     case DeclaratorContext::FunctionalCastContext:
2016     case DeclaratorContext::AliasDeclContext:
2017     case DeclaratorContext::AliasTemplateContext:
2018     case DeclaratorContext::LambdaExprParameterContext:
2019     case DeclaratorContext::ObjCParameterContext:
2020     case DeclaratorContext::ObjCResultContext:
2021     case DeclaratorContext::CXXNewContext:
2022     case DeclaratorContext::CXXCatchContext:
2023     case DeclaratorContext::ObjCCatchContext:
2024     case DeclaratorContext::BlockLiteralContext:
2025     case DeclaratorContext::LambdaExprContext:
2026     case DeclaratorContext::ConversionIdContext:
2027     case DeclaratorContext::TemplateArgContext:
2028     case DeclaratorContext::TemplateTypeArgContext:
2029     case DeclaratorContext::TrailingReturnContext:
2030     case DeclaratorContext::TrailingReturnVarContext:
2031       return false;
2032     }
2033     llvm_unreachable("unknown context kind!");
2034   }
2035
2036   /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
2037   /// followed by a C++ direct initializer, e.g. "int x(1);".
2038   bool mayBeFollowedByCXXDirectInit() const {
2039     if (hasGroupingParens()) return false;
2040
2041     if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2042       return false;
2043
2044     if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
2045         Context != DeclaratorContext::FileContext)
2046       return false;
2047
2048     // Special names can't have direct initializers.
2049     if (Name.getKind() != UnqualifiedIdKind::IK_Identifier)
2050       return false;
2051
2052     switch (Context) {
2053     case DeclaratorContext::FileContext:
2054     case DeclaratorContext::BlockContext:
2055     case DeclaratorContext::ForContext:
2056     case DeclaratorContext::InitStmtContext:
2057     case DeclaratorContext::TrailingReturnVarContext:
2058       return true;
2059
2060     case DeclaratorContext::ConditionContext:
2061       // This may not be followed by a direct initializer, but it can't be a
2062       // function declaration either, and we'd prefer to perform a tentative
2063       // parse in order to produce the right diagnostic.
2064       return true;
2065
2066     case DeclaratorContext::KNRTypeListContext:
2067     case DeclaratorContext::MemberContext:
2068     case DeclaratorContext::PrototypeContext:
2069     case DeclaratorContext::LambdaExprParameterContext:
2070     case DeclaratorContext::ObjCParameterContext:
2071     case DeclaratorContext::ObjCResultContext:
2072     case DeclaratorContext::TemplateParamContext:
2073     case DeclaratorContext::CXXCatchContext:
2074     case DeclaratorContext::ObjCCatchContext:
2075     case DeclaratorContext::TypeNameContext:
2076     case DeclaratorContext::FunctionalCastContext: // FIXME
2077     case DeclaratorContext::CXXNewContext:
2078     case DeclaratorContext::AliasDeclContext:
2079     case DeclaratorContext::AliasTemplateContext:
2080     case DeclaratorContext::BlockLiteralContext:
2081     case DeclaratorContext::LambdaExprContext:
2082     case DeclaratorContext::ConversionIdContext:
2083     case DeclaratorContext::TemplateArgContext:
2084     case DeclaratorContext::TemplateTypeArgContext:
2085     case DeclaratorContext::TrailingReturnContext:
2086       return false;
2087     }
2088     llvm_unreachable("unknown context kind!");
2089   }
2090
2091   /// isPastIdentifier - Return true if we have parsed beyond the point where
2092   /// the name would appear. (This may happen even if we haven't actually parsed
2093   /// a name, perhaps because this context doesn't require one.)
2094   bool isPastIdentifier() const { return Name.isValid(); }
2095
2096   /// hasName - Whether this declarator has a name, which might be an
2097   /// identifier (accessible via getIdentifier()) or some kind of
2098   /// special C++ name (constructor, destructor, etc.), or a structured
2099   /// binding (which is not exactly a name, but occupies the same position).
2100   bool hasName() const {
2101     return Name.getKind() != UnqualifiedIdKind::IK_Identifier ||
2102            Name.Identifier || isDecompositionDeclarator();
2103   }
2104
2105   /// Return whether this declarator is a decomposition declarator.
2106   bool isDecompositionDeclarator() const {
2107     return BindingGroup.isSet();
2108   }
2109
2110   IdentifierInfo *getIdentifier() const { 
2111     if (Name.getKind() == UnqualifiedIdKind::IK_Identifier)
2112       return Name.Identifier;
2113     
2114     return nullptr;
2115   }
2116   SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
2117
2118   /// Set the name of this declarator to be the given identifier.
2119   void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
2120     Name.setIdentifier(Id, IdLoc);
2121   }
2122
2123   /// Set the decomposition bindings for this declarator.
2124   void
2125   setDecompositionBindings(SourceLocation LSquareLoc,
2126                            ArrayRef<DecompositionDeclarator::Binding> Bindings,
2127                            SourceLocation RSquareLoc);
2128
2129   /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2130   /// EndLoc, which should be the last token of the chunk.
2131   /// This function takes attrs by R-Value reference because it takes ownership
2132   /// of those attributes from the parameter.
2133   void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs,
2134                    SourceLocation EndLoc) {
2135     DeclTypeInfo.push_back(TI);
2136     DeclTypeInfo.back().getAttrs().addAll(attrs.begin(), attrs.end());
2137     getAttributePool().takeAllFrom(attrs.getPool());
2138
2139     if (!EndLoc.isInvalid())
2140       SetRangeEnd(EndLoc);
2141   }
2142
2143   /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2144   /// EndLoc, which should be the last token of the chunk.
2145   void AddTypeInfo(const DeclaratorChunk &TI, SourceLocation EndLoc) {
2146     DeclTypeInfo.push_back(TI);
2147
2148     if (!EndLoc.isInvalid())
2149       SetRangeEnd(EndLoc);
2150   }
2151
2152   /// Add a new innermost chunk to this declarator.
2153   void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
2154     DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
2155   }
2156
2157   /// Return the number of types applied to this declarator.
2158   unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
2159
2160   /// Return the specified TypeInfo from this declarator.  TypeInfo #0 is
2161   /// closest to the identifier.
2162   const DeclaratorChunk &getTypeObject(unsigned i) const {
2163     assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2164     return DeclTypeInfo[i];
2165   }
2166   DeclaratorChunk &getTypeObject(unsigned i) {
2167     assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2168     return DeclTypeInfo[i];
2169   }
2170
2171   typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
2172   typedef llvm::iterator_range<type_object_iterator> type_object_range;
2173
2174   /// Returns the range of type objects, from the identifier outwards.
2175   type_object_range type_objects() const {
2176     return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
2177   }
2178
2179   void DropFirstTypeObject() {
2180     assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
2181     DeclTypeInfo.front().destroy();
2182     DeclTypeInfo.erase(DeclTypeInfo.begin());
2183   }
2184
2185   /// Return the innermost (closest to the declarator) chunk of this
2186   /// declarator that is not a parens chunk, or null if there are no
2187   /// non-parens chunks.
2188   const DeclaratorChunk *getInnermostNonParenChunk() const {
2189     for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2190       if (!DeclTypeInfo[i].isParen())
2191         return &DeclTypeInfo[i];
2192     }
2193     return nullptr;
2194   }
2195
2196   /// Return the outermost (furthest from the declarator) chunk of
2197   /// this declarator that is not a parens chunk, or null if there are
2198   /// no non-parens chunks.
2199   const DeclaratorChunk *getOutermostNonParenChunk() const {
2200     for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
2201       if (!DeclTypeInfo[i-1].isParen())
2202         return &DeclTypeInfo[i-1];
2203     }
2204     return nullptr;
2205   }
2206
2207   /// isArrayOfUnknownBound - This method returns true if the declarator
2208   /// is a declarator for an array of unknown bound (looking through
2209   /// parentheses).
2210   bool isArrayOfUnknownBound() const {
2211     const DeclaratorChunk *chunk = getInnermostNonParenChunk();
2212     return (chunk && chunk->Kind == DeclaratorChunk::Array &&
2213             !chunk->Arr.NumElts);
2214   }
2215
2216   /// isFunctionDeclarator - This method returns true if the declarator
2217   /// is a function declarator (looking through parentheses).
2218   /// If true is returned, then the reference type parameter idx is
2219   /// assigned with the index of the declaration chunk.
2220   bool isFunctionDeclarator(unsigned& idx) const {
2221     for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2222       switch (DeclTypeInfo[i].Kind) {
2223       case DeclaratorChunk::Function:
2224         idx = i;
2225         return true;
2226       case DeclaratorChunk::Paren:
2227         continue;
2228       case DeclaratorChunk::Pointer:
2229       case DeclaratorChunk::Reference:
2230       case DeclaratorChunk::Array:
2231       case DeclaratorChunk::BlockPointer:
2232       case DeclaratorChunk::MemberPointer:
2233       case DeclaratorChunk::Pipe:
2234         return false;
2235       }
2236       llvm_unreachable("Invalid type chunk");
2237     }
2238     return false;
2239   }
2240
2241   /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
2242   /// this method returns true if the identifier is a function declarator
2243   /// (looking through parentheses).
2244   bool isFunctionDeclarator() const {
2245     unsigned index;
2246     return isFunctionDeclarator(index);
2247   }
2248
2249   /// getFunctionTypeInfo - Retrieves the function type info object
2250   /// (looking through parentheses).
2251   DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
2252     assert(isFunctionDeclarator() && "Not a function declarator!");
2253     unsigned index = 0;
2254     isFunctionDeclarator(index);
2255     return DeclTypeInfo[index].Fun;
2256   }
2257
2258   /// getFunctionTypeInfo - Retrieves the function type info object
2259   /// (looking through parentheses).
2260   const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
2261     return const_cast<Declarator*>(this)->getFunctionTypeInfo();
2262   }
2263
2264   /// Determine whether the declaration that will be produced from 
2265   /// this declaration will be a function.
2266   /// 
2267   /// A declaration can declare a function even if the declarator itself
2268   /// isn't a function declarator, if the type specifier refers to a function
2269   /// type. This routine checks for both cases.
2270   bool isDeclarationOfFunction() const;
2271
2272   /// Return true if this declaration appears in a context where a
2273   /// function declarator would be a function declaration.
2274   bool isFunctionDeclarationContext() const {
2275     if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2276       return false;
2277
2278     switch (Context) {
2279     case DeclaratorContext::FileContext:
2280     case DeclaratorContext::MemberContext:
2281     case DeclaratorContext::BlockContext:
2282     case DeclaratorContext::ForContext:
2283     case DeclaratorContext::InitStmtContext:
2284       return true;
2285
2286     case DeclaratorContext::ConditionContext:
2287     case DeclaratorContext::KNRTypeListContext:
2288     case DeclaratorContext::TypeNameContext:
2289     case DeclaratorContext::FunctionalCastContext:
2290     case DeclaratorContext::AliasDeclContext:
2291     case DeclaratorContext::AliasTemplateContext:
2292     case DeclaratorContext::PrototypeContext:
2293     case DeclaratorContext::LambdaExprParameterContext:
2294     case DeclaratorContext::ObjCParameterContext:
2295     case DeclaratorContext::ObjCResultContext:
2296     case DeclaratorContext::TemplateParamContext:
2297     case DeclaratorContext::CXXNewContext:
2298     case DeclaratorContext::CXXCatchContext:
2299     case DeclaratorContext::ObjCCatchContext:
2300     case DeclaratorContext::BlockLiteralContext:
2301     case DeclaratorContext::LambdaExprContext:
2302     case DeclaratorContext::ConversionIdContext:
2303     case DeclaratorContext::TemplateArgContext:
2304     case DeclaratorContext::TemplateTypeArgContext:
2305     case DeclaratorContext::TrailingReturnContext:
2306     case DeclaratorContext::TrailingReturnVarContext:
2307       return false;
2308     }
2309     llvm_unreachable("unknown context kind!");
2310   }
2311
2312   /// Determine whether this declaration appears in a context where an
2313   /// expression could appear.
2314   bool isExpressionContext() const {
2315     switch (Context) {
2316     case DeclaratorContext::FileContext:
2317     case DeclaratorContext::KNRTypeListContext:
2318     case DeclaratorContext::MemberContext:
2319
2320     // FIXME: sizeof(...) permits an expression.
2321     case DeclaratorContext::TypeNameContext: 
2322     
2323     case DeclaratorContext::FunctionalCastContext:
2324     case DeclaratorContext::AliasDeclContext:
2325     case DeclaratorContext::AliasTemplateContext:
2326     case DeclaratorContext::PrototypeContext:
2327     case DeclaratorContext::LambdaExprParameterContext:
2328     case DeclaratorContext::ObjCParameterContext:
2329     case DeclaratorContext::ObjCResultContext:
2330     case DeclaratorContext::TemplateParamContext:
2331     case DeclaratorContext::CXXNewContext:
2332     case DeclaratorContext::CXXCatchContext:
2333     case DeclaratorContext::ObjCCatchContext:
2334     case DeclaratorContext::BlockLiteralContext:
2335     case DeclaratorContext::LambdaExprContext:
2336     case DeclaratorContext::ConversionIdContext:
2337     case DeclaratorContext::TrailingReturnContext:
2338     case DeclaratorContext::TrailingReturnVarContext:
2339     case DeclaratorContext::TemplateTypeArgContext:
2340       return false;
2341
2342     case DeclaratorContext::BlockContext:
2343     case DeclaratorContext::ForContext:
2344     case DeclaratorContext::InitStmtContext:
2345     case DeclaratorContext::ConditionContext:
2346     case DeclaratorContext::TemplateArgContext:
2347       return true;
2348     }
2349
2350     llvm_unreachable("unknown context kind!");
2351   }
2352   
2353   /// Return true if a function declarator at this position would be a
2354   /// function declaration.
2355   bool isFunctionDeclaratorAFunctionDeclaration() const {
2356     if (!isFunctionDeclarationContext())
2357       return false;
2358
2359     for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2360       if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
2361         return false;
2362
2363     return true;
2364   }
2365
2366   /// Determine whether a trailing return type was written (at any
2367   /// level) within this declarator.
2368   bool hasTrailingReturnType() const {
2369     for (const auto &Chunk : type_objects())
2370       if (Chunk.Kind == DeclaratorChunk::Function &&
2371           Chunk.Fun.hasTrailingReturnType())
2372         return true;
2373     return false;
2374   }
2375
2376   /// takeAttributes - Takes attributes from the given parsed-attributes
2377   /// set and add them to this declarator.
2378   ///
2379   /// These examples both add 3 attributes to "var":
2380   ///  short int var __attribute__((aligned(16),common,deprecated));
2381   ///  short int x, __attribute__((aligned(16)) var
2382   ///                                 __attribute__((common,deprecated));
2383   ///
2384   /// Also extends the range of the declarator.
2385   void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
2386     Attrs.takeAllFrom(attrs);
2387
2388     if (!lastLoc.isInvalid())
2389       SetRangeEnd(lastLoc);
2390   }
2391
2392   const ParsedAttributes &getAttributes() const { return Attrs; }
2393   ParsedAttributes &getAttributes() { return Attrs; }
2394
2395   /// hasAttributes - do we contain any attributes?
2396   bool hasAttributes() const {
2397     if (!getAttributes().empty() || getDeclSpec().hasAttributes())
2398       return true;
2399     for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2400       if (!getTypeObject(i).getAttrs().empty())
2401         return true;
2402     return false;
2403   }
2404
2405   /// Return a source range list of C++11 attributes associated
2406   /// with the declarator.
2407   void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) {
2408     for (const ParsedAttr &AL : Attrs)
2409       if (AL.isCXX11Attribute())
2410         Ranges.push_back(AL.getRange());
2411   }
2412
2413   void setAsmLabel(Expr *E) { AsmLabel = E; }
2414   Expr *getAsmLabel() const { return AsmLabel; }
2415
2416   void setExtension(bool Val = true) { Extension = Val; }
2417   bool getExtension() const { return Extension; }
2418
2419   void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
2420   bool isObjCIvar() const { return ObjCIvar; }
2421     
2422   void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
2423   bool isObjCWeakProperty() const { return ObjCWeakProperty; }
2424
2425   void setInvalidType(bool Val = true) { InvalidType = Val; }
2426   bool isInvalidType() const {
2427     return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
2428   }
2429
2430   void setGroupingParens(bool flag) { GroupingParens = flag; }
2431   bool hasGroupingParens() const { return GroupingParens; }
2432
2433   bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
2434   SourceLocation getCommaLoc() const { return CommaLoc; }
2435   void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2436
2437   bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2438   SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2439   void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2440
2441   void setFunctionDefinitionKind(FunctionDefinitionKind Val) { 
2442     FunctionDefinition = Val; 
2443   }
2444   
2445   bool isFunctionDefinition() const {
2446     return getFunctionDefinitionKind() != FDK_Declaration;
2447   }
2448   
2449   FunctionDefinitionKind getFunctionDefinitionKind() const { 
2450     return (FunctionDefinitionKind)FunctionDefinition; 
2451   }
2452
2453   /// Returns true if this declares a real member and not a friend.
2454   bool isFirstDeclarationOfMember() {
2455     return getContext() == DeclaratorContext::MemberContext &&
2456            !getDeclSpec().isFriendSpecified();
2457   }
2458
2459   /// Returns true if this declares a static member.  This cannot be called on a
2460   /// declarator outside of a MemberContext because we won't know until
2461   /// redeclaration time if the decl is static.
2462   bool isStaticMember();
2463
2464   /// Returns true if this declares a constructor or a destructor.
2465   bool isCtorOrDtor();
2466
2467   void setRedeclaration(bool Val) { Redeclaration = Val; }
2468   bool isRedeclaration() const { return Redeclaration; }
2469 };
2470
2471 /// This little struct is used to capture information about
2472 /// structure field declarators, which is basically just a bitfield size.
2473 struct FieldDeclarator {
2474   Declarator D;
2475   Expr *BitfieldSize;
2476   explicit FieldDeclarator(const DeclSpec &DS)
2477       : D(DS, DeclaratorContext::MemberContext),
2478         BitfieldSize(nullptr) {}
2479 };
2480
2481 /// Represents a C++11 virt-specifier-seq.
2482 class VirtSpecifiers {
2483 public:
2484   enum Specifier {
2485     VS_None = 0,
2486     VS_Override = 1,
2487     VS_Final = 2,
2488     VS_Sealed = 4,
2489     // Represents the __final keyword, which is legal for gcc in pre-C++11 mode.
2490     VS_GNU_Final = 8
2491   };
2492
2493   VirtSpecifiers() : Specifiers(0), LastSpecifier(VS_None) { }
2494
2495   bool SetSpecifier(Specifier VS, SourceLocation Loc,
2496                     const char *&PrevSpec);
2497
2498   bool isUnset() const { return Specifiers == 0; }
2499
2500   bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2501   SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2502
2503   bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); }
2504   bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
2505   SourceLocation getFinalLoc() const { return VS_finalLoc; }
2506
2507   void clear() { Specifiers = 0; }
2508
2509   static const char *getSpecifierName(Specifier VS);
2510
2511   SourceLocation getFirstLocation() const { return FirstLocation; }
2512   SourceLocation getLastLocation() const { return LastLocation; }
2513   Specifier getLastSpecifier() const { return LastSpecifier; }
2514   
2515 private:
2516   unsigned Specifiers;
2517   Specifier LastSpecifier;
2518
2519   SourceLocation VS_overrideLoc, VS_finalLoc;
2520   SourceLocation FirstLocation;
2521   SourceLocation LastLocation;
2522 };
2523
2524 enum class LambdaCaptureInitKind {
2525   NoInit,     //!< [a]
2526   CopyInit,   //!< [a = b], [a = {b}]
2527   DirectInit, //!< [a(b)]
2528   ListInit    //!< [a{b}]
2529 };
2530
2531 /// Represents a complete lambda introducer.
2532 struct LambdaIntroducer {
2533   /// An individual capture in a lambda introducer.
2534   struct LambdaCapture {
2535     LambdaCaptureKind Kind;
2536     SourceLocation Loc;
2537     IdentifierInfo *Id;
2538     SourceLocation EllipsisLoc;
2539     LambdaCaptureInitKind InitKind;
2540     ExprResult Init;
2541     ParsedType InitCaptureType;
2542     SourceRange ExplicitRange;
2543
2544     LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2545                   IdentifierInfo *Id, SourceLocation EllipsisLoc,
2546                   LambdaCaptureInitKind InitKind, ExprResult Init,
2547                   ParsedType InitCaptureType,
2548                   SourceRange ExplicitRange)
2549         : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
2550           InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType),
2551           ExplicitRange(ExplicitRange) {}
2552   };
2553
2554   SourceRange Range;
2555   SourceLocation DefaultLoc;
2556   LambdaCaptureDefault Default;
2557   SmallVector<LambdaCapture, 4> Captures;
2558
2559   LambdaIntroducer()
2560     : Default(LCD_None) {}
2561
2562   /// Append a capture in a lambda introducer.
2563   void addCapture(LambdaCaptureKind Kind,
2564                   SourceLocation Loc,
2565                   IdentifierInfo* Id,
2566                   SourceLocation EllipsisLoc,
2567                   LambdaCaptureInitKind InitKind,
2568                   ExprResult Init, 
2569                   ParsedType InitCaptureType,
2570                   SourceRange ExplicitRange) {
2571     Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
2572                                      InitCaptureType, ExplicitRange));
2573   }
2574 };
2575
2576 } // end namespace clang
2577
2578 #endif // LLVM_CLANG_SEMA_DECLSPEC_H