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