1 //===------------------------- ItaniumDemangle.cpp ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // FIXME: (possibly) incomplete list of features that clang mangles that this
11 // file does not yet support:
12 //   - enable_if attribute
13 //   - C++ modules TS
14 //   - All C++14 and C++17 features
15 
16 #include "llvm/Demangle/Demangle.h"
17 
18 #include "llvm/Demangle/Compiler.h"
19 
20 #include <algorithm>
21 #include <cassert>
22 #include <cctype>
23 #include <cstdio>
24 #include <cstdlib>
25 #include <cstring>
26 #include <numeric>
27 #include <vector>
28 
29 #ifdef _MSC_VER
30 // snprintf is implemented in VS 2015
31 #if _MSC_VER < 1900
32 #define snprintf _snprintf_s
33 #endif
34 #endif
35 
36 namespace {
37 
38 class StringView {
39   const char *First;
40   const char *Last;
41 
42 public:
43   template <size_t N>
44   StringView(const char (&Str)[N]) : First(Str), Last(Str + N - 1) {}
45   StringView(const char *First_, const char *Last_) : First(First_), Last(Last_) {}
46   StringView() : First(nullptr), Last(nullptr) {}
47 
48   StringView substr(size_t From, size_t To) {
49     if (To >= size())
50       To = size() - 1;
51     if (From >= size())
52       From = size() - 1;
53     return StringView(First + From, First + To);
54   }
55 
56   StringView dropFront(size_t N) const {
57     if (N >= size())
58       N = size() - 1;
59     return StringView(First + N, Last);
60   }
61 
62   bool startsWith(StringView Str) const {
63     if (Str.size() > size())
64       return false;
65     return std::equal(Str.begin(), Str.end(), begin());
66   }
67 
68   const char &operator[](size_t Idx) const { return *(begin() + Idx); }
69 
70   const char *begin() const { return First; }
71   const char *end() const { return Last; }
72   size_t size() const { return static_cast<size_t>(Last - First); }
73   bool empty() const { return First == Last; }
74 };
75 
76 bool operator==(const StringView &LHS, const StringView &RHS) {
77   return LHS.size() == RHS.size() &&
78          std::equal(LHS.begin(), LHS.end(), RHS.begin());
79 }
80 
81 // Stream that AST nodes write their string representation into after the AST
82 // has been parsed.
83 class OutputStream {
84   char *Buffer;
85   size_t CurrentPosition;
86   size_t BufferCapacity;
87 
88   // Ensure there is at least n more positions in buffer.
89   void grow(size_t N) {
90     if (N + CurrentPosition >= BufferCapacity) {
91       BufferCapacity *= 2;
92       if (BufferCapacity < N + CurrentPosition)
93         BufferCapacity = N + CurrentPosition;
94       Buffer = static_cast<char *>(std::realloc(Buffer, BufferCapacity));
95     }
96   }
97 
98 public:
99   OutputStream(char *StartBuf, size_t Size)
100       : Buffer(StartBuf), CurrentPosition(0), BufferCapacity(Size) {}
101 
102   /// If a ParameterPackExpansion (or similar type) is encountered, the offset
103   /// into the pack that we're currently printing.
104   unsigned CurrentPackIndex = std::numeric_limits<unsigned>::max();
105 
106   OutputStream &operator+=(StringView R) {
107     size_t Size = R.size();
108     if (Size == 0)
109       return *this;
110     grow(Size);
111     memmove(Buffer + CurrentPosition, R.begin(), Size);
112     CurrentPosition += Size;
113     return *this;
114   }
115 
116   OutputStream &operator+=(char C) {
117     grow(1);
118     Buffer[CurrentPosition++] = C;
119     return *this;
120   }
121 
122   size_t getCurrentPosition() const { return CurrentPosition; };
123 
124   char back() const {
125     return CurrentPosition ? Buffer[CurrentPosition - 1] : '\0';
126   }
127 
128   bool empty() const { return CurrentPosition == 0; }
129 
130   char *getBuffer() { return Buffer; }
131   char *getBufferEnd() { return Buffer + CurrentPosition - 1; }
132   size_t getBufferCapacity() { return BufferCapacity; }
133 };
134 
135 template <class T>
136 class SwapAndRestore {
137   T &Restore;
138   T OriginalValue;
139 public:
140   SwapAndRestore(T& Restore_, T NewVal)
141       : Restore(Restore_), OriginalValue(Restore) {
142     Restore = std::move(NewVal);
143   }
144   ~SwapAndRestore() { Restore = std::move(OriginalValue); }
145 
146   SwapAndRestore(const SwapAndRestore &) = delete;
147   SwapAndRestore &operator=(const SwapAndRestore &) = delete;
148 };
149 
150 // Base class of all AST nodes. The AST is built by the parser, then is
151 // traversed by the printLeft/Right functions to produce a demangled string.
152 class Node {
153 public:
154   enum Kind : unsigned char {
155     KDotSuffix,
156     KVendorExtQualType,
157     KQualType,
158     KConversionOperatorType,
159     KPostfixQualifiedType,
160     KElaboratedTypeSpefType,
161     KNameType,
162     KAbiTagAttr,
163     KObjCProtoName,
164     KPointerType,
165     KLValueReferenceType,
166     KRValueReferenceType,
167     KPointerToMemberType,
168     KArrayType,
169     KFunctionType,
170     KNoexceptSpec,
171     KDynamicExceptionSpec,
172     KFunctionEncoding,
173     KLiteralOperator,
174     KSpecialName,
175     KCtorVtableSpecialName,
176     KQualifiedName,
177     KEmptyName,
178     KVectorType,
179     KParameterPack,
180     KTemplateArgumentPack,
181     KParameterPackExpansion,
182     KTemplateArgs,
183     KNameWithTemplateArgs,
184     KGlobalQualifiedName,
185     KStdQualifiedName,
186     KExpandedSpecialSubstitution,
187     KSpecialSubstitution,
188     KCtorDtorName,
189     KDtorName,
190     KUnnamedTypeName,
191     KClosureTypeName,
192     KStructuredBindingName,
193     KExpr,
194     KBracedExpr,
195     KBracedRangeExpr,
196   };
197 
198   static constexpr unsigned NoParameterPack =
199     std::numeric_limits<unsigned>::max();
200   unsigned ParameterPackSize = NoParameterPack;
201 
202   Kind K;
203 
204   /// Three-way bool to track a cached value. Unknown is possible if this node
205   /// has an unexpanded parameter pack below it that may affect this cache.
206   enum class Cache : unsigned char { Yes, No, Unknown, };
207 
208   /// Tracks if this node has a component on its right side, in which case we
209   /// need to call printRight.
210   Cache RHSComponentCache;
211 
212   /// Track if this node is a (possibly qualified) array type. This can affect
213   /// how we format the output string.
214   Cache ArrayCache;
215 
216   /// Track if this node is a (possibly qualified) function type. This can
217   /// affect how we format the output string.
218   Cache FunctionCache;
219 
220   Node(Kind K_, unsigned ParameterPackSize_ = NoParameterPack,
221        Cache RHSComponentCache_ = Cache::No, Cache ArrayCache_ = Cache::No,
222        Cache FunctionCache_ = Cache::No)
223       : ParameterPackSize(ParameterPackSize_), K(K_),
224         RHSComponentCache(RHSComponentCache_), ArrayCache(ArrayCache_),
225         FunctionCache(FunctionCache_) {}
226 
227   bool containsUnexpandedParameterPack() const {
228     return ParameterPackSize != NoParameterPack;
229   }
230 
231   bool hasRHSComponent(OutputStream &S) const {
232     if (RHSComponentCache != Cache::Unknown)
233       return RHSComponentCache == Cache::Yes;
234     return hasRHSComponentSlow(S);
235   }
236 
237   bool hasArray(OutputStream &S) const {
238     if (ArrayCache != Cache::Unknown)
239       return ArrayCache == Cache::Yes;
240     return hasArraySlow(S);
241   }
242 
243   bool hasFunction(OutputStream &S) const {
244     if (FunctionCache != Cache::Unknown)
245       return FunctionCache == Cache::Yes;
246     return hasFunctionSlow(S);
247   }
248 
249   Kind getKind() const { return K; }
250 
251   virtual bool hasRHSComponentSlow(OutputStream &) const { return false; }
252   virtual bool hasArraySlow(OutputStream &) const { return false; }
253   virtual bool hasFunctionSlow(OutputStream &) const { return false; }
254 
255   /// If this node is a pack expansion that expands to 0 elements. This can have
256   /// an effect on how we should format the output.
257   bool isEmptyPackExpansion() const;
258 
259   void print(OutputStream &S) const {
260     printLeft(S);
261     if (RHSComponentCache != Cache::No)
262       printRight(S);
263   }
264 
265   // Print the "left" side of this Node into OutputStream.
266   virtual void printLeft(OutputStream &) const = 0;
267 
268   // Print the "right". This distinction is necessary to represent C++ types
269   // that appear on the RHS of their subtype, such as arrays or functions.
270   // Since most types don't have such a component, provide a default
271   // implemenation.
272   virtual void printRight(OutputStream &) const {}
273 
274   virtual StringView getBaseName() const { return StringView(); }
275 
276   // Silence compiler warnings, this dtor will never be called.
277   virtual ~Node() = default;
278 
279 #ifndef NDEBUG
280   LLVM_DUMP_METHOD void dump() const {
281     char *Buffer = static_cast<char*>(std::malloc(1024));
282     OutputStream S(Buffer, 1024);
283     print(S);
284     S += '\0';
285     printf("Symbol dump for %p: %s\n", (const void*)this, S.getBuffer());
286     std::free(S.getBuffer());
287   }
288 #endif
289 };
290 
291 class NodeArray {
292   Node **Elements;
293   size_t NumElements;
294 
295 public:
296   NodeArray() : Elements(nullptr), NumElements(0) {}
297   NodeArray(Node **Elements_, size_t NumElements_)
298       : Elements(Elements_), NumElements(NumElements_) {}
299 
300   bool empty() const { return NumElements == 0; }
301   size_t size() const { return NumElements; }
302 
303   Node **begin() const { return Elements; }
304   Node **end() const { return Elements + NumElements; }
305 
306   Node *operator[](size_t Idx) const { return Elements[Idx]; }
307 
308   void printWithComma(OutputStream &S) const {
309     bool FirstElement = true;
310     for (size_t Idx = 0; Idx != NumElements; ++Idx) {
311       if (Elements[Idx]->isEmptyPackExpansion())
312         continue;
313       if (!FirstElement)
314         S += ", ";
315       FirstElement = false;
316       Elements[Idx]->print(S);
317     }
318   }
319 };
320 
321 class DotSuffix final : public Node {
322   const Node *Prefix;
323   const StringView Suffix;
324 
325 public:
326   DotSuffix(Node *Prefix_, StringView Suffix_)
327       : Node(KDotSuffix), Prefix(Prefix_), Suffix(Suffix_) {}
328 
329   void printLeft(OutputStream &s) const override {
330     Prefix->print(s);
331     s += " (";
332     s += Suffix;
333     s += ")";
334   }
335 };
336 
337 class VendorExtQualType final : public Node {
338   const Node *Ty;
339   StringView Ext;
340 
341 public:
342   VendorExtQualType(Node *Ty_, StringView Ext_)
343       : Node(KVendorExtQualType, Ty_->ParameterPackSize),
344         Ty(Ty_), Ext(Ext_) {}
345 
346   void printLeft(OutputStream &S) const override {
347     Ty->print(S);
348     S += " ";
349     S += Ext;
350   }
351 };
352 
353 enum FunctionRefQual : unsigned char {
354   FrefQualNone,
355   FrefQualLValue,
356   FrefQualRValue,
357 };
358 
359 enum Qualifiers {
360   QualNone = 0,
361   QualConst = 0x1,
362   QualVolatile = 0x2,
363   QualRestrict = 0x4,
364 };
365 
366 void addQualifiers(Qualifiers &Q1, Qualifiers Q2) {
367   Q1 = static_cast<Qualifiers>(Q1 | Q2);
368 }
369 
370 class QualType : public Node {
371 protected:
372   const Qualifiers Quals;
373   const Node *Child;
374 
375   void printQuals(OutputStream &S) const {
376     if (Quals & QualConst)
377       S += " const";
378     if (Quals & QualVolatile)
379       S += " volatile";
380     if (Quals & QualRestrict)
381       S += " restrict";
382   }
383 
384 public:
385   QualType(Node *Child_, Qualifiers Quals_)
386       : Node(KQualType, Child_->ParameterPackSize, Child_->RHSComponentCache,
387              Child_->ArrayCache, Child_->FunctionCache),
388         Quals(Quals_), Child(Child_) {}
389 
390   bool hasRHSComponentSlow(OutputStream &S) const override {
391     return Child->hasRHSComponent(S);
392   }
393   bool hasArraySlow(OutputStream &S) const override {
394     return Child->hasArray(S);
395   }
396   bool hasFunctionSlow(OutputStream &S) const override {
397     return Child->hasFunction(S);
398   }
399 
400   void printLeft(OutputStream &S) const override {
401     Child->printLeft(S);
402     printQuals(S);
403   }
404 
405   void printRight(OutputStream &S) const override { Child->printRight(S); }
406 };
407 
408 class ConversionOperatorType final : public Node {
409   const Node *Ty;
410 
411 public:
412   ConversionOperatorType(Node *Ty_)
413       : Node(KConversionOperatorType, Ty_->ParameterPackSize), Ty(Ty_) {}
414 
415   void printLeft(OutputStream &S) const override {
416     S += "operator ";
417     Ty->print(S);
418   }
419 };
420 
421 class PostfixQualifiedType final : public Node {
422   const Node *Ty;
423   const StringView Postfix;
424 
425 public:
426   PostfixQualifiedType(Node *Ty_, StringView Postfix_)
427       : Node(KPostfixQualifiedType, Ty_->ParameterPackSize),
428         Ty(Ty_), Postfix(Postfix_) {}
429 
430   void printLeft(OutputStream &s) const override {
431     Ty->printLeft(s);
432     s += Postfix;
433   }
434 };
435 
436 class NameType final : public Node {
437   const StringView Name;
438 
439 public:
440   NameType(StringView Name_) : Node(KNameType), Name(Name_) {}
441 
442   StringView getName() const { return Name; }
443   StringView getBaseName() const override { return Name; }
444 
445   void printLeft(OutputStream &s) const override { s += Name; }
446 };
447 
448 class ElaboratedTypeSpefType : public Node {
449   StringView Kind;
450   Node *Child;
451 public:
452   ElaboratedTypeSpefType(StringView Kind_, Node *Child_)
453       : Node(KElaboratedTypeSpefType), Kind(Kind_), Child(Child_) {
454     ParameterPackSize = Child->ParameterPackSize;
455   }
456 
457   void printLeft(OutputStream &S) const override {
458     S += Kind;
459     S += ' ';
460     Child->print(S);
461   }
462 };
463 
464 class AbiTagAttr final : public Node {
465   const Node* Base;
466   StringView Tag;
467 public:
468   AbiTagAttr(const Node* Base_, StringView Tag_)
469       : Node(KAbiTagAttr, Base_->ParameterPackSize, Base_->RHSComponentCache,
470              Base_->ArrayCache, Base_->FunctionCache),
471         Base(Base_), Tag(Tag_) {}
472 
473   void printLeft(OutputStream &S) const override {
474     Base->printLeft(S);
475     S += "[abi:";
476     S += Tag;
477     S += "]";
478   }
479 };
480 
481 class ObjCProtoName : public Node {
482   Node *Ty;
483   StringView Protocol;
484 
485   friend class PointerType;
486 
487 public:
488   ObjCProtoName(Node *Ty_, StringView Protocol_)
489       : Node(KObjCProtoName), Ty(Ty_), Protocol(Protocol_) {}
490 
491   bool isObjCObject() const {
492     return Ty->getKind() == KNameType &&
493            static_cast<NameType *>(Ty)->getName() == "objc_object";
494   }
495 
496   void printLeft(OutputStream &S) const override {
497     Ty->print(S);
498     S += "<";
499     S += Protocol;
500     S += ">";
501   }
502 };
503 
504 class PointerType final : public Node {
505   const Node *Pointee;
506 
507 public:
508   PointerType(Node *Pointee_)
509       : Node(KPointerType, Pointee_->ParameterPackSize,
510              Pointee_->RHSComponentCache),
511         Pointee(Pointee_) {}
512 
513   bool hasRHSComponentSlow(OutputStream &S) const override {
514     return Pointee->hasRHSComponent(S);
515   }
516 
517   void printLeft(OutputStream &s) const override {
518     // We rewrite objc_object<SomeProtocol>* into id<SomeProtocol>.
519     if (Pointee->getKind() != KObjCProtoName ||
520         !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
521       Pointee->printLeft(s);
522       if (Pointee->hasArray(s))
523         s += " ";
524       if (Pointee->hasArray(s) || Pointee->hasFunction(s))
525         s += "(";
526       s += "*";
527     } else {
528       const auto *objcProto = static_cast<const ObjCProtoName *>(Pointee);
529       s += "id<";
530       s += objcProto->Protocol;
531       s += ">";
532     }
533   }
534 
535   void printRight(OutputStream &s) const override {
536     if (Pointee->getKind() != KObjCProtoName ||
537         !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
538       if (Pointee->hasArray(s) || Pointee->hasFunction(s))
539         s += ")";
540       Pointee->printRight(s);
541     }
542   }
543 };
544 
545 class LValueReferenceType final : public Node {
546   const Node *Pointee;
547 
548 public:
549   LValueReferenceType(Node *Pointee_)
550       : Node(KLValueReferenceType, Pointee_->ParameterPackSize,
551              Pointee_->RHSComponentCache),
552         Pointee(Pointee_) {}
553 
554   bool hasRHSComponentSlow(OutputStream &S) const override {
555     return Pointee->hasRHSComponent(S);
556   }
557 
558   void printLeft(OutputStream &s) const override {
559     Pointee->printLeft(s);
560     if (Pointee->hasArray(s))
561       s += " ";
562     if (Pointee->hasArray(s) || Pointee->hasFunction(s))
563       s += "(&";
564     else
565       s += "&";
566   }
567   void printRight(OutputStream &s) const override {
568     if (Pointee->hasArray(s) || Pointee->hasFunction(s))
569       s += ")";
570     Pointee->printRight(s);
571   }
572 };
573 
574 class RValueReferenceType final : public Node {
575   const Node *Pointee;
576 
577 public:
578   RValueReferenceType(Node *Pointee_)
579       : Node(KRValueReferenceType, Pointee_->ParameterPackSize,
580              Pointee_->RHSComponentCache),
581         Pointee(Pointee_) {}
582 
583   bool hasRHSComponentSlow(OutputStream &S) const override {
584     return Pointee->hasRHSComponent(S);
585   }
586 
587   void printLeft(OutputStream &s) const override {
588     Pointee->printLeft(s);
589     if (Pointee->hasArray(s))
590       s += " ";
591     if (Pointee->hasArray(s) || Pointee->hasFunction(s))
592       s += "(&&";
593     else
594       s += "&&";
595   }
596 
597   void printRight(OutputStream &s) const override {
598     if (Pointee->hasArray(s) || Pointee->hasFunction(s))
599       s += ")";
600     Pointee->printRight(s);
601   }
602 };
603 
604 class PointerToMemberType final : public Node {
605   const Node *ClassType;
606   const Node *MemberType;
607 
608 public:
609   PointerToMemberType(Node *ClassType_, Node *MemberType_)
610       : Node(KPointerToMemberType,
611              std::min(MemberType_->ParameterPackSize,
612                       ClassType_->ParameterPackSize),
613              MemberType_->RHSComponentCache),
614         ClassType(ClassType_), MemberType(MemberType_) {}
615 
616   bool hasRHSComponentSlow(OutputStream &S) const override {
617     return MemberType->hasRHSComponent(S);
618   }
619 
620   void printLeft(OutputStream &s) const override {
621     MemberType->printLeft(s);
622     if (MemberType->hasArray(s) || MemberType->hasFunction(s))
623       s += "(";
624     else
625       s += " ";
626     ClassType->print(s);
627     s += "::*";
628   }
629 
630   void printRight(OutputStream &s) const override {
631     if (MemberType->hasArray(s) || MemberType->hasFunction(s))
632       s += ")";
633     MemberType->printRight(s);
634   }
635 };
636 
637 class NodeOrString {
638   const void *First;
639   const void *Second;
640 
641 public:
642   /* implicit */ NodeOrString(StringView Str) {
643     const char *FirstChar = Str.begin();
644     const char *SecondChar = Str.end();
645     if (SecondChar == nullptr) {
646       assert(FirstChar == SecondChar);
647       ++FirstChar, ++SecondChar;
648     }
649     First = static_cast<const void *>(FirstChar);
650     Second = static_cast<const void *>(SecondChar);
651   }
652 
653   /* implicit */ NodeOrString(Node *N)
654       : First(static_cast<const void *>(N)), Second(nullptr) {}
655   NodeOrString() : First(nullptr), Second(nullptr) {}
656 
657   bool isString() const { return Second && First; }
658   bool isNode() const { return First && !Second; }
659   bool isEmpty() const { return !First && !Second; }
660 
661   StringView asString() const {
662     assert(isString());
663     return StringView(static_cast<const char *>(First),
664                       static_cast<const char *>(Second));
665   }
666 
667   const Node *asNode() const {
668     assert(isNode());
669     return static_cast<const Node *>(First);
670   }
671 };
672 
673 class ArrayType final : public Node {
674   Node *Base;
675   NodeOrString Dimension;
676 
677 public:
678   ArrayType(Node *Base_, NodeOrString Dimension_)
679       : Node(KArrayType, Base_->ParameterPackSize,
680              /*RHSComponentCache=*/Cache::Yes,
681              /*ArrayCache=*/Cache::Yes),
682         Base(Base_), Dimension(Dimension_) {
683     if (Dimension.isNode())
684       ParameterPackSize =
685           std::min(ParameterPackSize, Dimension.asNode()->ParameterPackSize);
686   }
687 
688   // Incomplete array type.
689   ArrayType(Node *Base_)
690       : Node(KArrayType, Base_->ParameterPackSize,
691              /*RHSComponentCache=*/Cache::Yes,
692              /*ArrayCache=*/Cache::Yes),
693         Base(Base_) {}
694 
695   bool hasRHSComponentSlow(OutputStream &) const override { return true; }
696   bool hasArraySlow(OutputStream &) const override { return true; }
697 
698   void printLeft(OutputStream &S) const override { Base->printLeft(S); }
699 
700   void printRight(OutputStream &S) const override {
701     if (S.back() != ']')
702       S += " ";
703     S += "[";
704     if (Dimension.isString())
705       S += Dimension.asString();
706     else if (Dimension.isNode())
707       Dimension.asNode()->print(S);
708     S += "]";
709     Base->printRight(S);
710   }
711 };
712 
713 class FunctionType final : public Node {
714   Node *Ret;
715   NodeArray Params;
716   Qualifiers CVQuals;
717   FunctionRefQual RefQual;
718   Node *ExceptionSpec;
719 
720 public:
721   FunctionType(Node *Ret_, NodeArray Params_, Qualifiers CVQuals_,
722                FunctionRefQual RefQual_, Node *ExceptionSpec_)
723       : Node(KFunctionType, Ret_->ParameterPackSize,
724              /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
725              /*FunctionCache=*/Cache::Yes),
726         Ret(Ret_), Params(Params_), CVQuals(CVQuals_), RefQual(RefQual_),
727         ExceptionSpec(ExceptionSpec_) {
728     for (Node *P : Params)
729       ParameterPackSize = std::min(ParameterPackSize, P->ParameterPackSize);
730     if (ExceptionSpec != nullptr)
731       ParameterPackSize =
732         std::min(ParameterPackSize, ExceptionSpec->ParameterPackSize);
733   }
734 
735   bool hasRHSComponentSlow(OutputStream &) const override { return true; }
736   bool hasFunctionSlow(OutputStream &) const override { return true; }
737 
738   // Handle C++'s ... quirky decl grammer by using the left & right
739   // distinction. Consider:
740   //   int (*f(float))(char) {}
741   // f is a function that takes a float and returns a pointer to a function
742   // that takes a char and returns an int. If we're trying to print f, start
743   // by printing out the return types's left, then print our parameters, then
744   // finally print right of the return type.
745   void printLeft(OutputStream &S) const override {
746     Ret->printLeft(S);
747     S += " ";
748   }
749 
750   void printRight(OutputStream &S) const override {
751     S += "(";
752     Params.printWithComma(S);
753     S += ")";
754     Ret->printRight(S);
755 
756     if (CVQuals & QualConst)
757       S += " const";
758     if (CVQuals & QualVolatile)
759       S += " volatile";
760     if (CVQuals & QualRestrict)
761       S += " restrict";
762 
763     if (RefQual == FrefQualLValue)
764       S += " &";
765     else if (RefQual == FrefQualRValue)
766       S += " &&";
767 
768     if (ExceptionSpec != nullptr) {
769       S += ' ';
770       ExceptionSpec->print(S);
771     }
772   }
773 };
774 
775 class NoexceptSpec : public Node {
776   Node *E;
777 public:
778   NoexceptSpec(Node *E_) : Node(KNoexceptSpec, E_->ParameterPackSize), E(E_) {}
779 
780   void printLeft(OutputStream &S) const override {
781     S += "noexcept(";
782     E->print(S);
783     S += ")";
784   }
785 };
786 
787 class DynamicExceptionSpec : public Node {
788   NodeArray Types;
789 public:
790   DynamicExceptionSpec(NodeArray Types_)
791       : Node(KDynamicExceptionSpec), Types(Types_) {
792     for (Node *T : Types)
793       ParameterPackSize = std::min(ParameterPackSize, T->ParameterPackSize);
794   }
795 
796   void printLeft(OutputStream &S) const override {
797     S += "throw(";
798     Types.printWithComma(S);
799     S += ')';
800   }
801 };
802 
803 class FunctionEncoding final : public Node {
804   const Node *Ret;
805   const Node *Name;
806   NodeArray Params;
807   Qualifiers CVQuals;
808   FunctionRefQual RefQual;
809 
810 public:
811   FunctionEncoding(Node *Ret_, Node *Name_, NodeArray Params_,
812                    Qualifiers CVQuals_, FunctionRefQual RefQual_)
813       : Node(KFunctionEncoding, NoParameterPack,
814              /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
815              /*FunctionCache=*/Cache::Yes),
816         Ret(Ret_), Name(Name_), Params(Params_), CVQuals(CVQuals_),
817         RefQual(RefQual_) {
818     for (Node *P : Params)
819       ParameterPackSize = std::min(ParameterPackSize, P->ParameterPackSize);
820     if (Ret)
821       ParameterPackSize = std::min(ParameterPackSize, Ret->ParameterPackSize);
822   }
823 
824   bool hasRHSComponentSlow(OutputStream &) const override { return true; }
825   bool hasFunctionSlow(OutputStream &) const override { return true; }
826 
827   Node *getName() { return const_cast<Node *>(Name); }
828 
829   void printLeft(OutputStream &S) const override {
830     if (Ret) {
831       Ret->printLeft(S);
832       if (!Ret->hasRHSComponent(S))
833         S += " ";
834     }
835     Name->print(S);
836   }
837 
838   void printRight(OutputStream &S) const override {
839     S += "(";
840     Params.printWithComma(S);
841     S += ")";
842     if (Ret)
843       Ret->printRight(S);
844 
845     if (CVQuals & QualConst)
846       S += " const";
847     if (CVQuals & QualVolatile)
848       S += " volatile";
849     if (CVQuals & QualRestrict)
850       S += " restrict";
851 
852     if (RefQual == FrefQualLValue)
853       S += " &";
854     else if (RefQual == FrefQualRValue)
855       S += " &&";
856   }
857 };
858 
859 class LiteralOperator : public Node {
860   const Node *OpName;
861 
862 public:
863   LiteralOperator(Node *OpName_)
864       : Node(KLiteralOperator, OpName_->ParameterPackSize), OpName(OpName_) {}
865 
866   void printLeft(OutputStream &S) const override {
867     S += "operator\"\" ";
868     OpName->print(S);
869   }
870 };
871 
872 class SpecialName final : public Node {
873   const StringView Special;
874   const Node *Child;
875 
876 public:
877   SpecialName(StringView Special_, Node* Child_)
878       : Node(KSpecialName, Child_->ParameterPackSize), Special(Special_),
879         Child(Child_) {}
880 
881   void printLeft(OutputStream &S) const override {
882     S += Special;
883     Child->print(S);
884   }
885 };
886 
887 class CtorVtableSpecialName final : public Node {
888   const Node *FirstType;
889   const Node *SecondType;
890 
891 public:
892   CtorVtableSpecialName(Node *FirstType_, Node *SecondType_)
893       : Node(KCtorVtableSpecialName, std::min(FirstType_->ParameterPackSize,
894                                               SecondType_->ParameterPackSize)),
895         FirstType(FirstType_), SecondType(SecondType_) {}
896 
897   void printLeft(OutputStream &S) const override {
898     S += "construction vtable for ";
899     FirstType->print(S);
900     S += "-in-";
901     SecondType->print(S);
902   }
903 };
904 
905 class QualifiedName final : public Node {
906   // qualifier::name
907   const Node *Qualifier;
908   const Node *Name;
909 
910 public:
911   QualifiedName(Node* Qualifier_, Node* Name_)
912       : Node(KQualifiedName,
913              std::min(Qualifier_->ParameterPackSize, Name_->ParameterPackSize)),
914         Qualifier(Qualifier_), Name(Name_) {}
915 
916   StringView getBaseName() const override { return Name->getBaseName(); }
917 
918   void printLeft(OutputStream &S) const override {
919     Qualifier->print(S);
920     S += "::";
921     Name->print(S);
922   }
923 };
924 
925 class EmptyName : public Node {
926 public:
927   EmptyName() : Node(KEmptyName) {}
928   void printLeft(OutputStream &) const override {}
929 };
930 
931 class VectorType final : public Node {
932   const Node *BaseType;
933   const NodeOrString Dimension;
934   const bool IsPixel;
935 
936 public:
937   VectorType(NodeOrString Dimension_)
938       : Node(KVectorType), BaseType(nullptr), Dimension(Dimension_),
939         IsPixel(true) {
940     if (Dimension.isNode())
941       ParameterPackSize = Dimension.asNode()->ParameterPackSize;
942   }
943   VectorType(Node *BaseType_, NodeOrString Dimension_)
944       : Node(KVectorType, BaseType_->ParameterPackSize), BaseType(BaseType_),
945         Dimension(Dimension_), IsPixel(false) {
946     if (Dimension.isNode())
947       ParameterPackSize =
948           std::min(ParameterPackSize, Dimension.asNode()->ParameterPackSize);
949   }
950 
951   void printLeft(OutputStream &S) const override {
952     if (IsPixel) {
953       S += "pixel vector[";
954       S += Dimension.asString();
955       S += "]";
956     } else {
957       BaseType->print(S);
958       S += " vector[";
959       if (Dimension.isNode())
960         Dimension.asNode()->print(S);
961       else if (Dimension.isString())
962         S += Dimension.asString();
963       S += "]";
964     }
965   }
966 };
967 
968 /// An unexpanded parameter pack (either in the expression or type context). If
969 /// this AST is correct, this node will have a ParameterPackExpansion node above
970 /// it.
971 ///
972 /// This node is created when some <template-args> are found that apply to an
973 /// <encoding>, and is stored in the TemplateParams table. In order for this to
974 /// appear in the final AST, it has to referenced via a <template-param> (ie,
975 /// T_).
976 class ParameterPack final : public Node {
977   NodeArray Data;
978 public:
979   ParameterPack(NodeArray Data_)
980       : Node(KParameterPack, static_cast<unsigned>(Data_.size())), Data(Data_) {
981     ArrayCache = FunctionCache = RHSComponentCache = Cache::Unknown;
982     if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
983           return P->ArrayCache == Cache::No;
984         }))
985       ArrayCache = Cache::No;
986     if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
987           return P->FunctionCache == Cache::No;
988         }))
989       FunctionCache = Cache::No;
990     if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
991           return P->RHSComponentCache == Cache::No;
992         }))
993       RHSComponentCache = Cache::No;
994   }
995 
996   bool hasRHSComponentSlow(OutputStream &S) const override {
997     size_t Idx = S.CurrentPackIndex;
998     return Idx < Data.size() && Data[Idx]->hasRHSComponent(S);
999   }
1000   bool hasArraySlow(OutputStream &S) const override {
1001     size_t Idx = S.CurrentPackIndex;
1002     return Idx < Data.size() && Data[Idx]->hasArray(S);
1003   }
1004   bool hasFunctionSlow(OutputStream &S) const override {
1005     size_t Idx = S.CurrentPackIndex;
1006     return Idx < Data.size() && Data[Idx]->hasFunction(S);
1007   }
1008 
1009   void printLeft(OutputStream &S) const override {
1010     size_t Idx = S.CurrentPackIndex;
1011     if (Idx < Data.size())
1012       Data[Idx]->printLeft(S);
1013   }
1014   void printRight(OutputStream &S) const override {
1015     size_t Idx = S.CurrentPackIndex;
1016     if (Idx < Data.size())
1017       Data[Idx]->printRight(S);
1018   }
1019 };
1020 
1021 /// A variadic template argument. This node represents an occurance of
1022 /// J<something>E in some <template-args>. It isn't itself unexpanded, unless
1023 /// one of it's Elements is. The parser inserts a ParameterPack into the
1024 /// TemplateParams table if the <template-args> this pack belongs to apply to an
1025 /// <encoding>.
1026 class TemplateArgumentPack final : public Node {
1027   NodeArray Elements;
1028 public:
1029   TemplateArgumentPack(NodeArray Elements_)
1030       : Node(KTemplateArgumentPack), Elements(Elements_) {
1031     for (Node *E : Elements)
1032       ParameterPackSize = std::min(E->ParameterPackSize, ParameterPackSize);
1033   }
1034 
1035   NodeArray getElements() const { return Elements; }
1036 
1037   void printLeft(OutputStream &S) const override {
1038     Elements.printWithComma(S);
1039   }
1040 };
1041 
1042 /// A pack expansion. Below this node, there are some unexpanded ParameterPacks
1043 /// which each have Child->ParameterPackSize elements.
1044 class ParameterPackExpansion final : public Node {
1045   const Node *Child;
1046 
1047 public:
1048   ParameterPackExpansion(Node* Child_)
1049       : Node(KParameterPackExpansion), Child(Child_) {}
1050 
1051   const Node *getChild() const { return Child; }
1052 
1053   void printLeft(OutputStream &S) const override {
1054     unsigned PackSize = Child->ParameterPackSize;
1055     if (PackSize == NoParameterPack) {
1056       Child->print(S);
1057       S += "...";
1058       return;
1059     }
1060 
1061     SwapAndRestore<unsigned> SavePackIndex(S.CurrentPackIndex, 0);
1062     for (unsigned I = 0; I != PackSize; ++I) {
1063       if (I != 0)
1064         S += ", ";
1065       S.CurrentPackIndex = I;
1066       Child->print(S);
1067     }
1068   }
1069 };
1070 
1071 inline bool Node::isEmptyPackExpansion() const {
1072   if (getKind() == KParameterPackExpansion) {
1073     auto *AsPack = static_cast<const ParameterPackExpansion *>(this);
1074     return AsPack->getChild()->isEmptyPackExpansion();
1075   }
1076   if (getKind() == KTemplateArgumentPack) {
1077     auto *AsTemplateArg = static_cast<const TemplateArgumentPack *>(this);
1078     for (Node *E : AsTemplateArg->getElements())
1079       if (!E->isEmptyPackExpansion())
1080         return false;
1081     return true;
1082   }
1083   return ParameterPackSize == 0;
1084 }
1085 
1086 class TemplateArgs final : public Node {
1087   NodeArray Params;
1088 
1089 public:
1090   TemplateArgs(NodeArray Params_) : Node(KTemplateArgs), Params(Params_) {
1091     for (Node *P : Params)
1092       ParameterPackSize = std::min(ParameterPackSize, P->ParameterPackSize);
1093   }
1094 
1095   NodeArray getParams() { return Params; }
1096 
1097   void printLeft(OutputStream &S) const override {
1098     S += "<";
1099     bool FirstElement = true;
1100     for (size_t Idx = 0, E = Params.size(); Idx != E; ++Idx) {
1101       if (Params[Idx]->isEmptyPackExpansion())
1102         continue;
1103       if (!FirstElement)
1104         S += ", ";
1105       FirstElement = false;
1106       Params[Idx]->print(S);
1107     }
1108     if (S.back() == '>')
1109       S += " ";
1110     S += ">";
1111   }
1112 };
1113 
1114 class NameWithTemplateArgs final : public Node {
1115   // name<template_args>
1116   Node *Name;
1117   Node *TemplateArgs;
1118 
1119 public:
1120   NameWithTemplateArgs(Node *Name_, Node *TemplateArgs_)
1121       : Node(KNameWithTemplateArgs, std::min(Name_->ParameterPackSize,
1122                                              TemplateArgs_->ParameterPackSize)),
1123         Name(Name_), TemplateArgs(TemplateArgs_) {}
1124 
1125   StringView getBaseName() const override { return Name->getBaseName(); }
1126 
1127   void printLeft(OutputStream &S) const override {
1128     Name->print(S);
1129     TemplateArgs->print(S);
1130   }
1131 };
1132 
1133 class GlobalQualifiedName final : public Node {
1134   Node *Child;
1135 
1136 public:
1137   GlobalQualifiedName(Node* Child_)
1138       : Node(KGlobalQualifiedName, Child_->ParameterPackSize), Child(Child_) {}
1139 
1140   StringView getBaseName() const override { return Child->getBaseName(); }
1141 
1142   void printLeft(OutputStream &S) const override {
1143     S += "::";
1144     Child->print(S);
1145   }
1146 };
1147 
1148 class StdQualifiedName final : public Node {
1149   Node *Child;
1150 
1151 public:
1152   StdQualifiedName(Node *Child_)
1153       : Node(KStdQualifiedName, Child_->ParameterPackSize), Child(Child_) {}
1154 
1155   StringView getBaseName() const override { return Child->getBaseName(); }
1156 
1157   void printLeft(OutputStream &S) const override {
1158     S += "std::";
1159     Child->print(S);
1160   }
1161 };
1162 
1163 enum class SpecialSubKind {
1164   allocator,
1165   basic_string,
1166   string,
1167   istream,
1168   ostream,
1169   iostream,
1170 };
1171 
1172 class ExpandedSpecialSubstitution final : public Node {
1173   SpecialSubKind SSK;
1174 
1175 public:
1176   ExpandedSpecialSubstitution(SpecialSubKind SSK_)
1177       : Node(KExpandedSpecialSubstitution), SSK(SSK_) {}
1178 
1179   StringView getBaseName() const override {
1180     switch (SSK) {
1181     case SpecialSubKind::allocator:
1182       return StringView("allocator");
1183     case SpecialSubKind::basic_string:
1184       return StringView("basic_string");
1185     case SpecialSubKind::string:
1186       return StringView("basic_string");
1187     case SpecialSubKind::istream:
1188       return StringView("basic_istream");
1189     case SpecialSubKind::ostream:
1190       return StringView("basic_ostream");
1191     case SpecialSubKind::iostream:
1192       return StringView("basic_iostream");
1193     }
1194     LLVM_BUILTIN_UNREACHABLE;
1195   }
1196 
1197   void printLeft(OutputStream &S) const override {
1198     switch (SSK) {
1199     case SpecialSubKind::allocator:
1200       S += "std::basic_string<char, std::char_traits<char>, "
1201            "std::allocator<char> >";
1202       break;
1203     case SpecialSubKind::basic_string:
1204     case SpecialSubKind::string:
1205       S += "std::basic_string<char, std::char_traits<char>, "
1206            "std::allocator<char> >";
1207       break;
1208     case SpecialSubKind::istream:
1209       S += "std::basic_istream<char, std::char_traits<char> >";
1210       break;
1211     case SpecialSubKind::ostream:
1212       S += "std::basic_ostream<char, std::char_traits<char> >";
1213       break;
1214     case SpecialSubKind::iostream:
1215       S += "std::basic_iostream<char, std::char_traits<char> >";
1216       break;
1217     }
1218   }
1219 };
1220 
1221 class SpecialSubstitution final : public Node {
1222 public:
1223   SpecialSubKind SSK;
1224 
1225   SpecialSubstitution(SpecialSubKind SSK_)
1226       : Node(KSpecialSubstitution), SSK(SSK_) {}
1227 
1228   StringView getBaseName() const override {
1229     switch (SSK) {
1230     case SpecialSubKind::allocator:
1231       return StringView("allocator");
1232     case SpecialSubKind::basic_string:
1233       return StringView("basic_string");
1234     case SpecialSubKind::string:
1235       return StringView("string");
1236     case SpecialSubKind::istream:
1237       return StringView("istream");
1238     case SpecialSubKind::ostream:
1239       return StringView("ostream");
1240     case SpecialSubKind::iostream:
1241       return StringView("iostream");
1242     }
1243     LLVM_BUILTIN_UNREACHABLE;
1244   }
1245 
1246   void printLeft(OutputStream &S) const override {
1247     switch (SSK) {
1248     case SpecialSubKind::allocator:
1249       S += "std::allocator";
1250       break;
1251     case SpecialSubKind::basic_string:
1252       S += "std::basic_string";
1253       break;
1254     case SpecialSubKind::string:
1255       S += "std::string";
1256       break;
1257     case SpecialSubKind::istream:
1258       S += "std::istream";
1259       break;
1260     case SpecialSubKind::ostream:
1261       S += "std::ostream";
1262       break;
1263     case SpecialSubKind::iostream:
1264       S += "std::iostream";
1265       break;
1266     }
1267   }
1268 };
1269 
1270 class CtorDtorName final : public Node {
1271   const Node *Basename;
1272   const bool IsDtor;
1273 
1274 public:
1275   CtorDtorName(Node *Basename_, bool IsDtor_)
1276       : Node(KCtorDtorName, Basename_->ParameterPackSize),
1277         Basename(Basename_), IsDtor(IsDtor_) {}
1278 
1279   void printLeft(OutputStream &S) const override {
1280     if (IsDtor)
1281       S += "~";
1282     S += Basename->getBaseName();
1283   }
1284 };
1285 
1286 class DtorName : public Node {
1287   const Node *Base;
1288 
1289 public:
1290   DtorName(Node *Base_) : Node(KDtorName), Base(Base_) {
1291     ParameterPackSize = Base->ParameterPackSize;
1292   }
1293 
1294   void printLeft(OutputStream &S) const override {
1295     S += "~";
1296     Base->printLeft(S);
1297   }
1298 };
1299 
1300 class UnnamedTypeName : public Node {
1301   const StringView Count;
1302 
1303 public:
1304   UnnamedTypeName(StringView Count_) : Node(KUnnamedTypeName), Count(Count_) {}
1305 
1306   void printLeft(OutputStream &S) const override {
1307     S += "'unnamed";
1308     S += Count;
1309     S += "\'";
1310   }
1311 };
1312 
1313 class ClosureTypeName : public Node {
1314   NodeArray Params;
1315   StringView Count;
1316 
1317 public:
1318   ClosureTypeName(NodeArray Params_, StringView Count_)
1319       : Node(KClosureTypeName), Params(Params_), Count(Count_) {
1320     for (Node *P : Params)
1321       ParameterPackSize = std::min(ParameterPackSize, P->ParameterPackSize);
1322   }
1323 
1324   void printLeft(OutputStream &S) const override {
1325     S += "\'lambda";
1326     S += Count;
1327     S += "\'(";
1328     Params.printWithComma(S);
1329     S += ")";
1330   }
1331 };
1332 
1333 class StructuredBindingName : public Node {
1334   NodeArray Bindings;
1335 public:
1336   StructuredBindingName(NodeArray Bindings_)
1337       : Node(KStructuredBindingName), Bindings(Bindings_) {}
1338 
1339   void printLeft(OutputStream &S) const override {
1340     S += '[';
1341     Bindings.printWithComma(S);
1342     S += ']';
1343   }
1344 };
1345 
1346 // -- Expression Nodes --
1347 
1348 struct Expr : public Node {
1349   Expr(Kind K = KExpr) : Node(K) {}
1350 };
1351 
1352 class BinaryExpr : public Expr {
1353   const Node *LHS;
1354   const StringView InfixOperator;
1355   const Node *RHS;
1356 
1357 public:
1358   BinaryExpr(Node *LHS_, StringView InfixOperator_, Node *RHS_)
1359       : LHS(LHS_), InfixOperator(InfixOperator_), RHS(RHS_) {
1360     ParameterPackSize =
1361       std::min(LHS->ParameterPackSize, RHS->ParameterPackSize);
1362   }
1363 
1364   void printLeft(OutputStream &S) const override {
1365     // might be a template argument expression, then we need to disambiguate
1366     // with parens.
1367     if (InfixOperator == ">")
1368       S += "(";
1369 
1370     S += "(";
1371     LHS->print(S);
1372     S += ") ";
1373     S += InfixOperator;
1374     S += " (";
1375     RHS->print(S);
1376     S += ")";
1377 
1378     if (InfixOperator == ">")
1379       S += ")";
1380   }
1381 };
1382 
1383 class ArraySubscriptExpr : public Expr {
1384   const Node *Op1;
1385   const Node *Op2;
1386 
1387 public:
1388   ArraySubscriptExpr(Node *Op1_, Node *Op2_) : Op1(Op1_), Op2(Op2_) {
1389     ParameterPackSize =
1390       std::min(Op1->ParameterPackSize, Op2->ParameterPackSize);
1391   }
1392 
1393   void printLeft(OutputStream &S) const override {
1394     S += "(";
1395     Op1->print(S);
1396     S += ")[";
1397     Op2->print(S);
1398     S += "]";
1399   }
1400 };
1401 
1402 class PostfixExpr : public Expr {
1403   const Node *Child;
1404   const StringView Operand;
1405 
1406 public:
1407   PostfixExpr(Node *Child_, StringView Operand_)
1408       : Child(Child_), Operand(Operand_) {
1409     ParameterPackSize = Child->ParameterPackSize;
1410   }
1411 
1412   void printLeft(OutputStream &S) const override {
1413     S += "(";
1414     Child->print(S);
1415     S += ")";
1416     S += Operand;
1417   }
1418 };
1419 
1420 class ConditionalExpr : public Expr {
1421   const Node *Cond;
1422   const Node *Then;
1423   const Node *Else;
1424 
1425 public:
1426   ConditionalExpr(Node *Cond_, Node *Then_, Node *Else_)
1427       : Cond(Cond_), Then(Then_), Else(Else_) {
1428     ParameterPackSize =
1429         std::min(Cond->ParameterPackSize,
1430                  std::min(Then->ParameterPackSize, Else->ParameterPackSize));
1431   }
1432 
1433   void printLeft(OutputStream &S) const override {
1434     S += "(";
1435     Cond->print(S);
1436     S += ") ? (";
1437     Then->print(S);
1438     S += ") : (";
1439     Else->print(S);
1440     S += ")";
1441   }
1442 };
1443 
1444 class MemberExpr : public Expr {
1445   const Node *LHS;
1446   const StringView Kind;
1447   const Node *RHS;
1448 
1449 public:
1450   MemberExpr(Node *LHS_, StringView Kind_, Node *RHS_)
1451       : LHS(LHS_), Kind(Kind_), RHS(RHS_) {
1452     ParameterPackSize =
1453       std::min(LHS->ParameterPackSize, RHS->ParameterPackSize);
1454   }
1455 
1456   void printLeft(OutputStream &S) const override {
1457     LHS->print(S);
1458     S += Kind;
1459     RHS->print(S);
1460   }
1461 };
1462 
1463 class EnclosingExpr : public Expr {
1464   const StringView Prefix;
1465   const Node *Infix;
1466   const StringView Postfix;
1467 
1468 public:
1469   EnclosingExpr(StringView Prefix_, Node *Infix_, StringView Postfix_)
1470       : Prefix(Prefix_), Infix(Infix_), Postfix(Postfix_) {
1471     ParameterPackSize = Infix->ParameterPackSize;
1472   }
1473 
1474   void printLeft(OutputStream &S) const override {
1475     S += Prefix;
1476     Infix->print(S);
1477     S += Postfix;
1478   }
1479 };
1480 
1481 class CastExpr : public Expr {
1482   // cast_kind<to>(from)
1483   const StringView CastKind;
1484   const Node *To;
1485   const Node *From;
1486 
1487 public:
1488   CastExpr(StringView CastKind_, Node *To_, Node *From_)
1489       : CastKind(CastKind_), To(To_), From(From_) {
1490     ParameterPackSize =
1491       std::min(To->ParameterPackSize, From->ParameterPackSize);
1492   }
1493 
1494   void printLeft(OutputStream &S) const override {
1495     S += CastKind;
1496     S += "<";
1497     To->printLeft(S);
1498     S += ">(";
1499     From->printLeft(S);
1500     S += ")";
1501   }
1502 };
1503 
1504 class SizeofParamPackExpr : public Expr {
1505   Node *Pack;
1506 
1507 public:
1508   SizeofParamPackExpr(Node *Pack_) : Pack(Pack_) {}
1509 
1510   void printLeft(OutputStream &S) const override {
1511     S += "sizeof...(";
1512     ParameterPackExpansion PPE(Pack);
1513     PPE.printLeft(S);
1514     S += ")";
1515   }
1516 };
1517 
1518 class CallExpr : public Expr {
1519   const Node *Callee;
1520   NodeArray Args;
1521 
1522 public:
1523   CallExpr(Node *Callee_, NodeArray Args_) : Callee(Callee_), Args(Args_) {
1524     for (Node *P : Args)
1525       ParameterPackSize = std::min(ParameterPackSize, P->ParameterPackSize);
1526     ParameterPackSize = std::min(ParameterPackSize, Callee->ParameterPackSize);
1527   }
1528 
1529   void printLeft(OutputStream &S) const override {
1530     Callee->print(S);
1531     S += "(";
1532     Args.printWithComma(S);
1533     S += ")";
1534   }
1535 };
1536 
1537 class NewExpr : public Expr {
1538   // new (expr_list) type(init_list)
1539   NodeArray ExprList;
1540   Node *Type;
1541   NodeArray InitList;
1542   bool IsGlobal; // ::operator new ?
1543   bool IsArray;  // new[] ?
1544 public:
1545   NewExpr(NodeArray ExprList_, Node *Type_, NodeArray InitList_, bool IsGlobal_,
1546           bool IsArray_)
1547       : ExprList(ExprList_), Type(Type_), InitList(InitList_),
1548         IsGlobal(IsGlobal_), IsArray(IsArray_) {
1549     for (Node *E : ExprList)
1550       ParameterPackSize = std::min(ParameterPackSize, E->ParameterPackSize);
1551     for (Node *I : InitList)
1552       ParameterPackSize = std::min(ParameterPackSize, I->ParameterPackSize);
1553     if (Type)
1554       ParameterPackSize = std::min(ParameterPackSize, Type->ParameterPackSize);
1555   }
1556 
1557   void printLeft(OutputStream &S) const override {
1558     if (IsGlobal)
1559       S += "::operator ";
1560     S += "new";
1561     if (IsArray)
1562       S += "[]";
1563     S += ' ';
1564     if (!ExprList.empty()) {
1565       S += "(";
1566       ExprList.printWithComma(S);
1567       S += ")";
1568     }
1569     Type->print(S);
1570     if (!InitList.empty()) {
1571       S += "(";
1572       InitList.printWithComma(S);
1573       S += ")";
1574     }
1575 
1576   }
1577 };
1578 
1579 class DeleteExpr : public Expr {
1580   Node *Op;
1581   bool IsGlobal;
1582   bool IsArray;
1583 
1584 public:
1585   DeleteExpr(Node *Op_, bool IsGlobal_, bool IsArray_)
1586       : Op(Op_), IsGlobal(IsGlobal_), IsArray(IsArray_) {
1587     ParameterPackSize = Op->ParameterPackSize;
1588   }
1589 
1590   void printLeft(OutputStream &S) const override {
1591     if (IsGlobal)
1592       S += "::";
1593     S += "delete";
1594     if (IsArray)
1595       S += "[] ";
1596     Op->print(S);
1597   }
1598 };
1599 
1600 class PrefixExpr : public Expr {
1601   StringView Prefix;
1602   Node *Child;
1603 
1604 public:
1605   PrefixExpr(StringView Prefix_, Node *Child_) : Prefix(Prefix_), Child(Child_) {
1606     ParameterPackSize = Child->ParameterPackSize;
1607   }
1608 
1609   void printLeft(OutputStream &S) const override {
1610     S += Prefix;
1611     S += "(";
1612     Child->print(S);
1613     S += ")";
1614   }
1615 };
1616 
1617 class FunctionParam : public Expr {
1618   StringView Number;
1619 
1620 public:
1621   FunctionParam(StringView Number_) : Number(Number_) {}
1622 
1623   void printLeft(OutputStream &S) const override {
1624     S += "fp";
1625     S += Number;
1626   }
1627 };
1628 
1629 class ConversionExpr : public Expr {
1630   const Node *Type;
1631   NodeArray Expressions;
1632 
1633 public:
1634   ConversionExpr(const Node *Type_, NodeArray Expressions_)
1635       : Type(Type_), Expressions(Expressions_) {
1636     for (Node *E : Expressions)
1637       ParameterPackSize = std::min(ParameterPackSize, E->ParameterPackSize);
1638     ParameterPackSize = std::min(ParameterPackSize, Type->ParameterPackSize);
1639   }
1640 
1641   void printLeft(OutputStream &S) const override {
1642     S += "(";
1643     Type->print(S);
1644     S += ")(";
1645     Expressions.printWithComma(S);
1646     S += ")";
1647   }
1648 };
1649 
1650 class InitListExpr : public Expr {
1651   Node *Ty;
1652   NodeArray Inits;
1653 public:
1654   InitListExpr(Node *Ty_, NodeArray Inits_)
1655       : Ty(Ty_), Inits(Inits_) {
1656     if (Ty)
1657       ParameterPackSize = Ty->ParameterPackSize;
1658     for (Node *I : Inits)
1659       ParameterPackSize = std::min(I->ParameterPackSize, ParameterPackSize);
1660   }
1661 
1662   void printLeft(OutputStream &S) const override {
1663     if (Ty)
1664       Ty->print(S);
1665     S += '{';
1666     Inits.printWithComma(S);
1667     S += '}';
1668   }
1669 };
1670 
1671 class BracedExpr : public Expr {
1672   Node *Elem;
1673   Node *Init;
1674   bool IsArray;
1675 public:
1676   BracedExpr(Node *Elem_, Node *Init_, bool IsArray_)
1677       : Expr(KBracedExpr), Elem(Elem_), Init(Init_), IsArray(IsArray_) {}
1678 
1679   void printLeft(OutputStream &S) const override {
1680     if (IsArray) {
1681       S += '[';
1682       Elem->print(S);
1683       S += ']';
1684     } else {
1685       S += '.';
1686       Elem->print(S);
1687     }
1688     if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
1689       S += " = ";
1690     Init->print(S);
1691   }
1692 };
1693 
1694 class BracedRangeExpr : public Expr {
1695   Node *First;
1696   Node *Last;
1697   Node *Init;
1698 public:
1699   BracedRangeExpr(Node *First_, Node *Last_, Node *Init_)
1700       : Expr(KBracedRangeExpr), First(First_), Last(Last_), Init(Init_) {}
1701 
1702   void printLeft(OutputStream &S) const override {
1703     S += '[';
1704     First->print(S);
1705     S += " ... ";
1706     Last->print(S);
1707     S += ']';
1708     if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
1709       S += " = ";
1710     Init->print(S);
1711   }
1712 };
1713 
1714 class ThrowExpr : public Expr {
1715   const Node *Op;
1716 
1717 public:
1718   ThrowExpr(Node *Op_) : Op(Op_) {
1719     ParameterPackSize = Op->ParameterPackSize;
1720   }
1721 
1722   void printLeft(OutputStream &S) const override {
1723     S += "throw ";
1724     Op->print(S);
1725   }
1726 };
1727 
1728 class BoolExpr : public Expr {
1729   bool Value;
1730 
1731 public:
1732   BoolExpr(bool Value_) : Value(Value_) {}
1733 
1734   void printLeft(OutputStream &S) const override {
1735     S += Value ? StringView("true") : StringView("false");
1736   }
1737 };
1738 
1739 class IntegerCastExpr : public Expr {
1740   // ty(integer)
1741   Node *Ty;
1742   StringView Integer;
1743 
1744 public:
1745   IntegerCastExpr(Node *Ty_, StringView Integer_) : Ty(Ty_), Integer(Integer_) {
1746     ParameterPackSize = Ty->ParameterPackSize;
1747   }
1748 
1749   void printLeft(OutputStream &S) const override {
1750     S += "(";
1751     Ty->print(S);
1752     S += ")";
1753     S += Integer;
1754   }
1755 };
1756 
1757 class IntegerExpr : public Expr {
1758   StringView Type;
1759   StringView Value;
1760 
1761 public:
1762   IntegerExpr(StringView Type_, StringView Value_) : Type(Type_), Value(Value_) {}
1763 
1764   void printLeft(OutputStream &S) const override {
1765     if (Type.size() > 3) {
1766       S += "(";
1767       S += Type;
1768       S += ")";
1769     }
1770 
1771     if (Value[0] == 'n') {
1772       S += "-";
1773       S += Value.dropFront(1);
1774     } else
1775       S += Value;
1776 
1777     if (Type.size() <= 3)
1778       S += Type;
1779   }
1780 };
1781 
1782 template <class Float> struct FloatData;
1783 
1784 template <class Float> class FloatExpr : public Expr {
1785   const StringView Contents;
1786 
1787 public:
1788   FloatExpr(StringView Contents_) : Contents(Contents_) {}
1789 
1790   void printLeft(OutputStream &s) const override {
1791     const char *first = Contents.begin();
1792     const char *last = Contents.end() + 1;
1793 
1794     const size_t N = FloatData<Float>::mangled_size;
1795     if (static_cast<std::size_t>(last - first) > N) {
1796       last = first + N;
1797       union {
1798         Float value;
1799         char buf[sizeof(Float)];
1800       };
1801       const char *t = first;
1802       char *e = buf;
1803       for (; t != last; ++t, ++e) {
1804         unsigned d1 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
1805                                   : static_cast<unsigned>(*t - 'a' + 10);
1806         ++t;
1807         unsigned d0 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
1808                                   : static_cast<unsigned>(*t - 'a' + 10);
1809         *e = static_cast<char>((d1 << 4) + d0);
1810       }
1811 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1812       std::reverse(buf, e);
1813 #endif
1814       char num[FloatData<Float>::max_demangled_size] = {0};
1815       int n = snprintf(num, sizeof(num), FloatData<Float>::spec, value);
1816       s += StringView(num, num + n);
1817     }
1818   }
1819 };
1820 
1821 class BumpPointerAllocator {
1822   struct BlockMeta {
1823     BlockMeta* Next;
1824     size_t Current;
1825   };
1826 
1827   static constexpr size_t AllocSize = 4096;
1828   static constexpr size_t UsableAllocSize = AllocSize - sizeof(BlockMeta);
1829 
1830   alignas(16) char InitialBuffer[AllocSize];
1831   BlockMeta* BlockList = nullptr;
1832 
1833   void grow() {
1834     char* NewMeta = new char[AllocSize];
1835     BlockList = new (NewMeta) BlockMeta{BlockList, 0};
1836   }
1837 
1838   void* allocateMassive(size_t NBytes) {
1839     NBytes += sizeof(BlockMeta);
1840     BlockMeta* NewMeta = reinterpret_cast<BlockMeta*>(new char[NBytes]);
1841     BlockList->Next = new (NewMeta) BlockMeta{BlockList->Next, 0};
1842     return static_cast<void*>(NewMeta + 1);
1843   }
1844 
1845 public:
1846   BumpPointerAllocator()
1847       : BlockList(new (InitialBuffer) BlockMeta{nullptr, 0}) {}
1848 
1849   void* allocate(size_t N) {
1850     N = (N + 15u) & ~15u;
1851     if (N + BlockList->Current >= UsableAllocSize) {
1852       if (N > UsableAllocSize)
1853         return allocateMassive(N);
1854       grow();
1855     }
1856     BlockList->Current += N;
1857     return static_cast<void*>(reinterpret_cast<char*>(BlockList + 1) +
1858                               BlockList->Current - N);
1859   }
1860 
1861   ~BumpPointerAllocator() {
1862     while (BlockList) {
1863       BlockMeta* Tmp = BlockList;
1864       BlockList = BlockList->Next;
1865       if (reinterpret_cast<char*>(Tmp) != InitialBuffer)
1866         delete[] reinterpret_cast<char*>(Tmp);
1867     }
1868   }
1869 };
1870 
1871 template <class T, size_t N>
1872 class PODSmallVector {
1873   static_assert(std::is_pod<T>::value,
1874                 "T is required to be a plain old data type");
1875 
1876   T* First;
1877   T* Last;
1878   T* Cap;
1879   T Inline[N];
1880 
1881   bool isInline() const { return First == Inline; }
1882 
1883   void clearInline() {
1884     First = Inline;
1885     Last = Inline;
1886     Cap = Inline + N;
1887   }
1888 
1889   void reserve(size_t NewCap) {
1890     size_t S = size();
1891     if (isInline()) {
1892       auto* Tmp = static_cast<T*>(std::malloc(NewCap * sizeof(T)));
1893       std::copy(First, Last, Tmp);
1894       First = Tmp;
1895     } else
1896       First = static_cast<T*>(std::realloc(First, NewCap * sizeof(T)));
1897     Last = First + S;
1898     Cap = First + NewCap;
1899   }
1900 
1901 public:
1902   PODSmallVector() : First(Inline), Last(First), Cap(Inline + N) {}
1903 
1904   PODSmallVector(const PODSmallVector&) = delete;
1905   PODSmallVector& operator=(const PODSmallVector&) = delete;
1906 
1907   PODSmallVector(PODSmallVector&& Other) : PODSmallVector() {
1908     if (Other.isInline()) {
1909       std::copy(Other.begin(), Other.end(), First);
1910       Last = First + Other.size();
1911       Other.clear();
1912       return;
1913     }
1914 
1915     First = Other.First;
1916     Last = Other.Last;
1917     Cap = Other.Cap;
1918     Other.clearInline();
1919   }
1920 
1921   PODSmallVector& operator=(PODSmallVector&& Other) {
1922     if (Other.isInline()) {
1923       if (!isInline()) {
1924         std::free(First);
1925         clearInline();
1926       }
1927       std::copy(Other.begin(), Other.end(), First);
1928       Last = First + Other.size();
1929       Other.clear();
1930       return *this;
1931     }
1932 
1933     if (isInline()) {
1934       First = Other.First;
1935       Last = Other.Last;
1936       Cap = Other.Cap;
1937       Other.clearInline();
1938       return *this;
1939     }
1940 
1941     std::swap(First, Other.First);
1942     std::swap(Last, Other.Last);
1943     std::swap(Cap, Other.Cap);
1944     Other.clear();
1945     return *this;
1946   }
1947 
1948   void push_back(const T& Elem) {
1949     if (Last == Cap)
1950       reserve(size() * 2);
1951     *Last++ = Elem;
1952   }
1953 
1954   void pop_back() {
1955     assert(Last != First && "Popping empty vector!");
1956     --Last;
1957   }
1958 
1959   void dropBack(size_t Index) {
1960     assert(Index <= size() && "dropBack() can't expand!");
1961     Last = First + Index;
1962   }
1963 
1964   T* begin() { return First; }
1965   T* end() { return Last; }
1966 
1967   bool empty() const { return First == Last; }
1968   size_t size() const { return static_cast<size_t>(Last - First); }
1969   T& back() {
1970     assert(Last != First && "Calling back() on empty vector!");
1971     return *(Last - 1);
1972   }
1973   T& operator[](size_t Index) {
1974     assert(Index < size() && "Invalid access!");
1975     return *(begin() + Index);
1976   }
1977   void clear() { Last = First; }
1978 
1979   ~PODSmallVector() {
1980     if (!isInline())
1981       std::free(First);
1982   }
1983 };
1984 
1985 struct Db {
1986   const char *First;
1987   const char *Last;
1988 
1989   // Name stack, this is used by the parser to hold temporary names that were
1990   // parsed. The parser colapses multiple names into new nodes to construct
1991   // the AST. Once the parser is finished, names.size() == 1.
1992   PODSmallVector<Node *, 32> Names;
1993 
1994   // Substitution table. Itanium supports name substitutions as a means of
1995   // compression. The string "S42_" refers to the 44nd entry (base-36) in this
1996   // table.
1997   PODSmallVector<Node *, 32> Subs;
1998 
1999   // Template parameter table. Like the above, but referenced like "T42_".
2000   // This has a smaller size compared to Subs and Names because it can be
2001   // stored on the stack.
2002   PODSmallVector<Node *, 8> TemplateParams;
2003 
2004   unsigned EncodingDepth = 0;
2005   bool TagTemplates = true;
2006   bool FixForwardReferences = false;
2007   bool TryToParseTemplateArgs = true;
2008   bool ParsingLambdaParams = false;
2009 
2010   BumpPointerAllocator ASTAllocator;
2011 
2012   Db(const char *First_, const char *Last_) : First(First_), Last(Last_) {}
2013 
2014   template <class T, class... Args> T *make(Args &&... args) {
2015     return new (ASTAllocator.allocate(sizeof(T)))
2016         T(std::forward<Args>(args)...);
2017   }
2018 
2019   template <class It> NodeArray makeNodeArray(It begin, It end) {
2020     size_t sz = static_cast<size_t>(end - begin);
2021     void *mem = ASTAllocator.allocate(sizeof(Node *) * sz);
2022     Node **data = new (mem) Node *[sz];
2023     std::copy(begin, end, data);
2024     return NodeArray(data, sz);
2025   }
2026 
2027   NodeArray popTrailingNodeArray(size_t FromPosition) {
2028     assert(FromPosition <= Names.size());
2029     NodeArray res =
2030         makeNodeArray(Names.begin() + (long)FromPosition, Names.end());
2031     Names.dropBack(FromPosition);
2032     return res;
2033   }
2034 
2035   bool consumeIf(StringView S) {
2036     if (StringView(First, Last).startsWith(S)) {
2037       First += S.size();
2038       return true;
2039     }
2040     return false;
2041   }
2042 
2043   bool consumeIf(char C) {
2044     if (First != Last && *First == C) {
2045       ++First;
2046       return true;
2047     }
2048     return false;
2049   }
2050 
2051   char consume() { return First != Last ? *First++ : '\0'; }
2052 
2053   char look(unsigned Lookahead = 0) {
2054     if (static_cast<size_t>(Last - First) <= Lookahead)
2055       return '\0';
2056     return First[Lookahead];
2057   }
2058 
2059   size_t numLeft() const { return static_cast<size_t>(Last - First); }
2060 
2061   StringView parseNumber(bool AllowNegative = false);
2062   Qualifiers parseCVQualifiers();
2063   bool parsePositiveInteger(size_t *Out);
2064   StringView parseBareSourceName();
2065 
2066   bool parseSeqId(size_t *Out);
2067   Node *parseSubstitution();
2068   Node *parseTemplateParam();
2069   Node *parseTemplateArgs();
2070   Node *parseTemplateArg();
2071 
2072   /// Parse the <expr> production.
2073   Node *parseExpr();
2074   Node *parsePrefixExpr(StringView Kind);
2075   Node *parseBinaryExpr(StringView Kind);
2076   Node *parseIntegerLiteral(StringView Lit);
2077   Node *parseExprPrimary();
2078   template <class Float> Node *parseFloatingLiteral();
2079   Node *parseFunctionParam();
2080   Node *parseNewExpr();
2081   Node *parseConversionExpr();
2082   Node *parseBracedExpr();
2083 
2084   /// Parse the <type> production.
2085   Node *parseType();
2086   Node *parseFunctionType();
2087   Node *parseVectorType();
2088   Node *parseDecltype();
2089   Node *parseArrayType();
2090   Node *parsePointerToMemberType();
2091   Node *parseClassEnumType();
2092   Node *parseQualifiedType();
2093 
2094   Node *parseEncoding();
2095   bool parseCallOffset();
2096   Node *parseSpecialName();
2097 
2098   /// Holds some extra information about a <name> that is being parsed. This
2099   /// information is only pertinent if the <name> refers to an <encoding>.
2100   struct NameState {
2101     bool CtorDtorConversion = false;
2102     bool EndsWithTemplateArgs = false;
2103     Qualifiers CVQualifiers = QualNone;
2104     FunctionRefQual ReferenceQualifier = FrefQualNone;
2105   };
2106 
2107   /// Parse the <name> production>
2108   Node *parseName(NameState *State = nullptr);
2109   Node *parseLocalName(NameState *State);
2110   Node *parseOperatorName(NameState *State);
2111   Node *parseUnqualifiedName(NameState *State);
2112   Node *parseUnnamedTypeName(NameState *State);
2113   Node *parseSourceName(NameState *State);
2114   Node *parseUnscopedName(NameState *State);
2115   Node *parseNestedName(NameState *State);
2116   Node *parseCtorDtorName(Node *&SoFar, NameState *State);
2117 
2118   Node *parseAbiTags(Node *N);
2119 
2120   /// Parse the <unresolved-name> production.
2121   Node *parseUnresolvedName();
2122   Node *parseSimpleId();
2123   Node *parseBaseUnresolvedName();
2124   Node *parseUnresolvedType();
2125   Node *parseDestructorName();
2126 
2127   /// Top-level entry point into the parser.
2128   Node *parse();
2129 };
2130 
2131 const char* parse_discriminator(const char* first, const char* last);
2132 
2133 // <name> ::= <nested-name> // N
2134 //        ::= <local-name> # See Scope Encoding below  // Z
2135 //        ::= <unscoped-template-name> <template-args>
2136 //        ::= <unscoped-name>
2137 //
2138 // <unscoped-template-name> ::= <unscoped-name>
2139 //                          ::= <substitution>
2140 Node *Db::parseName(NameState *State) {
2141   consumeIf('L'); // extension
2142 
2143   if (look() == 'N')
2144     return parseNestedName(State);
2145   if (look() == 'Z')
2146     return parseLocalName(State);
2147 
2148   //        ::= <unscoped-template-name> <template-args>
2149   if (look() == 'S' && look(1) != 't') {
2150     Node *S = parseSubstitution();
2151     if (S == nullptr)
2152       return nullptr;
2153     if (look() != 'I')
2154       return nullptr;
2155     Node *TA = parseTemplateArgs();
2156     if (TA == nullptr)
2157       return nullptr;
2158     if (State) State->EndsWithTemplateArgs = true;
2159     return make<NameWithTemplateArgs>(S, TA);
2160   }
2161 
2162   Node *N = parseUnscopedName(State);
2163   if (N == nullptr)
2164     return nullptr;
2165   //        ::= <unscoped-template-name> <template-args>
2166   if (look() == 'I') {
2167     Subs.push_back(N);
2168     Node *TA = parseTemplateArgs();
2169     if (TA == nullptr)
2170       return nullptr;
2171     if (State) State->EndsWithTemplateArgs = true;
2172     return make<NameWithTemplateArgs>(N, TA);
2173   }
2174   //        ::= <unscoped-name>
2175   return N;
2176 }
2177 
2178 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
2179 //              := Z <function encoding> E s [<discriminator>]
2180 //              := Z <function encoding> Ed [ <parameter number> ] _ <entity name>
2181 Node *Db::parseLocalName(NameState *State) {
2182   if (!consumeIf('Z'))
2183     return nullptr;
2184   Node *Encoding = parseEncoding();
2185   if (Encoding == nullptr || !consumeIf('E'))
2186     return nullptr;
2187 
2188   if (consumeIf('s')) {
2189     First = parse_discriminator(First, Last);
2190     return make<QualifiedName>(Encoding, make<NameType>("string literal"));
2191   }
2192 
2193   if (consumeIf('d')) {
2194     parseNumber(true);
2195     if (!consumeIf('_'))
2196       return nullptr;
2197     Node *N = parseName(State);
2198     if (N == nullptr)
2199       return nullptr;
2200     return make<QualifiedName>(Encoding, N);
2201   }
2202 
2203   Node *Entity = parseName(State);
2204   if (Entity == nullptr)
2205     return nullptr;
2206   First = parse_discriminator(First, Last);
2207   return make<QualifiedName>(Encoding, Entity);
2208 }
2209 
2210 // <unscoped-name> ::= <unqualified-name>
2211 //                 ::= St <unqualified-name>   # ::std::
2212 // extension       ::= StL<unqualified-name>
2213 Node *Db::parseUnscopedName(NameState *State) {
2214  if (consumeIf("StL") || consumeIf("St")) {
2215    Node *R = parseUnqualifiedName(State);
2216    if (R == nullptr)
2217      return nullptr;
2218    return make<StdQualifiedName>(R);
2219  }
2220  return parseUnqualifiedName(State);
2221 }
2222 
2223 // <unqualified-name> ::= <operator-name> [abi-tags]
2224 //                    ::= <ctor-dtor-name>
2225 //                    ::= <source-name>
2226 //                    ::= <unnamed-type-name>
2227 //                    ::= DC <source-name>+ E      # structured binding declaration
2228 Node *Db::parseUnqualifiedName(NameState *State) {
2229  // <ctor-dtor-name>s are special-cased in parseNestedName().
2230  Node *Result;
2231  if (look() == 'U')
2232    Result = parseUnnamedTypeName(State);
2233  else if (look() >= '1' && look() <= '9')
2234    Result = parseSourceName(State);
2235  else if (consumeIf("DC")) {
2236    size_t BindingsBegin = Names.size();
2237    do {
2238      Node *Binding = parseSourceName(State);
2239      if (Binding == nullptr)
2240        return nullptr;
2241      Names.push_back(Binding);
2242    } while (!consumeIf('E'));
2243    Result = make<StructuredBindingName>(popTrailingNodeArray(BindingsBegin));
2244  } else
2245    Result = parseOperatorName(State);
2246  if (Result != nullptr)
2247    Result = parseAbiTags(Result);
2248  return Result;
2249 }
2250 
2251 // <unnamed-type-name> ::= Ut [<nonnegative number>] _
2252 //                     ::= <closure-type-name>
2253 //
2254 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
2255 //
2256 // <lambda-sig> ::= <parameter type>+  # Parameter types or "v" if the lambda has no parameters
2257 Node *Db::parseUnnamedTypeName(NameState *) {
2258   if (consumeIf("Ut")) {
2259     StringView Count = parseNumber();
2260     if (!consumeIf('_'))
2261       return nullptr;
2262     return make<UnnamedTypeName>(Count);
2263   }
2264   if (consumeIf("Ul")) {
2265     NodeArray Params;
2266     SwapAndRestore<bool> SwapParams(ParsingLambdaParams, true);
2267     if (!consumeIf("vE")) {
2268       size_t ParamsBegin = Names.size();
2269       do {
2270         Node *P = parseType();
2271         if (P == nullptr)
2272           return nullptr;
2273         Names.push_back(P);
2274       } while (!consumeIf('E'));
2275       Params = popTrailingNodeArray(ParamsBegin);
2276     }
2277     StringView Count = parseNumber();
2278     if (!consumeIf('_'))
2279       return nullptr;
2280     return make<ClosureTypeName>(Params, Count);
2281   }
2282   return nullptr;
2283 }
2284 
2285 // <source-name> ::= <positive length number> <identifier>
2286 Node *Db::parseSourceName(NameState *) {
2287   size_t Length = 0;
2288   if (parsePositiveInteger(&Length))
2289     return nullptr;
2290   if (numLeft() < Length || Length == 0)
2291     return nullptr;
2292   StringView Name(First, First + Length);
2293   First += Length;
2294   if (Name.startsWith("_GLOBAL__N"))
2295     return make<NameType>("(anonymous namespace)");
2296   return make<NameType>(Name);
2297 }
2298 
2299 //   <operator-name> ::= aa    # &&
2300 //                   ::= ad    # & (unary)
2301 //                   ::= an    # &
2302 //                   ::= aN    # &=
2303 //                   ::= aS    # =
2304 //                   ::= cl    # ()
2305 //                   ::= cm    # ,
2306 //                   ::= co    # ~
2307 //                   ::= cv <type>    # (cast)
2308 //                   ::= da    # delete[]
2309 //                   ::= de    # * (unary)
2310 //                   ::= dl    # delete
2311 //                   ::= dv    # /
2312 //                   ::= dV    # /=
2313 //                   ::= eo    # ^
2314 //                   ::= eO    # ^=
2315 //                   ::= eq    # ==
2316 //                   ::= ge    # >=
2317 //                   ::= gt    # >
2318 //                   ::= ix    # []
2319 //                   ::= le    # <=
2320 //                   ::= li <source-name>  # operator ""
2321 //                   ::= ls    # <<
2322 //                   ::= lS    # <<=
2323 //                   ::= lt    # <
2324 //                   ::= mi    # -
2325 //                   ::= mI    # -=
2326 //                   ::= ml    # *
2327 //                   ::= mL    # *=
2328 //                   ::= mm    # -- (postfix in <expression> context)
2329 //                   ::= na    # new[]
2330 //                   ::= ne    # !=
2331 //                   ::= ng    # - (unary)
2332 //                   ::= nt    # !
2333 //                   ::= nw    # new
2334 //                   ::= oo    # ||
2335 //                   ::= or    # |
2336 //                   ::= oR    # |=
2337 //                   ::= pm    # ->*
2338 //                   ::= pl    # +
2339 //                   ::= pL    # +=
2340 //                   ::= pp    # ++ (postfix in <expression> context)
2341 //                   ::= ps    # + (unary)
2342 //                   ::= pt    # ->
2343 //                   ::= qu    # ?
2344 //                   ::= rm    # %
2345 //                   ::= rM    # %=
2346 //                   ::= rs    # >>
2347 //                   ::= rS    # >>=
2348 //                   ::= ss    # <=> C++2a
2349 //                   ::= v <digit> <source-name>        # vendor extended operator
2350 Node *Db::parseOperatorName(NameState *State) {
2351   switch (look()) {
2352   case 'a':
2353     switch (look(1)) {
2354     case 'a':
2355       First += 2;
2356       return make<NameType>("operator&&");
2357     case 'd':
2358     case 'n':
2359       First += 2;
2360       return make<NameType>("operator&");
2361     case 'N':
2362       First += 2;
2363       return make<NameType>("operator&=");
2364     case 'S':
2365       First += 2;
2366       return make<NameType>("operator=");
2367     }
2368     return nullptr;
2369   case 'c':
2370     switch (look(1)) {
2371     case 'l':
2372       First += 2;
2373       return make<NameType>("operator()");
2374     case 'm':
2375       First += 2;
2376       return make<NameType>("operator,");
2377     case 'o':
2378       First += 2;
2379       return make<NameType>("operator~");
2380     //                   ::= cv <type>    # (cast)
2381     case 'v': {
2382       SwapAndRestore<bool> SaveTemplate(TryToParseTemplateArgs, false);
2383       First += 2;
2384       Node *Ty = parseType();
2385       if (Ty == nullptr)
2386         return nullptr;
2387       if (State) State->CtorDtorConversion = true;
2388       return make<ConversionOperatorType>(Ty);
2389     }
2390     }
2391     return nullptr;
2392   case 'd':
2393     switch (look(1)) {
2394     case 'a':
2395       First += 2;
2396       return make<NameType>("operator delete[]");
2397     case 'e':
2398       First += 2;
2399       return make<NameType>("operator*");
2400     case 'l':
2401       First += 2;
2402       return make<NameType>("operator delete");
2403     case 'v':
2404       First += 2;
2405       return make<NameType>("operator/");
2406     case 'V':
2407       First += 2;
2408       return make<NameType>("operator/=");
2409     }
2410     return nullptr;
2411   case 'e':
2412     switch (look(1)) {
2413     case 'o':
2414       First += 2;
2415       return make<NameType>("operator^");
2416     case 'O':
2417       First += 2;
2418       return make<NameType>("operator^=");
2419     case 'q':
2420       First += 2;
2421       return make<NameType>("operator==");
2422     }
2423     return nullptr;
2424   case 'g':
2425     switch (look(1)) {
2426     case 'e':
2427       First += 2;
2428       return make<NameType>("operator>=");
2429     case 't':
2430       First += 2;
2431       return make<NameType>("operator>");
2432     }
2433     return nullptr;
2434   case 'i':
2435     if (look(1) == 'x') {
2436       First += 2;
2437       return make<NameType>("operator[]");
2438     }
2439     return nullptr;
2440   case 'l':
2441     switch (look(1)) {
2442     case 'e':
2443       First += 2;
2444       return make<NameType>("operator<=");
2445     //                   ::= li <source-name>  # operator ""
2446     case 'i': {
2447       First += 2;
2448       Node *SN = parseSourceName(State);
2449       if (SN == nullptr)
2450         return nullptr;
2451       return make<LiteralOperator>(SN);
2452     }
2453     case 's':
2454       First += 2;
2455       return make<NameType>("operator<<");
2456     case 'S':
2457       First += 2;
2458       return make<NameType>("operator<<=");
2459     case 't':
2460       First += 2;
2461       return make<NameType>("operator<");
2462     }
2463     return nullptr;
2464   case 'm':
2465     switch (look(1)) {
2466     case 'i':
2467       First += 2;
2468       return make<NameType>("operator-");
2469     case 'I':
2470       First += 2;
2471       return make<NameType>("operator-=");
2472     case 'l':
2473       First += 2;
2474       return make<NameType>("operator*");
2475     case 'L':
2476       First += 2;
2477       return make<NameType>("operator*=");
2478     case 'm':
2479       First += 2;
2480       return make<NameType>("operator--");
2481     }
2482     return nullptr;
2483   case 'n':
2484     switch (look(1)) {
2485     case 'a':
2486       First += 2;
2487       return make<NameType>("operator new[]");
2488     case 'e':
2489       First += 2;
2490       return make<NameType>("operator!=");
2491     case 'g':
2492       First += 2;
2493       return make<NameType>("operator-");
2494     case 't':
2495       First += 2;
2496       return make<NameType>("operator!");
2497     case 'w':
2498       First += 2;
2499       return make<NameType>("operator new");
2500     }
2501     return nullptr;
2502   case 'o':
2503     switch (look(1)) {
2504     case 'o':
2505       First += 2;
2506       return make<NameType>("operator||");
2507     case 'r':
2508       First += 2;
2509       return make<NameType>("operator|");
2510     case 'R':
2511       First += 2;
2512       return make<NameType>("operator|=");
2513     }
2514     return nullptr;
2515   case 'p':
2516     switch (look(1)) {
2517     case 'm':
2518       First += 2;
2519       return make<NameType>("operator->*");
2520     case 'l':
2521       First += 2;
2522       return make<NameType>("operator+");
2523     case 'L':
2524       First += 2;
2525       return make<NameType>("operator+=");
2526     case 'p':
2527       First += 2;
2528       return make<NameType>("operator++");
2529     case 's':
2530       First += 2;
2531       return make<NameType>("operator+");
2532     case 't':
2533       First += 2;
2534       return make<NameType>("operator->");
2535     }
2536     return nullptr;
2537   case 'q':
2538     if (look(1) == 'u') {
2539       First += 2;
2540       return make<NameType>("operator?");
2541     }
2542     return nullptr;
2543   case 'r':
2544     switch (look(1)) {
2545     case 'm':
2546       First += 2;
2547       return make<NameType>("operator%");
2548     case 'M':
2549       First += 2;
2550       return make<NameType>("operator%=");
2551     case 's':
2552       First += 2;
2553       return make<NameType>("operator>>");
2554     case 'S':
2555       First += 2;
2556       return make<NameType>("operator>>=");
2557     }
2558     return nullptr;
2559   case 's':
2560     if (look(1) == 's') {
2561       First += 2;
2562       return make<NameType>("operator<=>");
2563     }
2564     return nullptr;
2565   // ::= v <digit> <source-name>        # vendor extended operator
2566   case 'v':
2567     if (std::isdigit(look(1))) {
2568       First += 2;
2569       Node *SN = parseSourceName(State);
2570       if (SN == nullptr)
2571         return nullptr;
2572       return make<ConversionOperatorType>(SN);
2573     }
2574     return nullptr;
2575   }
2576   return nullptr;
2577 }
2578 
2579 // <ctor-dtor-name> ::= C1  # complete object constructor
2580 //                  ::= C2  # base object constructor
2581 //                  ::= C3  # complete object allocating constructor
2582 //   extension      ::= C5    # ?
2583 //                  ::= D0  # deleting destructor
2584 //                  ::= D1  # complete object destructor
2585 //                  ::= D2  # base object destructor
2586 //   extension      ::= D5    # ?
2587 Node *Db::parseCtorDtorName(Node *&SoFar, NameState *State) {
2588   if (SoFar->K == Node::KSpecialSubstitution) {
2589     auto SSK = static_cast<SpecialSubstitution *>(SoFar)->SSK;
2590     switch (SSK) {
2591     case SpecialSubKind::string:
2592     case SpecialSubKind::istream:
2593     case SpecialSubKind::ostream:
2594     case SpecialSubKind::iostream:
2595       SoFar = make<ExpandedSpecialSubstitution>(SSK);
2596     default:
2597       break;
2598     }
2599   }
2600 
2601   if (consumeIf('C')) {
2602     bool IsInherited = consumeIf('I');
2603     if (look() != '1' && look() != '2' && look() != '3' && look() != '5')
2604       return nullptr;
2605     ++First;
2606     if (State) State->CtorDtorConversion = true;
2607     if (IsInherited) {
2608       if (parseName() == nullptr)
2609         return nullptr;
2610     }
2611     return make<CtorDtorName>(SoFar, false);
2612   }
2613 
2614   if (look() == 'D' &&
2615       (look(1) == '0' || look(1) == '1' || look(1) == '2' || look(1) == '5')) {
2616     First += 2;
2617     if (State) State->CtorDtorConversion = true;
2618     return make<CtorDtorName>(SoFar, true);
2619   }
2620 
2621   return nullptr;
2622 }
2623 
2624 // <nested-name> ::= N [<CV-Qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
2625 //               ::= N [<CV-Qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
2626 //
2627 // <prefix> ::= <prefix> <unqualified-name>
2628 //          ::= <template-prefix> <template-args>
2629 //          ::= <template-param>
2630 //          ::= <decltype>
2631 //          ::= # empty
2632 //          ::= <substitution>
2633 //          ::= <prefix> <data-member-prefix>
2634 //  extension ::= L
2635 //
2636 // <template-prefix> ::= <prefix> <template unqualified-name>
2637 //                   ::= <template-param>
2638 //                   ::= <substitution>
2639 Node *Db::parseNestedName(NameState *State) {
2640   if (!consumeIf('N'))
2641     return nullptr;
2642 
2643   Qualifiers CVTmp = parseCVQualifiers();
2644   if (State) State->CVQualifiers = CVTmp;
2645 
2646   if (consumeIf('O')) {
2647     if (State) State->ReferenceQualifier = FrefQualRValue;
2648   } else if (consumeIf('R')) {
2649     if (State) State->ReferenceQualifier = FrefQualLValue;
2650   } else
2651     if (State) State->ReferenceQualifier = FrefQualNone;
2652 
2653   Node *SoFar = nullptr;
2654   auto PushComponent = [&](Node *Comp) {
2655     if (SoFar) SoFar = make<QualifiedName>(SoFar, Comp);
2656     else       SoFar = Comp;
2657     if (State) State->EndsWithTemplateArgs = false;
2658   };
2659 
2660   if (consumeIf("St"))
2661     SoFar = make<NameType>("std");
2662 
2663   while (!consumeIf('E')) {
2664     consumeIf('L'); // extension
2665 
2666     //          ::= <template-param>
2667     if (look() == 'T') {
2668       Node *TP = parseTemplateParam();
2669       if (TP == nullptr)
2670         return nullptr;
2671       PushComponent(TP);
2672       Subs.push_back(SoFar);
2673       continue;
2674     }
2675 
2676     //          ::= <template-prefix> <template-args>
2677     if (look() == 'I') {
2678       Node *TA = parseTemplateArgs();
2679       if (TA == nullptr || SoFar == nullptr)
2680         return nullptr;
2681       SoFar = make<NameWithTemplateArgs>(SoFar, TA);
2682       if (State) State->EndsWithTemplateArgs = true;
2683       Subs.push_back(SoFar);
2684       continue;
2685     }
2686 
2687     //          ::= <decltype>
2688     if (look() == 'D' && (look(1) == 't' || look(1) == 'T')) {
2689       Node *DT = parseDecltype();
2690       if (DT == nullptr)
2691         return nullptr;
2692       PushComponent(DT);
2693       Subs.push_back(SoFar);
2694       continue;
2695     }
2696 
2697     //          ::= <substitution>
2698     if (look() == 'S' && look(1) != 't') {
2699       Node *S = parseSubstitution();
2700       if (S == nullptr)
2701         return nullptr;
2702       PushComponent(S);
2703       if (SoFar != S)
2704         Subs.push_back(S);
2705       continue;
2706     }
2707 
2708     // Parse an <unqualified-name> thats actually a <ctor-dtor-name>.
2709     if (look() == 'C' || (look() == 'D' && look(1) != 'C')) {
2710       if (SoFar == nullptr)
2711         return nullptr;
2712       Node *CtorDtor = parseCtorDtorName(SoFar, State);
2713       if (CtorDtor == nullptr)
2714         return nullptr;
2715       PushComponent(CtorDtor);
2716       SoFar = parseAbiTags(SoFar);
2717       if (SoFar == nullptr)
2718         return nullptr;
2719       Subs.push_back(SoFar);
2720       continue;
2721     }
2722 
2723     //          ::= <prefix> <unqualified-name>
2724     Node *N = parseUnqualifiedName(State);
2725     if (N == nullptr)
2726       return nullptr;
2727     PushComponent(N);
2728     Subs.push_back(SoFar);
2729   }
2730 
2731   if (SoFar == nullptr || Subs.empty())
2732     return nullptr;
2733 
2734   Subs.pop_back();
2735   return SoFar;
2736 }
2737 
2738 // <simple-id> ::= <source-name> [ <template-args> ]
2739 Node *Db::parseSimpleId() {
2740   Node *SN = parseSourceName(/*NameState=*/nullptr);
2741   if (SN == nullptr)
2742     return nullptr;
2743   if (look() == 'I') {
2744     Node *TA = parseTemplateArgs();
2745     if (TA == nullptr)
2746       return nullptr;
2747     return make<NameWithTemplateArgs>(SN, TA);
2748   }
2749   return SN;
2750 }
2751 
2752 // <destructor-name> ::= <unresolved-type>  # e.g., ~T or ~decltype(f())
2753 //                   ::= <simple-id>        # e.g., ~A<2*N>
2754 Node *Db::parseDestructorName() {
2755   Node *Result;
2756   if (std::isdigit(look()))
2757     Result = parseSimpleId();
2758   else
2759     Result = parseUnresolvedType();
2760   if (Result == nullptr)
2761     return nullptr;
2762   return make<DtorName>(Result);
2763 }
2764 
2765 // <unresolved-type> ::= <template-param>
2766 //                   ::= <decltype>
2767 //                   ::= <substitution>
2768 Node *Db::parseUnresolvedType() {
2769   if (look() == 'T') {
2770     Node *TP = parseTemplateParam();
2771     if (TP == nullptr)
2772       return nullptr;
2773     Subs.push_back(TP);
2774     return TP;
2775   }
2776   if (look() == 'D') {
2777     Node *DT = parseDecltype();
2778     if (DT == nullptr)
2779       return nullptr;
2780     Subs.push_back(DT);
2781     return DT;
2782   }
2783   return parseSubstitution();
2784 }
2785 
2786 // <base-unresolved-name> ::= <simple-id>                                # unresolved name
2787 //          extension     ::= <operator-name>                            # unresolved operator-function-id
2788 //          extension     ::= <operator-name> <template-args>            # unresolved operator template-id
2789 //                        ::= on <operator-name>                         # unresolved operator-function-id
2790 //                        ::= on <operator-name> <template-args>         # unresolved operator template-id
2791 //                        ::= dn <destructor-name>                       # destructor or pseudo-destructor;
2792 //                                                                         # e.g. ~X or ~X<N-1>
2793 Node *Db::parseBaseUnresolvedName() {
2794   if (std::isdigit(look()))
2795     return parseSimpleId();
2796 
2797   if (consumeIf("dn"))
2798     return parseDestructorName();
2799 
2800   consumeIf("on");
2801 
2802   Node *Oper = parseOperatorName(/*NameState=*/nullptr);
2803   if (Oper == nullptr)
2804     return nullptr;
2805   if (look() == 'I') {
2806     Node *TA = parseTemplateArgs();
2807     if (TA == nullptr)
2808       return nullptr;
2809     return make<NameWithTemplateArgs>(Oper, TA);
2810   }
2811   return Oper;
2812 }
2813 
2814 // <unresolved-name>
2815 //  extension        ::= srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
2816 //                   ::= [gs] <base-unresolved-name>                     # x or (with "gs") ::x
2817 //                   ::= [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
2818 //                                                                       # A::x, N::y, A<T>::z; "gs" means leading "::"
2819 //                   ::= sr <unresolved-type> <base-unresolved-name>     # T::x / decltype(p)::x
2820 //  extension        ::= sr <unresolved-type> <template-args> <base-unresolved-name>
2821 //                                                                       # T::N::x /decltype(p)::N::x
2822 //  (ignored)        ::= srN <unresolved-type>  <unresolved-qualifier-level>+ E <base-unresolved-name>
2823 //
2824 // <unresolved-qualifier-level> ::= <simple-id>
2825 Node *Db::parseUnresolvedName() {
2826   Node *SoFar = nullptr;
2827 
2828   // srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
2829   // srN <unresolved-type>                   <unresolved-qualifier-level>+ E <base-unresolved-name>
2830   if (consumeIf("srN")) {
2831     SoFar = parseUnresolvedType();
2832     if (SoFar == nullptr)
2833       return nullptr;
2834 
2835     if (look() == 'I') {
2836       Node *TA = parseTemplateArgs();
2837       if (TA == nullptr)
2838         return nullptr;
2839       SoFar = make<NameWithTemplateArgs>(SoFar, TA);
2840     }
2841 
2842     while (!consumeIf('E')) {
2843       Node *Qual = parseSimpleId();
2844       if (Qual == nullptr)
2845         return nullptr;
2846       SoFar = make<QualifiedName>(SoFar, Qual);
2847     }
2848 
2849     Node *Base = parseBaseUnresolvedName();
2850     if (Base == nullptr)
2851       return nullptr;
2852     return make<QualifiedName>(SoFar, Base);
2853   }
2854 
2855   bool Global = consumeIf("gs");
2856 
2857   // [gs] <base-unresolved-name>                     # x or (with "gs") ::x
2858   if (!consumeIf("sr")) {
2859     SoFar = parseBaseUnresolvedName();
2860     if (SoFar == nullptr)
2861       return nullptr;
2862     if (Global)
2863       SoFar = make<GlobalQualifiedName>(SoFar);
2864     return SoFar;
2865   }
2866 
2867   // [gs] sr <unresolved-qualifier-level>+ E   <base-unresolved-name>
2868   if (std::isdigit(look())) {
2869     do {
2870       Node *Qual = parseSimpleId();
2871       if (Qual == nullptr)
2872         return nullptr;
2873       if (SoFar)
2874         SoFar = make<QualifiedName>(SoFar, Qual);
2875       else if (Global)
2876         SoFar = make<GlobalQualifiedName>(Qual);
2877       else
2878         SoFar = Qual;
2879     } while (!consumeIf('E'));
2880   }
2881   //      sr <unresolved-type>                 <base-unresolved-name>
2882   //      sr <unresolved-type> <template-args> <base-unresolved-name>
2883   else {
2884     SoFar = parseUnresolvedType();
2885     if (SoFar == nullptr)
2886       return nullptr;
2887 
2888     if (look() == 'I') {
2889       Node *TA = parseTemplateArgs();
2890       if (TA == nullptr)
2891         return nullptr;
2892       SoFar = make<NameWithTemplateArgs>(SoFar, TA);
2893     }
2894   }
2895 
2896   assert(SoFar != nullptr);
2897 
2898   Node *Base = parseBaseUnresolvedName();
2899   if (Base == nullptr)
2900     return nullptr;
2901   return make<QualifiedName>(SoFar, Base);
2902 }
2903 
2904 // <abi-tags> ::= <abi-tag> [<abi-tags>]
2905 // <abi-tag> ::= B <source-name>
2906 Node *Db::parseAbiTags(Node *N) {
2907   while (consumeIf('B')) {
2908     StringView SN = parseBareSourceName();
2909     if (SN.empty())
2910       return nullptr;
2911     N = make<AbiTagAttr>(N, SN);
2912   }
2913   return N;
2914 }
2915 
2916 // <number> ::= [n] <non-negative decimal integer>
2917 StringView Db::parseNumber(bool AllowNegative) {
2918   const char *Tmp = First;
2919   if (AllowNegative)
2920     consumeIf('n');
2921   if (numLeft() == 0 || !std::isdigit(*First))
2922     return StringView();
2923   while (numLeft() != 0 && std::isdigit(*First))
2924     ++First;
2925   return StringView(Tmp, First);
2926 }
2927 
2928 // <positive length number> ::= [0-9]*
2929 bool Db::parsePositiveInteger(size_t *Out) {
2930   *Out = 0;
2931   if (look() < '0' || look() > '9')
2932     return true;
2933   while (look() >= '0' && look() <= '9') {
2934     *Out *= 10;
2935     *Out += static_cast<size_t>(consume() - '0');
2936   }
2937   return false;
2938 }
2939 
2940 StringView Db::parseBareSourceName() {
2941   size_t Int = 0;
2942   if (parsePositiveInteger(&Int) || numLeft() < Int)
2943     return StringView();
2944   StringView R(First, First + Int);
2945   First += Int;
2946   return R;
2947 }
2948 
2949 // <function-type> ::= [<CV-qualifiers>] [<exception-spec>] [Dx] F [Y] <bare-function-type> [<ref-qualifier>] E
2950 //
2951 // <exception-spec> ::= Do                # non-throwing exception-specification (e.g., noexcept, throw())
2952 //                  ::= DO <expression> E # computed (instantiation-dependent) noexcept
2953 //                  ::= Dw <type>+ E      # dynamic exception specification with instantiation-dependent types
2954 //
2955 // <ref-qualifier> ::= R                   # & ref-qualifier
2956 // <ref-qualifier> ::= O                   # && ref-qualifier
2957 Node *Db::parseFunctionType() {
2958   Qualifiers CVQuals = parseCVQualifiers();
2959 
2960   Node *ExceptionSpec = nullptr;
2961   if (consumeIf("Do")) {
2962     ExceptionSpec = make<NameType>("noexcept");
2963   } else if (consumeIf("DO")) {
2964     Node *E = parseExpr();
2965     if (E == nullptr || !consumeIf('E'))
2966       return nullptr;
2967     ExceptionSpec = make<NoexceptSpec>(E);
2968   } else if (consumeIf("Dw")) {
2969     size_t SpecsBegin = Names.size();
2970     while (!consumeIf('E')) {
2971       Node *T = parseType();
2972       if (T == nullptr)
2973         return nullptr;
2974       Names.push_back(T);
2975     }
2976     ExceptionSpec =
2977       make<DynamicExceptionSpec>(popTrailingNodeArray(SpecsBegin));
2978   }
2979 
2980   consumeIf("Dx"); // transaction safe
2981 
2982   if (!consumeIf('F'))
2983     return nullptr;
2984   consumeIf('Y'); // extern "C"
2985   Node *ReturnType = parseType();
2986   if (ReturnType == nullptr)
2987     return nullptr;
2988 
2989   FunctionRefQual ReferenceQualifier = FrefQualNone;
2990   size_t ParamsBegin = Names.size();
2991   while (true) {
2992     if (consumeIf('E'))
2993       break;
2994     if (consumeIf('v'))
2995       continue;
2996     if (consumeIf("RE")) {
2997       ReferenceQualifier = FrefQualLValue;
2998       break;
2999     }
3000     if (consumeIf("OE")) {
3001       ReferenceQualifier = FrefQualRValue;
3002       break;
3003     }
3004     Node *T = parseType();
3005     if (T == nullptr)
3006       return nullptr;
3007     Names.push_back(T);
3008   }
3009 
3010   NodeArray Params = popTrailingNodeArray(ParamsBegin);
3011   return make<FunctionType>(ReturnType, Params, CVQuals,
3012                             ReferenceQualifier, ExceptionSpec);
3013 }
3014 
3015 // extension:
3016 // <vector-type>           ::= Dv <positive dimension number> _ <extended element type>
3017 //                         ::= Dv [<dimension expression>] _ <element type>
3018 // <extended element type> ::= <element type>
3019 //                         ::= p # AltiVec vector pixel
3020 Node *Db::parseVectorType() {
3021   if (!consumeIf("Dv"))
3022     return nullptr;
3023   if (look() >= '1' && look() <= '9') {
3024     StringView DimensionNumber = parseNumber();
3025     if (!consumeIf('_'))
3026       return nullptr;
3027     if (consumeIf('p'))
3028       return make<VectorType>(DimensionNumber);
3029     Node *ElemType = parseType();
3030     if (ElemType == nullptr)
3031       return nullptr;
3032     return make<VectorType>(ElemType, DimensionNumber);
3033   }
3034 
3035   if (!consumeIf('_')) {
3036     Node *DimExpr = parseExpr();
3037     if (!DimExpr)
3038       return nullptr;
3039     if (!consumeIf('_'))
3040       return nullptr;
3041     Node *ElemType = parseType();
3042     if (!ElemType)
3043       return nullptr;
3044     return make<VectorType>(ElemType, DimExpr);
3045   }
3046   Node *ElemType = parseType();
3047   if (!ElemType)
3048     return nullptr;
3049   return make<VectorType>(ElemType, StringView());
3050 }
3051 
3052 // <decltype>  ::= Dt <expression> E  # decltype of an id-expression or class member access (C++0x)
3053 //             ::= DT <expression> E  # decltype of an expression (C++0x)
3054 Node *Db::parseDecltype() {
3055   if (!consumeIf('D'))
3056     return nullptr;
3057   if (!consumeIf('t') && !consumeIf('T'))
3058     return nullptr;
3059   Node *E = parseExpr();
3060   if (E == nullptr)
3061     return nullptr;
3062   if (!consumeIf('E'))
3063     return nullptr;
3064   return make<EnclosingExpr>("decltype(", E, ")");
3065 }
3066 
3067 // <array-type> ::= A <positive dimension number> _ <element type>
3068 //              ::= A [<dimension expression>] _ <element type>
3069 Node *Db::parseArrayType() {
3070   if (!consumeIf('A'))
3071     return nullptr;
3072 
3073   if (std::isdigit(look())) {
3074     StringView Dimension = parseNumber();
3075     if (!consumeIf('_'))
3076       return nullptr;
3077     Node *Ty = parseType();
3078     if (Ty == nullptr)
3079       return nullptr;
3080     return make<ArrayType>(Ty, Dimension);
3081   }
3082 
3083   if (!consumeIf('_')) {
3084     Node *DimExpr = parseExpr();
3085     if (DimExpr == nullptr)
3086       return nullptr;
3087     if (!consumeIf('_'))
3088       return nullptr;
3089     Node *ElementType = parseType();
3090     if (ElementType == nullptr)
3091       return nullptr;
3092     return make<ArrayType>(ElementType, DimExpr);
3093   }
3094 
3095   Node *Ty = parseType();
3096   if (Ty == nullptr)
3097     return nullptr;
3098   return make<ArrayType>(Ty);
3099 }
3100 
3101 // <pointer-to-member-type> ::= M <class type> <member type>
3102 Node *Db::parsePointerToMemberType() {
3103   if (!consumeIf('M'))
3104     return nullptr;
3105   Node *ClassType = parseType();
3106   if (ClassType == nullptr)
3107     return nullptr;
3108   Node *MemberType = parseType();
3109   if (MemberType == nullptr)
3110     return nullptr;
3111   return make<PointerToMemberType>(ClassType, MemberType);
3112 }
3113 
3114 // <class-enum-type> ::= <name>     # non-dependent type name, dependent type name, or dependent typename-specifier
3115 //                   ::= Ts <name>  # dependent elaborated type specifier using 'struct' or 'class'
3116 //                   ::= Tu <name>  # dependent elaborated type specifier using 'union'
3117 //                   ::= Te <name>  # dependent elaborated type specifier using 'enum'
3118 Node *Db::parseClassEnumType() {
3119   StringView ElabSpef;
3120   if (consumeIf("Ts"))
3121     ElabSpef = "struct";
3122   else if (consumeIf("Tu"))
3123     ElabSpef = "union";
3124   else if (consumeIf("Te"))
3125     ElabSpef = "enum";
3126 
3127   Node *Name = parseName();
3128   if (Name == nullptr)
3129     return nullptr;
3130 
3131   if (!ElabSpef.empty())
3132     return make<ElaboratedTypeSpefType>(ElabSpef, Name);
3133 
3134   return Name;
3135 }
3136 
3137 // <qualified-type>     ::= <qualifiers> <type>
3138 // <qualifiers> ::= <extended-qualifier>* <CV-qualifiers>
3139 // <extended-qualifier> ::= U <source-name> [<template-args>] # vendor extended type qualifier
3140 Node *Db::parseQualifiedType() {
3141   if (consumeIf('U')) {
3142     StringView Qual = parseBareSourceName();
3143     if (Qual.empty())
3144       return nullptr;
3145 
3146     // FIXME parse the optional <template-args> here!
3147 
3148     // extension            ::= U <objc-name> <objc-type>  # objc-type<identifier>
3149     if (Qual.startsWith("objcproto")) {
3150       StringView ProtoSourceName = Qual.dropFront(std::strlen("objcproto"));
3151       StringView Proto;
3152       {
3153         SwapAndRestore<const char *> SaveFirst(First, ProtoSourceName.begin()),
3154                                      SaveLast(Last, ProtoSourceName.end());
3155         Proto = parseBareSourceName();
3156       }
3157       if (Proto.empty())
3158         return nullptr;
3159       Node *Child = parseQualifiedType();
3160       if (Child == nullptr)
3161         return nullptr;
3162       return make<ObjCProtoName>(Child, Proto);
3163     }
3164 
3165     Node *Child = parseQualifiedType();
3166     if (Child == nullptr)
3167       return nullptr;
3168     return make<VendorExtQualType>(Child, Qual);
3169   }
3170 
3171   Qualifiers Quals = parseCVQualifiers();
3172   Node *Ty = parseType();
3173   if (Ty == nullptr)
3174     return nullptr;
3175   if (Quals != QualNone)
3176     Ty = make<QualType>(Ty, Quals);
3177   return Ty;
3178 }
3179 
3180 // <type>      ::= <builtin-type>
3181 //             ::= <qualified-type>
3182 //             ::= <function-type>
3183 //             ::= <class-enum-type>
3184 //             ::= <array-type>
3185 //             ::= <pointer-to-member-type>
3186 //             ::= <template-param>
3187 //             ::= <template-template-param> <template-args>
3188 //             ::= <decltype>
3189 //             ::= P <type>        # pointer
3190 //             ::= R <type>        # l-value reference
3191 //             ::= O <type>        # r-value reference (C++11)
3192 //             ::= C <type>        # complex pair (C99)
3193 //             ::= G <type>        # imaginary (C99)
3194 //             ::= <substitution>  # See Compression below
3195 // extension   ::= U <objc-name> <objc-type>  # objc-type<identifier>
3196 // extension   ::= <vector-type> # <vector-type> starts with Dv
3197 //
3198 // <objc-name> ::= <k0 number> objcproto <k1 number> <identifier>  # k0 = 9 + <number of digits in k1> + k1
3199 // <objc-type> ::= <source-name>  # PU<11+>objcproto 11objc_object<source-name> 11objc_object -> id<source-name>
3200 Node *Db::parseType() {
3201   Node *Result = nullptr;
3202 
3203   switch (look()) {
3204   //             ::= <qualified-type>
3205   case 'r':
3206   case 'V':
3207   case 'K': {
3208     unsigned AfterQuals = 0;
3209     if (look(AfterQuals) == 'r') ++AfterQuals;
3210     if (look(AfterQuals) == 'V') ++AfterQuals;
3211     if (look(AfterQuals) == 'K') ++AfterQuals;
3212 
3213     if (look(AfterQuals) == 'F' ||
3214         (look(AfterQuals) == 'D' &&
3215          (look(AfterQuals + 1) == 'o' || look(AfterQuals + 1) == 'O' ||
3216           look(AfterQuals + 1) == 'w' || look(AfterQuals + 1) == 'x'))) {
3217       Result = parseFunctionType();
3218       break;
3219     }
3220     LLVM_FALLTHROUGH;
3221   }
3222   case 'U': {
3223     Result = parseQualifiedType();
3224     break;
3225   }
3226   // <builtin-type> ::= v    # void
3227   case 'v':
3228     ++First;
3229     return make<NameType>("void");
3230   //                ::= w    # wchar_t
3231   case 'w':
3232     ++First;
3233     return make<NameType>("wchar_t");
3234   //                ::= b    # bool
3235   case 'b':
3236     ++First;
3237     return make<NameType>("bool");
3238   //                ::= c    # char
3239   case 'c':
3240     ++First;
3241     return make<NameType>("char");
3242   //                ::= a    # signed char
3243   case 'a':
3244     ++First;
3245     return make<NameType>("signed char");
3246   //                ::= h    # unsigned char
3247   case 'h':
3248     ++First;
3249     return make<NameType>("unsigned char");
3250   //                ::= s    # short
3251   case 's':
3252     ++First;
3253     return make<NameType>("short");
3254   //                ::= t    # unsigned short
3255   case 't':
3256     ++First;
3257     return make<NameType>("unsigned short");
3258   //                ::= i    # int
3259   case 'i':
3260     ++First;
3261     return make<NameType>("int");
3262   //                ::= j    # unsigned int
3263   case 'j':
3264     ++First;
3265     return make<NameType>("unsigned int");
3266   //                ::= l    # long
3267   case 'l':
3268     ++First;
3269     return make<NameType>("long");
3270   //                ::= m    # unsigned long
3271   case 'm':
3272     ++First;
3273     return make<NameType>("unsigned long");
3274   //                ::= x    # long long, __int64
3275   case 'x':
3276     ++First;
3277     return make<NameType>("long long");
3278   //                ::= y    # unsigned long long, __int64
3279   case 'y':
3280     ++First;
3281     return make<NameType>("unsigned long long");
3282   //                ::= n    # __int128
3283   case 'n':
3284     ++First;
3285     return make<NameType>("__int128");
3286   //                ::= o    # unsigned __int128
3287   case 'o':
3288     ++First;
3289     return make<NameType>("unsigned __int128");
3290   //                ::= f    # float
3291   case 'f':
3292     ++First;
3293     return make<NameType>("float");
3294   //                ::= d    # double
3295   case 'd':
3296     ++First;
3297     return make<NameType>("double");
3298   //                ::= e    # long double, __float80
3299   case 'e':
3300     ++First;
3301     return make<NameType>("long double");
3302   //                ::= g    # __float128
3303   case 'g':
3304     ++First;
3305     return make<NameType>("__float128");
3306   //                ::= z    # ellipsis
3307   case 'z':
3308     ++First;
3309     return make<NameType>("...");
3310 
3311   // <builtin-type> ::= u <source-name>    # vendor extended type
3312   case 'u': {
3313     ++First;
3314     StringView Res = parseBareSourceName();
3315     if (Res.empty())
3316       return nullptr;
3317     return make<NameType>(Res);
3318   }
3319   case 'D':
3320     switch (look(1)) {
3321     //                ::= Dd   # IEEE 754r decimal floating point (64 bits)
3322     case 'd':
3323       First += 2;
3324       return make<NameType>("decimal64");
3325     //                ::= De   # IEEE 754r decimal floating point (128 bits)
3326     case 'e':
3327       First += 2;
3328       return make<NameType>("decimal128");
3329     //                ::= Df   # IEEE 754r decimal floating point (32 bits)
3330     case 'f':
3331       First += 2;
3332       return make<NameType>("decimal32");
3333     //                ::= Dh   # IEEE 754r half-precision floating point (16 bits)
3334     case 'h':
3335       First += 2;
3336       return make<NameType>("decimal16");
3337     //                ::= Di   # char32_t
3338     case 'i':
3339       First += 2;
3340       return make<NameType>("char32_t");
3341     //                ::= Ds   # char16_t
3342     case 's':
3343       First += 2;
3344       return make<NameType>("char16_t");
3345     //                ::= Da   # auto (in dependent new-expressions)
3346     case 'a':
3347       First += 2;
3348       return make<NameType>("auto");
3349     //                ::= Dc   # decltype(auto)
3350     case 'c':
3351       First += 2;
3352       return make<NameType>("decltype(auto)");
3353     //                ::= Dn   # std::nullptr_t (i.e., decltype(nullptr))
3354     case 'n':
3355       First += 2;
3356       return make<NameType>("std::nullptr_t");
3357 
3358     //             ::= <decltype>
3359     case 't':
3360     case 'T': {
3361       Result = parseDecltype();
3362       break;
3363     }
3364     // extension   ::= <vector-type> # <vector-type> starts with Dv
3365     case 'v': {
3366       Result = parseVectorType();
3367       break;
3368     }
3369     //           ::= Dp <type>       # pack expansion (C++0x)
3370     case 'p': {
3371       First += 2;
3372       Node *Child = parseType();
3373       if (!Child)
3374         return nullptr;
3375       Result = make<ParameterPackExpansion>(Child);
3376       break;
3377     }
3378     // Exception specifier on a function type.
3379     case 'o':
3380     case 'O':
3381     case 'w':
3382     // Transaction safe function type.
3383     case 'x':
3384       Result = parseFunctionType();
3385       break;
3386     }
3387     break;
3388   //             ::= <function-type>
3389   case 'F': {
3390     Result = parseFunctionType();
3391     break;
3392   }
3393   //             ::= <array-type>
3394   case 'A': {
3395     Result = parseArrayType();
3396     break;
3397   }
3398   //             ::= <pointer-to-member-type>
3399   case 'M': {
3400     Result = parsePointerToMemberType();
3401     break;
3402   }
3403   //             ::= <template-param>
3404   case 'T': {
3405     // This could be an elaborate type specifier on a <class-enum-type>.
3406     if (look(1) == 's' || look(1) == 'u' || look(1) == 'e') {
3407       Result = parseClassEnumType();
3408       break;
3409     }
3410 
3411     Result = parseTemplateParam();
3412     if (Result == nullptr)
3413       return nullptr;
3414 
3415     // Result could be either of:
3416     //   <type>        ::= <template-param>
3417     //   <type>        ::= <template-template-param> <template-args>
3418     //
3419     //   <template-template-param> ::= <template-param>
3420     //                             ::= <substitution>
3421     //
3422     // If this is followed by some <template-args>, and we're permitted to
3423     // parse them, take the second production.
3424 
3425     if (TryToParseTemplateArgs && look() == 'I') {
3426       Node *TA = parseTemplateArgs();
3427       if (TA == nullptr)
3428         return nullptr;
3429       Result = make<NameWithTemplateArgs>(Result, TA);
3430     }
3431     break;
3432   }
3433   //             ::= P <type>        # pointer
3434   case 'P': {
3435     ++First;
3436     Node *Ptr = parseType();
3437     if (Ptr == nullptr)
3438       return nullptr;
3439     Result = make<PointerType>(Ptr);
3440     break;
3441   }
3442   //             ::= R <type>        # l-value reference
3443   case 'R': {
3444     ++First;
3445     Node *Ref = parseType();
3446     if (Ref == nullptr)
3447       return nullptr;
3448     Result = make<LValueReferenceType>(Ref);
3449     break;
3450   }
3451   //             ::= O <type>        # r-value reference (C++11)
3452   case 'O': {
3453     ++First;
3454     Node *Ref = parseType();
3455     if (Ref == nullptr)
3456       return nullptr;
3457     Result = make<RValueReferenceType>(Ref);
3458     break;
3459   }
3460   //             ::= C <type>        # complex pair (C99)
3461   case 'C': {
3462     ++First;
3463     Node *P = parseType();
3464     if (P == nullptr)
3465       return nullptr;
3466     Result = make<PostfixQualifiedType>(P, " complex");
3467     break;
3468   }
3469   //             ::= G <type>        # imaginary (C99)
3470   case 'G': {
3471     ++First;
3472     Node *P = parseType();
3473     if (P == nullptr)
3474       return P;
3475     Result = make<PostfixQualifiedType>(P, " imaginary");
3476     break;
3477   }
3478   //             ::= <substitution>  # See Compression below
3479   case 'S': {
3480     if (look(1) && look(1) != 't') {
3481       Node *Sub = parseSubstitution();
3482       if (Sub == nullptr)
3483         return nullptr;
3484 
3485       // Sub could be either of:
3486       //   <type>        ::= <substitution>
3487       //   <type>        ::= <template-template-param> <template-args>
3488       //
3489       //   <template-template-param> ::= <template-param>
3490       //                             ::= <substitution>
3491       //
3492       // If this is followed by some <template-args>, and we're permitted to
3493       // parse them, take the second production.
3494 
3495       if (TryToParseTemplateArgs && look() == 'I') {
3496         Node *TA = parseTemplateArgs();
3497         if (TA == nullptr)
3498           return nullptr;
3499         Result = make<NameWithTemplateArgs>(Sub, TA);
3500         break;
3501       }
3502 
3503       // If all we parsed was a substitution, don't re-insert into the
3504       // substitution table.
3505       return Sub;
3506     }
3507     LLVM_FALLTHROUGH;
3508   }
3509   //        ::= <class-enum-type>
3510   default: {
3511     Result = parseClassEnumType();
3512     break;
3513   }
3514   }
3515 
3516   // If we parsed a type, insert it into the substitution table. Note that all
3517   // <builtin-type>s and <substitution>s have already bailed out, because they
3518   // don't get substitutions.
3519   if (Result != nullptr)
3520     Subs.push_back(Result);
3521   return Result;
3522 }
3523 
3524 Node *Db::parsePrefixExpr(StringView Kind) {
3525   Node *E = parseExpr();
3526   if (E == nullptr)
3527     return nullptr;
3528   return make<PrefixExpr>(Kind, E);
3529 }
3530 
3531 Node *Db::parseBinaryExpr(StringView Kind) {
3532   Node *LHS = parseExpr();
3533   if (LHS == nullptr)
3534     return nullptr;
3535   Node *RHS = parseExpr();
3536   if (RHS == nullptr)
3537     return nullptr;
3538   return make<BinaryExpr>(LHS, Kind, RHS);
3539 }
3540 
3541 Node *Db::parseIntegerLiteral(StringView Lit) {
3542   StringView Tmp = parseNumber(true);
3543   if (!Tmp.empty() && consumeIf('E'))
3544     return make<IntegerExpr>(Lit, Tmp);
3545   return nullptr;
3546 }
3547 
3548 // <CV-Qualifiers> ::= [r] [V] [K]
3549 Qualifiers Db::parseCVQualifiers() {
3550   Qualifiers CVR = QualNone;
3551   if (consumeIf('r'))
3552     addQualifiers(CVR, QualRestrict);
3553   if (consumeIf('V'))
3554     addQualifiers(CVR, QualVolatile);
3555   if (consumeIf('K'))
3556     addQualifiers(CVR, QualConst);
3557   return CVR;
3558 }
3559 
3560 // <function-param> ::= fp <top-level CV-Qualifiers> _                                     # L == 0, first parameter
3561 //                  ::= fp <top-level CV-Qualifiers> <parameter-2 non-negative number> _   # L == 0, second and later parameters
3562 //                  ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> _         # L > 0, first parameter
3563 //                  ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> <parameter-2 non-negative number> _   # L > 0, second and later parameters
3564 Node *Db::parseFunctionParam() {
3565   if (consumeIf("fp")) {
3566     parseCVQualifiers();
3567     StringView Num = parseNumber();
3568     if (!consumeIf('_'))
3569       return nullptr;
3570     return make<FunctionParam>(Num);
3571   }
3572   if (consumeIf("fL")) {
3573     if (parseNumber().empty())
3574       return nullptr;
3575     if (!consumeIf('p'))
3576       return nullptr;
3577     parseCVQualifiers();
3578     StringView Num = parseNumber();
3579     if (!consumeIf('_'))
3580       return nullptr;
3581     return make<FunctionParam>(Num);
3582   }
3583   return nullptr;
3584 }
3585 
3586 // [gs] nw <expression>* _ <type> E                     # new (expr-list) type
3587 // [gs] nw <expression>* _ <type> <initializer>         # new (expr-list) type (init)
3588 // [gs] na <expression>* _ <type> E                     # new[] (expr-list) type
3589 // [gs] na <expression>* _ <type> <initializer>         # new[] (expr-list) type (init)
3590 // <initializer> ::= pi <expression>* E                 # parenthesized initialization
3591 Node *Db::parseNewExpr() {
3592   bool Global = consumeIf("gs");
3593   bool IsArray = look(1) == 'a';
3594   if (!consumeIf("nw") && !consumeIf("na"))
3595     return nullptr;
3596   size_t Exprs = Names.size();
3597   while (!consumeIf('_')) {
3598     Node *Ex = parseExpr();
3599     if (Ex == nullptr)
3600       return nullptr;
3601     Names.push_back(Ex);
3602   }
3603   NodeArray ExprList = popTrailingNodeArray(Exprs);
3604   Node *Ty = parseType();
3605   if (Ty == nullptr)
3606     return Ty;
3607   if (consumeIf("pi")) {
3608     size_t InitsBegin = Names.size();
3609     while (!consumeIf('E')) {
3610       Node *Init = parseExpr();
3611       if (Init == nullptr)
3612         return Init;
3613       Names.push_back(Init);
3614     }
3615     NodeArray Inits = popTrailingNodeArray(InitsBegin);
3616     return make<NewExpr>(ExprList, Ty, Inits, Global, IsArray);
3617   } else if (!consumeIf('E'))
3618     return nullptr;
3619   return make<NewExpr>(ExprList, Ty, NodeArray(), Global, IsArray);
3620 }
3621 
3622 // cv <type> <expression>                               # conversion with one argument
3623 // cv <type> _ <expression>* E                          # conversion with a different number of arguments
3624 Node *Db::parseConversionExpr() {
3625   if (!consumeIf("cv"))
3626     return nullptr;
3627   Node *Ty;
3628   {
3629     SwapAndRestore<bool> SaveTemp(TryToParseTemplateArgs, false);
3630     Ty = parseType();
3631   }
3632 
3633   if (Ty == nullptr)
3634     return nullptr;
3635 
3636   if (consumeIf('_')) {
3637     size_t ExprsBegin = Names.size();
3638     while (!consumeIf('E')) {
3639       Node *E = parseExpr();
3640       if (E == nullptr)
3641         return E;
3642       Names.push_back(E);
3643     }
3644     NodeArray Exprs = popTrailingNodeArray(ExprsBegin);
3645     return make<ConversionExpr>(Ty, Exprs);
3646   }
3647 
3648   Node *E[1] = {parseExpr()};
3649   if (E[0] == nullptr)
3650     return nullptr;
3651   return make<ConversionExpr>(Ty, makeNodeArray(E, E + 1));
3652 }
3653 
3654 // <expr-primary> ::= L <type> <value number> E                          # integer literal
3655 //                ::= L <type> <value float> E                           # floating literal
3656 //                ::= L <string type> E                                  # string literal
3657 //                ::= L <nullptr type> E                                 # nullptr literal (i.e., "LDnE")
3658 // FIXME:         ::= L <type> <real-part float> _ <imag-part float> E   # complex floating point literal (C 2000)
3659 //                ::= L <mangled-name> E                                 # external name
3660 Node *Db::parseExprPrimary() {
3661   if (!consumeIf('L'))
3662     return nullptr;
3663   switch (look()) {
3664   case 'w':
3665     ++First;
3666     return parseIntegerLiteral("wchar_t");
3667   case 'b':
3668     if (consumeIf("b0E"))
3669       return make<BoolExpr>(0);
3670     if (consumeIf("b1E"))
3671       return make<BoolExpr>(1);
3672     return nullptr;
3673   case 'c':
3674     ++First;
3675     return parseIntegerLiteral("char");
3676   case 'a':
3677     ++First;
3678     return parseIntegerLiteral("signed char");
3679   case 'h':
3680     ++First;
3681     return parseIntegerLiteral("unsigned char");
3682   case 's':
3683     ++First;
3684     return parseIntegerLiteral("short");
3685   case 't':
3686     ++First;
3687     return parseIntegerLiteral("unsigned short");
3688   case 'i':
3689     ++First;
3690     return parseIntegerLiteral("");
3691   case 'j':
3692     ++First;
3693     return parseIntegerLiteral("u");
3694   case 'l':
3695     ++First;
3696     return parseIntegerLiteral("l");
3697   case 'm':
3698     ++First;
3699     return parseIntegerLiteral("ul");
3700   case 'x':
3701     ++First;
3702     return parseIntegerLiteral("ll");
3703   case 'y':
3704     ++First;
3705     return parseIntegerLiteral("ull");
3706   case 'n':
3707     ++First;
3708     return parseIntegerLiteral("__int128");
3709   case 'o':
3710     ++First;
3711     return parseIntegerLiteral("unsigned __int128");
3712   case 'f':
3713     ++First;
3714     return parseFloatingLiteral<float>();
3715   case 'd':
3716     ++First;
3717     return parseFloatingLiteral<double>();
3718   case 'e':
3719     ++First;
3720     return parseFloatingLiteral<long double>();
3721   case '_':
3722     if (consumeIf("_Z")) {
3723       Node *R = parseEncoding();
3724       if (R != nullptr && consumeIf('E'))
3725         return R;
3726     }
3727     return nullptr;
3728   case 'T':
3729     // Invalid mangled name per
3730     //   http://sourcerytools.com/pipermail/cxx-abi-dev/2011-August/002422.html
3731     return nullptr;
3732   default: {
3733     // might be named type
3734     Node *T = parseType();
3735     if (T == nullptr)
3736       return nullptr;
3737     StringView N = parseNumber();
3738     if (!N.empty()) {
3739       if (!consumeIf('E'))
3740         return nullptr;
3741       return make<IntegerCastExpr>(T, N);
3742     }
3743     if (consumeIf('E'))
3744       return T;
3745     return nullptr;
3746   }
3747   }
3748 }
3749 
3750 // <braced-expression> ::= <expression>
3751 //                     ::= di <field source-name> <braced-expression>    # .name = expr
3752 //                     ::= dx <index expression> <braced-expression>     # [expr] = expr
3753 //                     ::= dX <range begin expression> <range end expression> <braced-expression>
3754 Node *Db::parseBracedExpr() {
3755   if (look() == 'd') {
3756     switch (look(1)) {
3757     case 'i': {
3758       First += 2;
3759       Node *Field = parseSourceName(/*NameState=*/nullptr);
3760       if (Field == nullptr)
3761         return nullptr;
3762       Node *Init = parseBracedExpr();
3763       if (Init == nullptr)
3764         return nullptr;
3765       return make<BracedExpr>(Field, Init, /*isArray=*/false);
3766     }
3767     case 'x': {
3768       First += 2;
3769       Node *Index = parseExpr();
3770       if (Index == nullptr)
3771         return nullptr;
3772       Node *Init = parseBracedExpr();
3773       if (Init == nullptr)
3774         return nullptr;
3775       return make<BracedExpr>(Index, Init, /*isArray=*/true);
3776     }
3777     case 'X': {
3778       First += 2;
3779       Node *RangeBegin = parseExpr();
3780       if (RangeBegin == nullptr)
3781         return nullptr;
3782       Node *RangeEnd = parseExpr();
3783       if (RangeEnd == nullptr)
3784         return nullptr;
3785       Node *Init = parseBracedExpr();
3786       if (Init == nullptr)
3787         return nullptr;
3788       return make<BracedRangeExpr>(RangeBegin, RangeEnd, Init);
3789     }
3790     }
3791   }
3792   return parseExpr();
3793 }
3794 
3795 // <expression> ::= <unary operator-name> <expression>
3796 //              ::= <binary operator-name> <expression> <expression>
3797 //              ::= <ternary operator-name> <expression> <expression> <expression>
3798 //              ::= cl <expression>+ E                                   # call
3799 //              ::= cv <type> <expression>                               # conversion with one argument
3800 //              ::= cv <type> _ <expression>* E                          # conversion with a different number of arguments
3801 //              ::= [gs] nw <expression>* _ <type> E                     # new (expr-list) type
3802 //              ::= [gs] nw <expression>* _ <type> <initializer>         # new (expr-list) type (init)
3803 //              ::= [gs] na <expression>* _ <type> E                     # new[] (expr-list) type
3804 //              ::= [gs] na <expression>* _ <type> <initializer>         # new[] (expr-list) type (init)
3805 //              ::= [gs] dl <expression>                                 # delete expression
3806 //              ::= [gs] da <expression>                                 # delete[] expression
3807 //              ::= pp_ <expression>                                     # prefix ++
3808 //              ::= mm_ <expression>                                     # prefix --
3809 //              ::= ti <type>                                            # typeid (type)
3810 //              ::= te <expression>                                      # typeid (expression)
3811 //              ::= dc <type> <expression>                               # dynamic_cast<type> (expression)
3812 //              ::= sc <type> <expression>                               # static_cast<type> (expression)
3813 //              ::= cc <type> <expression>                               # const_cast<type> (expression)
3814 //              ::= rc <type> <expression>                               # reinterpret_cast<type> (expression)
3815 //              ::= st <type>                                            # sizeof (a type)
3816 //              ::= sz <expression>                                      # sizeof (an expression)
3817 //              ::= at <type>                                            # alignof (a type)
3818 //              ::= az <expression>                                      # alignof (an expression)
3819 //              ::= nx <expression>                                      # noexcept (expression)
3820 //              ::= <template-param>
3821 //              ::= <function-param>
3822 //              ::= dt <expression> <unresolved-name>                    # expr.name
3823 //              ::= pt <expression> <unresolved-name>                    # expr->name
3824 //              ::= ds <expression> <expression>                         # expr.*expr
3825 //              ::= sZ <template-param>                                  # size of a parameter pack
3826 //              ::= sZ <function-param>                                  # size of a function parameter pack
3827 //              ::= sp <expression>                                      # pack expansion
3828 //              ::= tw <expression>                                      # throw expression
3829 //              ::= tr                                                   # throw with no operand (rethrow)
3830 //              ::= <unresolved-name>                                    # f(p), N::f(p), ::f(p),
3831 //                                                                       # freestanding dependent name (e.g., T::x),
3832 //                                                                       # objectless nonstatic member reference
3833 //              ::= fL <binary-operator-name> <expression> <expression>
3834 //              ::= fR <binary-operator-name> <expression> <expression>
3835 //              ::= fl <binary-operator-name> <expression>
3836 //              ::= fr <binary-operator-name> <expression>
3837 //              ::= <expr-primary>
3838 Node *Db::parseExpr() {
3839   bool Global = consumeIf("gs");
3840   if (numLeft() < 2)
3841     return nullptr;
3842 
3843   switch (*First) {
3844   case 'L':
3845     return parseExprPrimary();
3846   case 'T':
3847     return parseTemplateParam();
3848   case 'f':
3849     return parseFunctionParam();
3850   case 'a':
3851     switch (First[1]) {
3852     case 'a':
3853       First += 2;
3854       return parseBinaryExpr("&&");
3855     case 'd':
3856       First += 2;
3857       return parsePrefixExpr("&");
3858     case 'n':
3859       First += 2;
3860       return parseBinaryExpr("&");
3861     case 'N':
3862       First += 2;
3863       return parseBinaryExpr("&=");
3864     case 'S':
3865       First += 2;
3866       return parseBinaryExpr("=");
3867     case 't': {
3868       First += 2;
3869       Node *Ty = parseType();
3870       if (Ty == nullptr)
3871         return nullptr;
3872       return make<EnclosingExpr>("alignof (", Ty, ")");
3873     }
3874     case 'z': {
3875       First += 2;
3876       Node *Ty = parseExpr();
3877       if (Ty == nullptr)
3878         return nullptr;
3879       return make<EnclosingExpr>("alignof (", Ty, ")");
3880     }
3881     }
3882     return nullptr;
3883   case 'c':
3884     switch (First[1]) {
3885     // cc <type> <expression>                               # const_cast<type>(expression)
3886     case 'c': {
3887       First += 2;
3888       Node *Ty = parseType();
3889       if (Ty == nullptr)
3890         return Ty;
3891       Node *Ex = parseExpr();
3892       if (Ex == nullptr)
3893         return Ex;
3894       return make<CastExpr>("const_cast", Ty, Ex);
3895     }
3896     // cl <expression>+ E                                   # call
3897     case 'l': {
3898       First += 2;
3899       Node *Callee = parseExpr();
3900       if (Callee == nullptr)
3901         return Callee;
3902       size_t ExprsBegin = Names.size();
3903       while (!consumeIf('E')) {
3904         Node *E = parseExpr();
3905         if (E == nullptr)
3906           return E;
3907         Names.push_back(E);
3908       }
3909       return make<CallExpr>(Callee, popTrailingNodeArray(ExprsBegin));
3910     }
3911     case 'm':
3912       First += 2;
3913       return parseBinaryExpr(",");
3914     case 'o':
3915       First += 2;
3916       return parsePrefixExpr("~");
3917     case 'v':
3918       return parseConversionExpr();
3919     }
3920     return nullptr;
3921   case 'd':
3922     switch (First[1]) {
3923     case 'a': {
3924       First += 2;
3925       Node *Ex = parseExpr();
3926       if (Ex == nullptr)
3927         return Ex;
3928       return make<DeleteExpr>(Ex, Global, /*is_array=*/true);
3929     }
3930     case 'c': {
3931       First += 2;
3932       Node *T = parseType();
3933       if (T == nullptr)
3934         return T;
3935       Node *Ex = parseExpr();
3936       if (Ex == nullptr)
3937         return Ex;
3938       return make<CastExpr>("dynamic_cast", T, Ex);
3939     }
3940     case 'e':
3941       First += 2;
3942       return parsePrefixExpr("*");
3943     case 'l': {
3944       First += 2;
3945       Node *E = parseExpr();
3946       if (E == nullptr)
3947         return E;
3948       return make<DeleteExpr>(E, Global, /*is_array=*/false);
3949     }
3950     case 'n':
3951       return parseUnresolvedName();
3952     case 's': {
3953       First += 2;
3954       Node *LHS = parseExpr();
3955       if (LHS == nullptr)
3956         return nullptr;
3957       Node *RHS = parseExpr();
3958       if (RHS == nullptr)
3959         return nullptr;
3960       return make<MemberExpr>(LHS, ".*", RHS);
3961     }
3962     case 't': {
3963       First += 2;
3964       Node *LHS = parseExpr();
3965       if (LHS == nullptr)
3966         return LHS;
3967       Node *RHS = parseExpr();
3968       if (RHS == nullptr)
3969         return nullptr;
3970       return make<MemberExpr>(LHS, ".", RHS);
3971     }
3972     case 'v':
3973       First += 2;
3974       return parseBinaryExpr("/");
3975     case 'V':
3976       First += 2;
3977       return parseBinaryExpr("/=");
3978     }
3979     return nullptr;
3980   case 'e':
3981     switch (First[1]) {
3982     case 'o':
3983       First += 2;
3984       return parseBinaryExpr("^");
3985     case 'O':
3986       First += 2;
3987       return parseBinaryExpr("^=");
3988     case 'q':
3989       First += 2;
3990       return parseBinaryExpr("==");
3991     }
3992     return nullptr;
3993   case 'g':
3994     switch (First[1]) {
3995     case 'e':
3996       First += 2;
3997       return parseBinaryExpr(">=");
3998     case 't':
3999       First += 2;
4000       return parseBinaryExpr(">");
4001     }
4002     return nullptr;
4003   case 'i':
4004     switch (First[1]) {
4005     case 'x': {
4006       First += 2;
4007       Node *Base = parseExpr();
4008       if (Base == nullptr)
4009         return nullptr;
4010       Node *Index = parseExpr();
4011       if (Index == nullptr)
4012         return Index;
4013       return make<ArraySubscriptExpr>(Base, Index);
4014     }
4015     case 'l': {
4016       First += 2;
4017       size_t InitsBegin = Names.size();
4018       while (!consumeIf('E')) {
4019         Node *E = parseBracedExpr();
4020         if (E == nullptr)
4021           return nullptr;
4022         Names.push_back(E);
4023       }
4024       return make<InitListExpr>(nullptr, popTrailingNodeArray(InitsBegin));
4025     }
4026     }
4027     return nullptr;
4028   case 'l':
4029     switch (First[1]) {
4030     case 'e':
4031       First += 2;
4032       return parseBinaryExpr("<=");
4033     case 's':
4034       First += 2;
4035       return parseBinaryExpr("<<");
4036     case 'S':
4037       First += 2;
4038       return parseBinaryExpr("<<=");
4039     case 't':
4040       First += 2;
4041       return parseBinaryExpr("<");
4042     }
4043     return nullptr;
4044   case 'm':
4045     switch (First[1]) {
4046     case 'i':
4047       First += 2;
4048       return parseBinaryExpr("-");
4049     case 'I':
4050       First += 2;
4051       return parseBinaryExpr("-=");
4052     case 'l':
4053       First += 2;
4054       return parseBinaryExpr("*");
4055     case 'L':
4056       First += 2;
4057       return parseBinaryExpr("*=");
4058     case 'm':
4059       First += 2;
4060       if (consumeIf('_'))
4061         return parsePrefixExpr("--");
4062       Node *Ex = parseExpr();
4063       if (Ex == nullptr)
4064         return nullptr;
4065       return make<PostfixExpr>(Ex, "--");
4066     }
4067     return nullptr;
4068   case 'n':
4069     switch (First[1]) {
4070     case 'a':
4071     case 'w':
4072       return parseNewExpr();
4073     case 'e':
4074       First += 2;
4075       return parseBinaryExpr("!=");
4076     case 'g':
4077       First += 2;
4078       return parsePrefixExpr("-");
4079     case 't':
4080       First += 2;
4081       return parsePrefixExpr("!");
4082     case 'x':
4083       First += 2;
4084       Node *Ex = parseExpr();
4085       if (Ex == nullptr)
4086         return Ex;
4087       return make<EnclosingExpr>("noexcept (", Ex, ")");
4088     }
4089     return nullptr;
4090   case 'o':
4091     switch (First[1]) {
4092     case 'n':
4093       return parseUnresolvedName();
4094     case 'o':
4095       First += 2;
4096       return parseBinaryExpr("||");
4097     case 'r':
4098       First += 2;
4099       return parseBinaryExpr("|");
4100     case 'R':
4101       First += 2;
4102       return parseBinaryExpr("|=");
4103     }
4104     return nullptr;
4105   case 'p':
4106     switch (First[1]) {
4107     case 'm':
4108       First += 2;
4109       return parseBinaryExpr("->*");
4110     case 'l':
4111       First += 2;
4112       return parseBinaryExpr("+");
4113     case 'L':
4114       First += 2;
4115       return parseBinaryExpr("+=");
4116     case 'p': {
4117       First += 2;
4118       if (consumeIf('_'))
4119         return parsePrefixExpr("++");
4120       Node *Ex = parseExpr();
4121       if (Ex == nullptr)
4122         return Ex;
4123       return make<PostfixExpr>(Ex, "++");
4124     }
4125     case 's':
4126       First += 2;
4127       return parsePrefixExpr("+");
4128     case 't': {
4129       First += 2;
4130       Node *L = parseExpr();
4131       if (L == nullptr)
4132         return nullptr;
4133       Node *R = parseExpr();
4134       if (R == nullptr)
4135         return nullptr;
4136       return make<MemberExpr>(L, "->", R);
4137     }
4138     }
4139     return nullptr;
4140   case 'q':
4141     if (First[1] == 'u') {
4142       First += 2;
4143       Node *Cond = parseExpr();
4144       if (Cond == nullptr)
4145         return nullptr;
4146       Node *LHS = parseExpr();
4147       if (LHS == nullptr)
4148         return nullptr;
4149       Node *RHS = parseExpr();
4150       if (RHS == nullptr)
4151         return nullptr;
4152       return make<ConditionalExpr>(Cond, LHS, RHS);
4153     }
4154     return nullptr;
4155   case 'r':
4156     switch (First[1]) {
4157     case 'c': {
4158       First += 2;
4159       Node *T = parseType();
4160       if (T == nullptr)
4161         return T;
4162       Node *Ex = parseExpr();
4163       if (Ex == nullptr)
4164         return Ex;
4165       return make<CastExpr>("reinterpret_cast", T, Ex);
4166     }
4167     case 'm':
4168       First += 2;
4169       return parseBinaryExpr("%");
4170     case 'M':
4171       First += 2;
4172       return parseBinaryExpr("%=");
4173     case 's':
4174       First += 2;
4175       return parseBinaryExpr(">>");
4176     case 'S':
4177       First += 2;
4178       return parseBinaryExpr(">>=");
4179     }
4180     return nullptr;
4181   case 's':
4182     switch (First[1]) {
4183     case 'c': {
4184       First += 2;
4185       Node *T = parseType();
4186       if (T == nullptr)
4187         return T;
4188       Node *Ex = parseExpr();
4189       if (Ex == nullptr)
4190         return Ex;
4191       return make<CastExpr>("static_cast", T, Ex);
4192     }
4193     case 'p': {
4194       First += 2;
4195       Node *Child = parseExpr();
4196       if (Child == nullptr)
4197         return nullptr;
4198       return make<ParameterPackExpansion>(Child);
4199     }
4200     case 'r':
4201       return parseUnresolvedName();
4202     case 't': {
4203       First += 2;
4204       Node *Ty = parseType();
4205       if (Ty == nullptr)
4206         return Ty;
4207       return make<EnclosingExpr>("sizeof (", Ty, ")");
4208     }
4209     case 'z': {
4210       First += 2;
4211       Node *Ex = parseExpr();
4212       if (Ex == nullptr)
4213         return Ex;
4214       return make<EnclosingExpr>("sizeof (", Ex, ")");
4215     }
4216     case 'Z':
4217       First += 2;
4218       if (look() == 'T') {
4219         Node *R = parseTemplateParam();
4220         if (R == nullptr)
4221           return nullptr;
4222         return make<SizeofParamPackExpr>(R);
4223       } else if (look() == 'f') {
4224         Node *FP = parseFunctionParam();
4225         if (FP == nullptr)
4226           return nullptr;
4227         return make<EnclosingExpr>("sizeof...", FP, ")");
4228       }
4229       return nullptr;
4230     }
4231     return nullptr;
4232   case 't':
4233     switch (First[1]) {
4234     case 'e': {
4235       First += 2;
4236       Node *Ex = parseExpr();
4237       if (Ex == nullptr)
4238         return Ex;
4239       return make<EnclosingExpr>("typeid (", Ex, ")");
4240     }
4241     case 'i': {
4242       First += 2;
4243       Node *Ty = parseType();
4244       if (Ty == nullptr)
4245         return Ty;
4246       return make<EnclosingExpr>("typeid (", Ty, ")");
4247     }
4248     case 'l': {
4249       First += 2;
4250       Node *Ty = parseType();
4251       if (Ty == nullptr)
4252         return nullptr;
4253       size_t InitsBegin = Names.size();
4254       while (!consumeIf('E')) {
4255         Node *E = parseBracedExpr();
4256         if (E == nullptr)
4257           return nullptr;
4258         Names.push_back(E);
4259       }
4260       return make<InitListExpr>(Ty, popTrailingNodeArray(InitsBegin));
4261     }
4262     case 'r':
4263       First += 2;
4264       return make<NameType>("throw");
4265     case 'w': {
4266       First += 2;
4267       Node *Ex = parseExpr();
4268       if (Ex == nullptr)
4269         return nullptr;
4270       return make<ThrowExpr>(Ex);
4271     }
4272     }
4273     return nullptr;
4274   case '1':
4275   case '2':
4276   case '3':
4277   case '4':
4278   case '5':
4279   case '6':
4280   case '7':
4281   case '8':
4282   case '9':
4283     return parseUnresolvedName();
4284   }
4285   return nullptr;
4286 }
4287 
4288 // <call-offset> ::= h <nv-offset> _
4289 //               ::= v <v-offset> _
4290 //
4291 // <nv-offset> ::= <offset number>
4292 //               # non-virtual base override
4293 //
4294 // <v-offset>  ::= <offset number> _ <virtual offset number>
4295 //               # virtual base override, with vcall offset
4296 bool Db::parseCallOffset() {
4297   // Just scan through the call offset, we never add this information into the
4298   // output.
4299   if (consumeIf('h'))
4300     return parseNumber(true).empty() || !consumeIf('_');
4301   if (consumeIf('v'))
4302     return parseNumber(true).empty() || !consumeIf('_') ||
4303            parseNumber(true).empty() || !consumeIf('_');
4304   return true;
4305 }
4306 
4307 // <special-name> ::= TV <type>    # virtual table
4308 //                ::= TT <type>    # VTT structure (construction vtable index)
4309 //                ::= TI <type>    # typeinfo structure
4310 //                ::= TS <type>    # typeinfo name (null-terminated byte string)
4311 //                ::= Tc <call-offset> <call-offset> <base encoding>
4312 //                    # base is the nominal target function of thunk
4313 //                    # first call-offset is 'this' adjustment
4314 //                    # second call-offset is result adjustment
4315 //                ::= T <call-offset> <base encoding>
4316 //                    # base is the nominal target function of thunk
4317 //                ::= GV <object name> # Guard variable for one-time initialization
4318 //                                     # No <type>
4319 //                ::= TW <object name> # Thread-local wrapper
4320 //                ::= TH <object name> # Thread-local initialization
4321 //                ::= GR <object name> _             # First temporary
4322 //                ::= GR <object name> <seq-id> _    # Subsequent temporaries
4323 //      extension ::= TC <first type> <number> _ <second type> # construction vtable for second-in-first
4324 //      extension ::= GR <object name> # reference temporary for object
4325 Node *Db::parseSpecialName() {
4326   switch (look()) {
4327   case 'T':
4328     switch (look(1)) {
4329     // TV <type>    # virtual table
4330     case 'V': {
4331       First += 2;
4332       Node *Ty = parseType();
4333       if (Ty == nullptr)
4334         return nullptr;
4335       return make<SpecialName>("vtable for ", Ty);
4336     }
4337     // TT <type>    # VTT structure (construction vtable index)
4338     case 'T': {
4339       First += 2;
4340       Node *Ty = parseType();
4341       if (Ty == nullptr)
4342         return nullptr;
4343       return make<SpecialName>("VTT for ", Ty);
4344     }
4345     // TI <type>    # typeinfo structure
4346     case 'I': {
4347       First += 2;
4348       Node *Ty = parseType();
4349       if (Ty == nullptr)
4350         return nullptr;
4351       return make<SpecialName>("typeinfo for ", Ty);
4352     }
4353     // TS <type>    # typeinfo name (null-terminated byte string)
4354     case 'S': {
4355       First += 2;
4356       Node *Ty = parseType();
4357       if (Ty == nullptr)
4358         return nullptr;
4359       return make<SpecialName>("typeinfo name for ", Ty);
4360     }
4361     // Tc <call-offset> <call-offset> <base encoding>
4362     case 'c': {
4363       First += 2;
4364       if (parseCallOffset() || parseCallOffset())
4365         return nullptr;
4366       Node *Encoding = parseEncoding();
4367       if (Encoding == nullptr)
4368         return nullptr;
4369       return make<SpecialName>("covariant return thunk to ", Encoding);
4370     }
4371     // extension ::= TC <first type> <number> _ <second type>
4372     //               # construction vtable for second-in-first
4373     case 'C': {
4374       First += 2;
4375       Node *FirstType = parseType();
4376       if (FirstType == nullptr)
4377         return nullptr;
4378       if (parseNumber(true).empty() || !consumeIf('_'))
4379         return nullptr;
4380       Node *SecondType = parseType();
4381       if (SecondType == nullptr)
4382         return nullptr;
4383       return make<CtorVtableSpecialName>(SecondType, FirstType);
4384     }
4385     // TW <object name> # Thread-local wrapper
4386     case 'W': {
4387       First += 2;
4388       Node *Name = parseName();
4389       if (Name == nullptr)
4390         return nullptr;
4391       return make<SpecialName>("thread-local wrapper routine for ", Name);
4392     }
4393     // TH <object name> # Thread-local initialization
4394     case 'H': {
4395       First += 2;
4396       Node *Name = parseName();
4397       if (Name == nullptr)
4398         return nullptr;
4399       return make<SpecialName>("thread-local initialization routine for ", Name);
4400     }
4401     // T <call-offset> <base encoding>
4402     default: {
4403       ++First;
4404       bool IsVirt = look() == 'v';
4405       if (parseCallOffset())
4406         return nullptr;
4407       Node *BaseEncoding = parseEncoding();
4408       if (BaseEncoding == nullptr)
4409         return nullptr;
4410       if (IsVirt)
4411         return make<SpecialName>("virtual thunk to ", BaseEncoding);
4412       else
4413         return make<SpecialName>("non-virtual thunk to ", BaseEncoding);
4414     }
4415     }
4416   case 'G':
4417     switch (look(1)) {
4418     // GV <object name> # Guard variable for one-time initialization
4419     case 'V': {
4420       First += 2;
4421       Node *Name = parseName();
4422       if (Name == nullptr)
4423         return nullptr;
4424       return make<SpecialName>("guard variable for ", Name);
4425     }
4426     // GR <object name> # reference temporary for object
4427     // GR <object name> _             # First temporary
4428     // GR <object name> <seq-id> _    # Subsequent temporaries
4429     case 'R': {
4430       First += 2;
4431       Node *Name = parseName();
4432       if (Name == nullptr)
4433         return nullptr;
4434       size_t Count;
4435       bool ParsedSeqId = !parseSeqId(&Count);
4436       if (!consumeIf('_') && ParsedSeqId)
4437         return nullptr;
4438       return make<SpecialName>("reference temporary for ", Name);
4439     }
4440     }
4441   }
4442   return nullptr;
4443 }
4444 
4445 // <encoding> ::= <function name> <bare-function-type>
4446 //            ::= <data name>
4447 //            ::= <special-name>
4448 Node *Db::parseEncoding() {
4449   // Always "tag" templates (insert them into Db::TemplateParams) unless we're
4450   // doing a second parse to resolve a forward template reference, in which case
4451   // we only tag templates if EncodingDepth > 1.
4452   // FIXME: This is kinda broken; it would be better to make a forward reference
4453   // and patch it all in one pass.
4454   SwapAndRestore<bool> SaveTagTemplates(TagTemplates,
4455                                         TagTemplates || EncodingDepth);
4456   SwapAndRestore<unsigned> SaveEncodingDepth(EncodingDepth, EncodingDepth + 1);
4457 
4458   if (look() == 'G' || look() == 'T')
4459     return parseSpecialName();
4460 
4461   auto IsEndOfEncoding = [&] {
4462     // The set of chars that can potentially follow an <encoding> (none of which
4463     // can start a <type>). Enumerating these allows us to avoid speculative
4464     // parsing.
4465     return numLeft() == 0 || look() == 'E' || look() == '.' || look() == '_';
4466   };
4467 
4468   NameState NameInfo;
4469   Node *Name = parseName(&NameInfo);
4470   if (Name == nullptr || IsEndOfEncoding())
4471     return Name;
4472 
4473   TagTemplates = false;
4474 
4475   Node *ReturnType = nullptr;
4476   if (!NameInfo.CtorDtorConversion && NameInfo.EndsWithTemplateArgs) {
4477     ReturnType = parseType();
4478     if (ReturnType == nullptr)
4479       return nullptr;
4480   }
4481 
4482   if (consumeIf('v'))
4483     return make<FunctionEncoding>(ReturnType, Name, NodeArray(),
4484                                   NameInfo.CVQualifiers,
4485                                   NameInfo.ReferenceQualifier);
4486 
4487   size_t ParamsBegin = Names.size();
4488   do {
4489     Node *Ty = parseType();
4490     if (Ty == nullptr)
4491       return nullptr;
4492     Names.push_back(Ty);
4493   } while (!IsEndOfEncoding());
4494 
4495   return make<FunctionEncoding>(ReturnType, Name,
4496                                 popTrailingNodeArray(ParamsBegin),
4497                                 NameInfo.CVQualifiers,
4498                                 NameInfo.ReferenceQualifier);
4499 }
4500 
4501 template <class Float>
4502 struct FloatData;
4503 
4504 template <>
4505 struct FloatData<float>
4506 {
4507     static const size_t mangled_size = 8;
4508     static const size_t max_demangled_size = 24;
4509     static constexpr const char* spec = "%af";
4510 };
4511 
4512 constexpr const char* FloatData<float>::spec;
4513 
4514 template <>
4515 struct FloatData<double>
4516 {
4517     static const size_t mangled_size = 16;
4518     static const size_t max_demangled_size = 32;
4519     static constexpr const char* spec = "%a";
4520 };
4521 
4522 constexpr const char* FloatData<double>::spec;
4523 
4524 template <>
4525 struct FloatData<long double>
4526 {
4527 #if defined(__mips__) && defined(__mips_n64) || defined(__aarch64__) || \
4528     defined(__wasm__)
4529     static const size_t mangled_size = 32;
4530 #elif defined(__arm__) || defined(__mips__) || defined(__hexagon__)
4531     static const size_t mangled_size = 16;
4532 #else
4533     static const size_t mangled_size = 20;  // May need to be adjusted to 16 or 24 on other platforms
4534 #endif
4535     static const size_t max_demangled_size = 40;
4536     static constexpr const char *spec = "%LaL";
4537 };
4538 
4539 constexpr const char *FloatData<long double>::spec;
4540 
4541 template <class Float> Node *Db::parseFloatingLiteral() {
4542   const size_t N = FloatData<Float>::mangled_size;
4543   if (numLeft() <= N)
4544     return nullptr;
4545   StringView Data(First, First + N);
4546   for (char C : Data)
4547     if (!std::isxdigit(C))
4548       return nullptr;
4549   First += N;
4550   if (!consumeIf('E'))
4551     return nullptr;
4552   return make<FloatExpr<Float>>(Data);
4553 }
4554 
4555 // <seq-id> ::= <0-9A-Z>+
4556 bool Db::parseSeqId(size_t *Out) {
4557   if (!(look() >= '0' && look() <= '9') &&
4558       !(look() >= 'A' && look() <= 'Z'))
4559     return true;
4560 
4561   size_t Id = 0;
4562   while (true) {
4563     if (look() >= '0' && look() <= '9') {
4564       Id *= 36;
4565       Id += static_cast<size_t>(look() - '0');
4566     } else if (look() >= 'A' && look() <= 'Z') {
4567       Id *= 36;
4568       Id += static_cast<size_t>(look() - 'A') + 10;
4569     } else {
4570       *Out = Id;
4571       return false;
4572     }
4573     ++First;
4574   }
4575 }
4576 
4577 // <substitution> ::= S <seq-id> _
4578 //                ::= S_
4579 // <substitution> ::= Sa # ::std::allocator
4580 // <substitution> ::= Sb # ::std::basic_string
4581 // <substitution> ::= Ss # ::std::basic_string < char,
4582 //                                               ::std::char_traits<char>,
4583 //                                               ::std::allocator<char> >
4584 // <substitution> ::= Si # ::std::basic_istream<char,  std::char_traits<char> >
4585 // <substitution> ::= So # ::std::basic_ostream<char,  std::char_traits<char> >
4586 // <substitution> ::= Sd # ::std::basic_iostream<char, std::char_traits<char> >
4587 Node *Db::parseSubstitution() {
4588   if (!consumeIf('S'))
4589     return nullptr;
4590 
4591   if (std::islower(look())) {
4592     Node *SpecialSub;
4593     switch (look()) {
4594     case 'a':
4595       ++First;
4596       SpecialSub = make<SpecialSubstitution>(SpecialSubKind::allocator);
4597       break;
4598     case 'b':
4599       ++First;
4600       SpecialSub = make<SpecialSubstitution>(SpecialSubKind::basic_string);
4601       break;
4602     case 's':
4603       ++First;
4604       SpecialSub = make<SpecialSubstitution>(SpecialSubKind::string);
4605       break;
4606     case 'i':
4607       ++First;
4608       SpecialSub = make<SpecialSubstitution>(SpecialSubKind::istream);
4609       break;
4610     case 'o':
4611       ++First;
4612       SpecialSub = make<SpecialSubstitution>(SpecialSubKind::ostream);
4613       break;
4614     case 'd':
4615       ++First;
4616       SpecialSub = make<SpecialSubstitution>(SpecialSubKind::iostream);
4617       break;
4618     default:
4619       return nullptr;
4620     }
4621     // Itanium C++ ABI 5.1.2: If a name that would use a built-in <substitution>
4622     // has ABI tags, the tags are appended to the substitution; the result is a
4623     // substitutable component.
4624     Node *WithTags = parseAbiTags(SpecialSub);
4625     if (WithTags != SpecialSub) {
4626       Subs.push_back(WithTags);
4627       SpecialSub = WithTags;
4628     }
4629     return SpecialSub;
4630   }
4631 
4632   //                ::= S_
4633   if (consumeIf('_')) {
4634     if (Subs.empty())
4635       return nullptr;
4636     return Subs[0];
4637   }
4638 
4639   //                ::= S <seq-id> _
4640   size_t Index = 0;
4641   if (parseSeqId(&Index))
4642     return nullptr;
4643   ++Index;
4644   if (!consumeIf('_') || Index >= Subs.size())
4645     return nullptr;
4646   return Subs[Index];
4647 }
4648 
4649 // <template-param> ::= T_    # first template parameter
4650 //                  ::= T <parameter-2 non-negative number> _
4651 Node *Db::parseTemplateParam() {
4652   if (!consumeIf('T'))
4653     return nullptr;
4654 
4655   size_t Index = 0;
4656   if (!consumeIf('_')) {
4657     if (parsePositiveInteger(&Index))
4658       return nullptr;
4659     ++Index;
4660     if (!consumeIf('_'))
4661       return nullptr;
4662   }
4663 
4664   // Itanium ABI 5.1.8: In a generic lambda, uses of auto in the parameter list
4665   // are mangled as the corresponding artificial template type parameter.
4666   if (ParsingLambdaParams)
4667     return make<NameType>("auto");
4668 
4669   if (Index >= TemplateParams.size()) {
4670     FixForwardReferences = true;
4671     return make<NameType>("FORWARD_REFERENCE");
4672   }
4673   return TemplateParams[Index];
4674 }
4675 
4676 // <template-arg> ::= <type>                    # type or template
4677 //                ::= X <expression> E          # expression
4678 //                ::= <expr-primary>            # simple expressions
4679 //                ::= J <template-arg>* E       # argument pack
4680 //                ::= LZ <encoding> E           # extension
4681 Node *Db::parseTemplateArg() {
4682   switch (look()) {
4683   case 'X': {
4684     ++First;
4685     Node *Arg = parseExpr();
4686     if (Arg == nullptr || !consumeIf('E'))
4687       return nullptr;
4688     return Arg;
4689   }
4690   case 'J': {
4691     ++First;
4692     size_t ArgsBegin = Names.size();
4693     while (!consumeIf('E')) {
4694       Node *Arg = parseTemplateArg();
4695       if (Arg == nullptr)
4696         return nullptr;
4697       Names.push_back(Arg);
4698     }
4699     NodeArray Args = popTrailingNodeArray(ArgsBegin);
4700     return make<TemplateArgumentPack>(Args);
4701   }
4702   case 'L': {
4703     //                ::= LZ <encoding> E           # extension
4704     if (look(1) == 'Z') {
4705       First += 2;
4706       Node *Arg = parseEncoding();
4707       if (Arg == nullptr || !consumeIf('E'))
4708         return nullptr;
4709       return Arg;
4710     }
4711     //                ::= <expr-primary>            # simple expressions
4712     return parseExprPrimary();
4713   }
4714   default:
4715     return parseType();
4716   }
4717 }
4718 
4719 // <template-args> ::= I <template-arg>* E
4720 //     extension, the abi says <template-arg>+
4721 Node *Db::parseTemplateArgs() {
4722   if (!consumeIf('I'))
4723     return nullptr;
4724 
4725   // <template-params> refer to the innermost <template-args>. Clear out any
4726   // outer args that we may have inserted into TemplateParams.
4727   if (TagTemplates)
4728     TemplateParams.clear();
4729 
4730   size_t ArgsBegin = Names.size();
4731   while (!consumeIf('E')) {
4732     if (TagTemplates) {
4733       auto OldParams = std::move(TemplateParams);
4734       Node *Arg = parseTemplateArg();
4735       TemplateParams = std::move(OldParams);
4736       if (Arg == nullptr)
4737         return nullptr;
4738       Names.push_back(Arg);
4739       Node *TableEntry = Arg;
4740       if (Arg->getKind() == Node::KTemplateArgumentPack) {
4741         TableEntry = make<ParameterPack>(
4742             static_cast<TemplateArgumentPack*>(TableEntry)->getElements());
4743       }
4744       TemplateParams.push_back(TableEntry);
4745     } else {
4746       Node *Arg = parseTemplateArg();
4747       if (Arg == nullptr)
4748         return nullptr;
4749       Names.push_back(Arg);
4750     }
4751   }
4752   return make<TemplateArgs>(popTrailingNodeArray(ArgsBegin));
4753 }
4754 
4755 // <discriminator> := _ <non-negative number>      # when number < 10
4756 //                 := __ <non-negative number> _   # when number >= 10
4757 //  extension      := decimal-digit+               # at the end of string
4758 
4759 const char*
4760 parse_discriminator(const char* first, const char* last)
4761 {
4762     // parse but ignore discriminator
4763     if (first != last)
4764     {
4765         if (*first == '_')
4766         {
4767             const char* t1 = first+1;
4768             if (t1 != last)
4769             {
4770                 if (std::isdigit(*t1))
4771                     first = t1+1;
4772                 else if (*t1 == '_')
4773                 {
4774                     for (++t1; t1 != last && std::isdigit(*t1); ++t1)
4775                         ;
4776                     if (t1 != last && *t1 == '_')
4777                         first = t1 + 1;
4778                 }
4779             }
4780         }
4781         else if (std::isdigit(*first))
4782         {
4783             const char* t1 = first+1;
4784             for (; t1 != last && std::isdigit(*t1); ++t1)
4785                 ;
4786             if (t1 == last)
4787                 first = last;
4788         }
4789     }
4790     return first;
4791 }
4792 
4793 // <mangled-name> ::= _Z <encoding>
4794 //                ::= <type>
4795 // extension      ::= ___Z <encoding> _block_invoke
4796 // extension      ::= ___Z <encoding> _block_invoke<decimal-digit>+
4797 // extension      ::= ___Z <encoding> _block_invoke_<decimal-digit>+
4798 Node *Db::parse() {
4799   if (consumeIf("_Z")) {
4800     Node *Encoding = parseEncoding();
4801     if (Encoding == nullptr)
4802       return nullptr;
4803     if (look() == '.') {
4804       Encoding = make<DotSuffix>(Encoding, StringView(First, Last));
4805       First = Last;
4806     }
4807     if (numLeft() != 0)
4808       return nullptr;
4809     return Encoding;
4810   }
4811 
4812   if (consumeIf("___Z")) {
4813     Node *Encoding = parseEncoding();
4814     if (Encoding == nullptr || !consumeIf("_block_invoke"))
4815       return nullptr;
4816     bool RequireNumber = consumeIf('_');
4817     if (parseNumber().empty() && RequireNumber)
4818       return nullptr;
4819     if (numLeft() != 0)
4820       return nullptr;
4821     return make<SpecialName>("invocation function for block in ", Encoding);
4822   }
4823 
4824   Node *Ty = parseType();
4825   if (numLeft() != 0)
4826     return nullptr;
4827   return Ty;
4828 }
4829 }  // unnamed namespace
4830 
4831 enum {
4832   unknown_error = -4,
4833   invalid_args = -3,
4834   invalid_mangled_name = -2,
4835   memory_alloc_failure = -1,
4836   success = 0,
4837 };
4838 
4839 char *llvm::itaniumDemangle(const char *MangledName, char *Buf,
4840                             size_t *N, int *Status) {
4841   if (MangledName == nullptr || (Buf != nullptr && N == nullptr)) {
4842     if (Status)
4843       *Status = invalid_args;
4844     return nullptr;
4845   }
4846 
4847   size_t BufSize = Buf != nullptr ? *N : 0;
4848   int InternalStatus = success;
4849   size_t MangledNameLength = std::strlen(MangledName);
4850 
4851   Db Parser(MangledName, MangledName + MangledNameLength);
4852   Node *AST = Parser.parse();
4853 
4854   if (AST == nullptr)
4855     InternalStatus = invalid_mangled_name;
4856 
4857   if (InternalStatus == success && Parser.FixForwardReferences &&
4858       !Parser.TemplateParams.empty()) {
4859     Parser.FixForwardReferences = false;
4860     Parser.TagTemplates = false;
4861     Parser.Names.clear();
4862     Parser.Subs.clear();
4863     Parser.First = MangledName;
4864     Parser.Last = MangledName + MangledNameLength;
4865     AST = Parser.parse();
4866     if (AST == nullptr || Parser.FixForwardReferences)
4867       InternalStatus = invalid_mangled_name;
4868   }
4869 
4870   if (InternalStatus == success && AST->containsUnexpandedParameterPack())
4871     InternalStatus = invalid_mangled_name;
4872 
4873   if (InternalStatus == success) {
4874     if (Buf == nullptr) {
4875       BufSize = 1024;
4876       Buf = static_cast<char*>(std::malloc(BufSize));
4877     }
4878 
4879     if (Buf) {
4880       OutputStream Stream(Buf, BufSize);
4881       AST->print(Stream);
4882       Stream += '\0';
4883       if (N != nullptr)
4884         *N = Stream.getCurrentPosition();
4885       Buf = Stream.getBuffer();
4886     } else
4887       InternalStatus = memory_alloc_failure;
4888   }
4889 
4890   if (Status)
4891     *Status = InternalStatus;
4892   return InternalStatus == success ? Buf : nullptr;
4893 }
4894