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