llvm.org GIT mirror llvm / 6e3e8a7
[MS Demangler] Re-write the Microsoft demangler. This is a pretty large refactor / re-write of the Microsoft demangler. The previous one was a little hackish because it evolved as I was learning about all the various edge cases, exceptions, etc. It didn't have a proper AST and so there was lots of custom handling of things that should have been much more clean. Taking what was learned from that experience, it's now re-written with a completely redesigned and much more sensible AST. It's probably still not perfect, but at least it's comprehensible now to someone else who wants to come along and make some modifications or read the code. Incidentally, this fixed a couple of bugs, so I've enabled the tests which now pass. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@340710 91177308-0d34-0410-b5e6-96231b3b80d8 Zachary Turner 1 year, 21 days ago
8 changed file(s) with 2245 addition(s) and 1892 deletion(s). Raw diff Collapse all Expand all
0 add_llvm_library(LLVMDemangle
11 ItaniumDemangle.cpp
22 MicrosoftDemangle.cpp
3 MicrosoftDemangleNodes.cpp
34
45 ADDITIONAL_HEADER_DIRS
56 "${LLVM_MAIN_INCLUDE_DIR}/llvm/Demangle"
1313 //
1414 //===----------------------------------------------------------------------===//
1515
16 #include "MicrosoftDemangleNodes.h"
1617 #include "llvm/Demangle/Demangle.h"
1718
1819 #include "llvm/Demangle/Compiler.h"
2425 #include
2526 #include
2627
27 // This memory allocator is extremely fast, but it doesn't call dtors
28 // for allocated objects. That means you can't use STL containers
29 // (such as std::vector) with this allocator. But it pays off --
30 // the demangler is 3x faster with this allocator compared to one with
31 // STL containers.
32 namespace {
33 constexpr size_t AllocUnit = 4096;
34
35 class ArenaAllocator {
36 struct AllocatorNode {
37 uint8_t *Buf = nullptr;
38 size_t Used = 0;
39 size_t Capacity = 0;
40 AllocatorNode *Next = nullptr;
41 };
42
43 void addNode(size_t Capacity) {
44 AllocatorNode *NewHead = new AllocatorNode;
45 NewHead->Buf = new uint8_t[Capacity];
46 NewHead->Next = Head;
47 NewHead->Capacity = Capacity;
48 Head = NewHead;
49 NewHead->Used = 0;
50 }
51
52 public:
53 ArenaAllocator() { addNode(AllocUnit); }
54
55 ~ArenaAllocator() {
56 while (Head) {
57 assert(Head->Buf);
58 delete[] Head->Buf;
59 AllocatorNode *Next = Head->Next;
60 delete Head;
61 Head = Next;
62 }
63 }
64
65 char *allocUnalignedBuffer(size_t Length) {
66 uint8_t *Buf = Head->Buf + Head->Used;
67
68 Head->Used += Length;
69 if (Head->Used > Head->Capacity) {
70 // It's possible we need a buffer which is larger than our default unit
71 // size, so we need to be careful to add a node with capacity that is at
72 // least as large as what we need.
73 addNode(std::max(AllocUnit, Length));
74 Head->Used = Length;
75 Buf = Head->Buf;
76 }
77
78 return reinterpret_cast(Buf);
79 }
80
81 template T *alloc(Args &&... ConstructorArgs) {
82
83 size_t Size = sizeof(T);
84 assert(Head && Head->Buf);
85
86 size_t P = (size_t)Head->Buf + Head->Used;
87 uintptr_t AlignedP =
88 (((size_t)P + alignof(T) - 1) & ~(size_t)(alignof(T) - 1));
89 uint8_t *PP = (uint8_t *)AlignedP;
90 size_t Adjustment = AlignedP - P;
91
92 Head->Used += Size + Adjustment;
93 if (Head->Used < Head->Capacity)
94 return new (PP) T(std::forward(ConstructorArgs)...);
95
96 addNode(AllocUnit);
97 Head->Used = Size;
98 return new (Head->Buf) T(std::forward(ConstructorArgs)...);
99 }
100
101 private:
102 AllocatorNode *Head = nullptr;
103 };
104 } // namespace
28 using namespace llvm;
29 using namespace ms_demangle;
10530
10631 static bool startsWithDigit(StringView S) {
10732 return !S.empty() && std::isdigit(S.front());
10833 }
10934
110 // Writes a space if the last token does not end with a punctuation.
111 static void outputSpaceIfNecessary(OutputStream &OS) {
112 if (OS.empty())
113 return;
114
115 char C = OS.back();
116 if (isalnum(C) || C == '>')
117 OS << " ";
118 }
119
120 // Storage classes
121 enum Qualifiers : uint8_t {
122 Q_None = 0,
123 Q_Const = 1 << 0,
124 Q_Volatile = 1 << 1,
125 Q_Far = 1 << 2,
126 Q_Huge = 1 << 3,
127 Q_Unaligned = 1 << 4,
128 Q_Restrict = 1 << 5,
129 Q_Pointer64 = 1 << 6
35 enum class QualifierMangleMode { Drop, Mangle, Result };
36
37 struct NodeList {
38 Node *N = nullptr;
39 NodeList *Next = nullptr;
13040 };
13141
132 enum class StorageClass : uint8_t {
133 None,
134 PrivateStatic,
135 ProtectedStatic,
136 PublicStatic,
137 Global,
138 FunctionLocalStatic,
139 };
140
141 enum class QualifierMangleMode { Drop, Mangle, Result };
142
143 enum class PointerAffinity { Pointer, Reference, RValueReference };
144
145 // Calling conventions
146 enum class CallingConv : uint8_t {
147 None,
148 Cdecl,
149 Pascal,
150 Thiscall,
151 Stdcall,
152 Fastcall,
153 Clrcall,
154 Eabi,
155 Vectorcall,
156 Regcall,
157 };
158
159 enum class ReferenceKind : uint8_t { None, LValueRef, RValueRef };
160
161 // Types
162 enum class PrimTy : uint8_t {
163 Unknown,
164 None,
165 Function,
166 Ptr,
167 MemberPtr,
168 Array,
169
170 Struct,
171 Union,
172 Class,
173 Enum,
174
175 Void,
176 Bool,
177 Char,
178 Schar,
179 Uchar,
180 Char16,
181 Char32,
182 Short,
183 Ushort,
184 Int,
185 Uint,
186 Long,
187 Ulong,
188 Int64,
189 Uint64,
190 Wchar,
191 Float,
192 Double,
193 Ldouble,
194 Nullptr,
195 Custom,
196 Vftable,
197 Vbtable,
198 LocalStaticGuard
199 };
200
201 enum class OperatorTy : uint8_t {
202 Ctor, // ?0 # Foo::Foo()
203 Dtor, // ?1 # Foo::~Foo()
204 New, // ?2 # operator new
205 Delete, // ?3 # operator delete
206 Assign, // ?4 # operator=
207 RightShift, // ?5 # operator>>
208 LeftShift, // ?6 # operator<<
209 LogicalNot, // ?7 # operator!
210 Equals, // ?8 # operator==
211 NotEquals, // ?9 # operator!=
212 ArraySubscript, // ?A # operator[]
213 Conversion, // ?B # Foo::operator ()
214 Pointer, // ?C # operator->
215 Dereference, // ?D # operator*
216 Increment, // ?E # operator++
217 Decrement, // ?F # operator--
218 Minus, // ?G # operator-
219 Plus, // ?H # operator+
220 BitwiseAnd, // ?I # operator&
221 MemberPointer, // ?J # operator->*
222 Divide, // ?K # operator/
223 Modulus, // ?L # operator%
224 LessThan, // ?M operator<
225 LessThanEqual, // ?N operator<=
226 GreaterThan, // ?O operator>
227 GreaterThanEqual, // ?P operator>=
228 Comma, // ?Q operator,
229 Parens, // ?R operator()
230 BitwiseNot, // ?S operator~
231 BitwiseXor, // ?T operator^
232 BitwiseOr, // ?U operator|
233 LogicalAnd, // ?V operator&&
234 LogicalOr, // ?W operator||
235 TimesEqual, // ?X operator*=
236 PlusEqual, // ?Y operator+=
237 MinusEqual, // ?Z operator-=
238 DivEqual, // ?_0 operator/=
239 ModEqual, // ?_1 operator%=
240 RshEqual, // ?_2 operator>>=
241 LshEqual, // ?_3 operator<<=
242 BitwiseAndEqual, // ?_4 operator&=
243 BitwiseOrEqual, // ?_5 operator|=
244 BitwiseXorEqual, // ?_6 operator^=
245 Vftable, // ?_7 # vftable
246 Vbtable, // ?_8 # vbtable
247 Vcall, // ?_9 # vcall
248 Typeof, // ?_A # typeof
249 LocalStaticGuard, // ?_B # local static guard
250 StringLiteral, // ?_C # string literal
251 VbaseDtor, // ?_D # vbase destructor
252 VecDelDtor, // ?_E # vector deleting destructor
253 DefaultCtorClosure, // ?_F # default constructor closure
254 ScalarDelDtor, // ?_G # scalar deleting destructor
255 VecCtorIter, // ?_H # vector constructor iterator
256 VecDtorIter, // ?_I # vector destructor iterator
257 VecVbaseCtorIter, // ?_J # vector vbase constructor iterator
258 VdispMap, // ?_K # virtual displacement map
259 EHVecCtorIter, // ?_L # eh vector constructor iterator
260 EHVecDtorIter, // ?_M # eh vector destructor iterator
261 EHVecVbaseCtorIter, // ?_N # eh vector vbase constructor iterator
262 CopyCtorClosure, // ?_O # copy constructor closure
263 UdtReturning, // ?_P # udt returning
264 Unknown, // ?_Q #
265 RttiTypeDescriptor, // ?_R0 # RTTI Type Descriptor
266 RttiBaseClassDescriptor, // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
267 RttiBaseClassArray, // ?_R2 # RTTI Base Class Array
268 RttiClassHierarchyDescriptor, // ?_R3 # RTTI Class Hierarchy Descriptor
269 RttiCompleteObjLocator, // ?_R4 # RTTI Complete Object Locator
270 LocalVftable, // ?_S # local vftable
271 LocalVftableCtorClosure, // ?_T # local vftable constructor closure
272 ArrayNew, // ?_U operator new[]
273 ArrayDelete, // ?_V operator delete[]
274 ManVectorCtorIter, // ?__A managed vector ctor iterator
275 ManVectorDtorIter, // ?__B managed vector dtor iterator
276 EHVectorCopyCtorIter, // ?__C EH vector copy ctor iterator
277 EHVectorVbaseCopyCtorIter, // ?__D EH vector vbase copy ctor iterator
278 DynamicInitializer, // ?__E dynamic initializer for `T'
279 DynamicAtexitDestructor, // ?__F dynamic atexit destructor for `T'
280 VectorCopyCtorIter, // ?__G vector copy constructor iterator
281 VectorVbaseCopyCtorIter, // ?__H vector vbase copy constructor iterator
282 ManVectorVbaseCopyCtorIter, // ?__I managed vector vbase copy constructor
283 // iterator
284 LocalStaticThreadGuard, // ?__J local static thread guard
285 LiteralOperator, // ?__K operator ""_name
286 CoAwait, // ?__L co_await
287 Spaceship, // operator<=>
288 };
289
290 // A map to translate from operator prefix to operator type.
291 struct OperatorMapEntry {
292 StringView Prefix;
293 StringView Name;
294 OperatorTy Operator;
295 };
296
297 // The entries here must be in the same order as the enumeration so that it can
298 // be indexed by enum value.
299 OperatorMapEntry OperatorMap[] = {
300 {"0", " ", OperatorTy::Ctor},
301 {"1", " ", OperatorTy::Dtor},
302 {"2", "operator new", OperatorTy::New},
303 {"3", "operator delete", OperatorTy::Delete},
304 {"4", "operator=", OperatorTy::Assign},
305 {"5", "operator>>", OperatorTy::RightShift},
306 {"6", "operator<<", OperatorTy::LeftShift},
307 {"7", "operator!", OperatorTy::LogicalNot},
308 {"8", "operator==", OperatorTy::Equals},
309 {"9", "operator!=", OperatorTy::NotEquals},
310 {"A", "operator[]", OperatorTy::ArraySubscript},
311 {"B", "operator ", OperatorTy::Conversion},
312 {"C", "operator->", OperatorTy::Pointer},
313 {"D", "operator*", OperatorTy::Dereference},
314 {"E", "operator++", OperatorTy::Increment},
315 {"F", "operator--", OperatorTy::Decrement},
316 {"G", "operator-", OperatorTy::Minus},
317 {"H", "operator+", OperatorTy::Plus},
318 {"I", "operator&", OperatorTy::BitwiseAnd},
319 {"J", "operator->*", OperatorTy::MemberPointer},
320 {"K", "operator/", OperatorTy::Divide},
321 {"L", "operator%", OperatorTy::Modulus},
322 {"M", "operator<", OperatorTy::LessThan},
323 {"N", "operator<=", OperatorTy::LessThanEqual},
324 {"O", "operator>", OperatorTy::GreaterThan},
325 {"P", "operator>=", OperatorTy::GreaterThanEqual},
326 {"Q", "operator,", OperatorTy::Comma},
327 {"R", "operator()", OperatorTy::Parens},
328 {"S", "operator~", OperatorTy::BitwiseNot},
329 {"T", "operator^", OperatorTy::BitwiseXor},
330 {"U", "operator|", OperatorTy::BitwiseOr},
331 {"V", "operator&&", OperatorTy::LogicalAnd},
332 {"W", "operator||", OperatorTy::LogicalOr},
333 {"X", "operator*=", OperatorTy::TimesEqual},
334 {"Y", "operator+=", OperatorTy::PlusEqual},
335 {"Z", "operator-=", OperatorTy::MinusEqual},
336 {"_0", "operator/=", OperatorTy::DivEqual},
337 {"_1", "operator%=", OperatorTy::ModEqual},
338 {"_2", "operator>>=", OperatorTy::RshEqual},
339 {"_3", "operator<<=", OperatorTy::LshEqual},
340 {"_4", "operator&=", OperatorTy::BitwiseAndEqual},
341 {"_5", "operator|=", OperatorTy::BitwiseOrEqual},
342 {"_6", "operator^=", OperatorTy::BitwiseXorEqual},
343 {"_7", "`vftable'", OperatorTy::Vftable},
344 {"_8", "`vbtable'", OperatorTy::Vbtable},
345 {"_9", "`vcall'", OperatorTy::Vcall},
346 {"_A", "`typeof'", OperatorTy::Typeof},
347 {"_B", "`local static guard'", OperatorTy::LocalStaticGuard},
348 {"_C", "`string'", OperatorTy::StringLiteral},
349 {"_D", "`vbase dtor'", OperatorTy::VbaseDtor},
350 {"_E", "`vector deleting dtor'", OperatorTy::VecDelDtor},
351 {"_F", "`default ctor closure'", OperatorTy::DefaultCtorClosure},
352 {"_G", "`scalar deleting dtor'", OperatorTy::ScalarDelDtor},
353 {"_H", "`vector ctor iterator'", OperatorTy::VecCtorIter},
354 {"_I", "`vector dtor iterator'", OperatorTy::VecDtorIter},
355 {"_J", "`vector vbase ctor iterator'", OperatorTy::VecVbaseCtorIter},
356 {"_K", "`virtual displacement map'", OperatorTy::VdispMap},
357 {"_L", "`eh vector ctor iterator'", OperatorTy::EHVecCtorIter},
358 {"_M", "`eh vector dtor iterator'", OperatorTy::EHVecDtorIter},
359 {"_N", "`eh vector vbase ctor iterator'", OperatorTy::EHVecVbaseCtorIter},
360 {"_O", "`copy ctor closure'", OperatorTy::CopyCtorClosure},
361 {"_P", "`udt returning'", OperatorTy::UdtReturning},
362 {"_Q", "`unknown'", OperatorTy::Unknown},
363 {"_R0", "`RTTI Type Descriptor'", OperatorTy::RttiTypeDescriptor},
364 {"_R1", "RTTI Base Class Descriptor", OperatorTy::RttiBaseClassDescriptor},
365 {"_R2", "`RTTI Base Class Array'", OperatorTy::RttiBaseClassArray},
366 {"_R3", "`RTTI Class Hierarchy Descriptor'",
367 OperatorTy::RttiClassHierarchyDescriptor},
368 {"_R4", "`RTTI Complete Object Locator'",
369 OperatorTy::RttiCompleteObjLocator},
370 {"_S", "`local vftable'", OperatorTy::LocalVftable},
371 {"_T", "`local vftable ctor closure'", OperatorTy::LocalVftableCtorClosure},
372 {"_U", "operator new[]", OperatorTy::ArrayNew},
373 {"_V", "operator delete[]", OperatorTy::ArrayDelete},
374 {"__A", "managed vector ctor iterator", OperatorTy::ManVectorCtorIter},
375 {"__B", "managed vector dtor iterator", OperatorTy::ManVectorDtorIter},
376 {"__C", "EH vector copy ctor iterator", OperatorTy::EHVectorCopyCtorIter},
377 {"__D", "EH vector vbase copy ctor iterator",
378 OperatorTy::EHVectorVbaseCopyCtorIter},
379 {"__E", "dynamic initializer", OperatorTy::DynamicInitializer},
380 {"__F", "dynamic atexit destructor", OperatorTy::DynamicAtexitDestructor},
381 {"__G", "vector copy ctor iterator", OperatorTy::VectorCopyCtorIter},
382 {"__H", "vector vbase copy constructor iterator",
383 OperatorTy::VectorVbaseCopyCtorIter},
384 {"__I", "managed vector vbase copy constructor iterator",
385 OperatorTy::ManVectorVbaseCopyCtorIter},
386 {"__J", "local static thread guard", OperatorTy::LocalStaticThreadGuard},
387 {"__K", "operator \"\"", OperatorTy::LiteralOperator},
388 {"__L", "co_await", OperatorTy::CoAwait},
389 };
390
391 // Function classes
392 enum FuncClass : uint16_t {
393 None = 0,
394 Public = 1 << 0,
395 Protected = 1 << 1,
396 Private = 1 << 2,
397 Global = 1 << 3,
398 Static = 1 << 4,
399 Virtual = 1 << 5,
400 Far = 1 << 6,
401 ExternC = 1 << 7,
402 NoPrototype = 1 << 8,
403 VirtualThisAdjust = 1 << 9,
404 VirtualThisAdjustEx = 1 << 10,
405 StaticThisAdjust = 1 << 11
406 };
42 enum class FunctionIdentifierCodeGroup { Basic, Under, DoubleUnder };
40743
40844 enum NameBackrefBehavior : uint8_t {
40945 NBB_None = 0, // don't save any names as backrefs.
41046 NBB_Template = 1 << 0, // save template instanations.
41147 NBB_Simple = 1 << 1, // save simple names.
41248 };
413
414 enum class SymbolCategory {
415 Unknown,
416 NamedFunction,
417 NamedVariable,
418 UnnamedFunction,
419 UnnamedVariable,
420 SpecialOperator
421 };
422
423 namespace {
424
425 struct Type;
426 struct Name;
427
428 struct FunctionParams {
429 bool IsVariadic = false;
430
431 Type *Current = nullptr;
432
433 FunctionParams *Next = nullptr;
434 };
435
436 struct TemplateParams {
437 bool IsTemplateTemplate = false;
438 bool IsAliasTemplate = false;
439 bool IsIntegerLiteral = false;
440 bool IntegerLiteralIsNegative = false;
441 bool IsEmptyParameterPack = false;
442 bool PointerToSymbol = false;
443 bool NullptrLiteral = false;
444 bool DataMemberPointer = false;
445 bool ReferenceToSymbol = false;
446
447 int ThunkOffsetCount = 0;
448 std::array ThunkOffsets;
449
450 // If IsIntegerLiteral is true, this is a non-type template parameter
451 // whose value is contained in this field.
452 uint64_t IntegralValue = 0;
453
454 // Type can be null if this is a template template parameter. In that case
455 // only Name will be valid.
456 Type *ParamType = nullptr;
457
458 // Name can be valid if this is a template template parameter (see above) or
459 // this is a function declaration (e.g. foo<&SomeFunc>). In the latter case
460 // Name contains the name of the function and Type contains the signature.
461 Name *ParamName = nullptr;
462
463 TemplateParams *Next = nullptr;
464 };
465
466 // The type class. Mangled symbols are first parsed and converted to
467 // this type and then converted to string.
468 struct Type {
469 virtual ~Type() {}
470
471 virtual Type *clone(ArenaAllocator &Arena) const;
472
473 // Write the "first half" of a given type. This is a static functions to
474 // give the code a chance to do processing that is common to a subset of
475 // subclasses
476 static void outputPre(OutputStream &OS, Type &Ty);
477
478 // Write the "second half" of a given type. This is a static functions to
479 // give the code a chance to do processing that is common to a subset of
480 // subclasses
481 static void outputPost(OutputStream &OS, Type &Ty);
482
483 virtual void outputPre(OutputStream &OS);
484 virtual void outputPost(OutputStream &OS);
485
486 // Primitive type such as Int.
487 PrimTy Prim = PrimTy::Unknown;
488
489 Qualifiers Quals = Q_None;
490 StringView Custom;
491 StorageClass Storage = StorageClass::None; // storage class
492 };
493
494 // Represents an identifier which may be a template.
495 struct Name {
496 virtual ~Name() = default;
497
498 bool IsTemplateInstantiation = false;
499 bool IsOperator = false;
500 bool IsBackReference = false;
501
502 // Name read from an MangledName string.
503 StringView Str;
504
505 // Template parameters. Only valid if IsTemplateInstantiation is true.
506 TemplateParams *TParams = nullptr;
507
508 // Nested BackReferences (e.g. "A::B::C") are represented as a linked list.
509 Name *Next = nullptr;
510 };
511
512 struct OperatorInfo : public Name {
513 explicit OperatorInfo(const OperatorMapEntry &Info) : Info(&Info) {
514 this->IsOperator = true;
515 }
516 explicit OperatorInfo(OperatorTy OpType)
517 : OperatorInfo(OperatorMap[(int)OpType]) {}
518
519 const OperatorMapEntry *Info = nullptr;
520 bool IsIndirectTable = false;
521 };
522
523 struct IndirectTable : public OperatorInfo {
524 explicit IndirectTable(const OperatorMapEntry &Info) : OperatorInfo(Info) {
525 this->IsOperator = true;
526 this->IsIndirectTable = true;
527 }
528 explicit IndirectTable(OperatorTy OpType)
529 : IndirectTable(OperatorMap[(int)OpType]) {}
530
531 const Name *TableLocation = nullptr;
532 const Name *TableTarget = nullptr;
533 };
534
535 struct StringLiteral : public OperatorInfo {
536 StringLiteral() : OperatorInfo(OperatorTy::StringLiteral) {}
537
538 PrimTy CharType;
539 bool IsTruncated = false;
540 };
541
542 struct RttiBaseClassDescriptor : public OperatorInfo {
543 RttiBaseClassDescriptor()
544 : OperatorInfo(OperatorTy::RttiBaseClassDescriptor) {}
545
546 uint32_t NVOffset = 0;
547 int32_t VBPtrOffset = 0;
548 uint32_t VBTableOffset = 0;
549 uint32_t Flags = 0;
550 };
551
552 struct LocalStaticGuardVariable : public OperatorInfo {
553 LocalStaticGuardVariable() : OperatorInfo(OperatorTy::LocalStaticGuard) {}
554
555 uint32_t ScopeIndex = 0;
556 bool IsVisible = false;
557 };
558
559 struct VirtualMemberPtrThunk : public OperatorInfo {
560 VirtualMemberPtrThunk() : OperatorInfo(OperatorTy::Vcall) {}
561
562 uint64_t OffsetInVTable = 0;
563 CallingConv CC = CallingConv::Cdecl;
564 };
565
566 struct PointerType : public Type {
567 Type *clone(ArenaAllocator &Arena) const override;
568 void outputPre(OutputStream &OS) override;
569 void outputPost(OutputStream &OS) override;
570
571 PointerAffinity Affinity;
572
573 // Represents a type X in "a pointer to X", "a reference to X",
574 // "an array of X", or "a function returning X".
575 Type *Pointee = nullptr;
576 };
577
578 struct MemberPointerType : public Type {
579 Type *clone(ArenaAllocator &Arena) const override;
580 void outputPre(OutputStream &OS) override;
581 void outputPost(OutputStream &OS) override;
582
583 Name *MemberName = nullptr;
584
585 // Represents a type X in "a pointer to X", "a reference to X",
586 // "an array of X", or "a function returning X".
587 Type *Pointee = nullptr;
588 };
589
590 struct FunctionType : public Type {
591 struct ThisAdjustor {
592 uint32_t StaticOffset = 0;
593 int32_t VBPtrOffset = 0;
594 int32_t VBOffsetOffset = 0;
595 int32_t VtordispOffset = 0;
596 };
597
598 Type *clone(ArenaAllocator &Arena) const override;
599 void outputPre(OutputStream &OS) override;
600 void outputPost(OutputStream &OS) override;
601
602 // True if this FunctionType instance is the Pointee of a PointerType or
603 // MemberPointerType.
604 bool IsFunctionPointer = false;
605 bool IsThunk = false;
606
607 Type *ReturnType = nullptr;
608 // If this is a reference, the type of reference.
609 ReferenceKind RefKind;
610
611 CallingConv CallConvention;
612 FuncClass FunctionClass;
613
614 // Valid if IsThunk is true.
615 ThisAdjustor *ThisAdjust = nullptr;
616
617 FunctionParams Params;
618 };
619
620 struct UdtType : public Type {
621 Type *clone(ArenaAllocator &Arena) const override;
622 void outputPre(OutputStream &OS) override;
623
624 Name *UdtName = nullptr;
625 };
626
627 struct ArrayDimension {
628 uint64_t Dim = 0;
629 ArrayDimension *Next = nullptr;
630 };
631
632 struct ArrayType : public Type {
633 Type *clone(ArenaAllocator &Arena) const override;
634 void outputPre(OutputStream &OS) override;
635 void outputPost(OutputStream &OS) override;
636
637 // Either NextDimension or ElementType will be valid.
638 ArrayDimension *Dims = nullptr;
639
640 Type *ElementType = nullptr;
641 };
642
643 } // namespace
64449
64550 static bool isMemberPointer(StringView MangledName) {
64651 switch (MangledName.popFront()) {
696101 return false;
697102 }
698103
699 static void outputCallingConvention(OutputStream &OS, CallingConv CC) {
700 outputSpaceIfNecessary(OS);
701
702 switch (CC) {
703 case CallingConv::Cdecl:
704 OS << "__cdecl";
705 break;
706 case CallingConv::Fastcall:
707 OS << "__fastcall";
708 break;
709 case CallingConv::Pascal:
710 OS << "__pascal";
711 break;
712 case CallingConv::Regcall:
713 OS << "__regcall";
714 break;
715 case CallingConv::Stdcall:
716 OS << "__stdcall";
717 break;
718 case CallingConv::Thiscall:
719 OS << "__thiscall";
720 break;
721 case CallingConv::Eabi:
722 OS << "__eabi";
723 break;
724 case CallingConv::Vectorcall:
725 OS << "__vectorcall";
726 break;
727 case CallingConv::Clrcall:
728 OS << "__clrcall";
729 break;
730 default:
731 break;
732 }
104 static SpecialIntrinsicKind
105 consumeSpecialIntrinsicKind(StringView &MangledName) {
106 if (MangledName.consumeFront("?_7"))
107 return SpecialIntrinsicKind::Vftable;
108 if (MangledName.consumeFront("?_8"))
109 return SpecialIntrinsicKind::Vbtable;
110 if (MangledName.consumeFront("?_9"))
111 return SpecialIntrinsicKind::VcallThunk;
112 if (MangledName.consumeFront("?_A"))
113 return SpecialIntrinsicKind::Typeof;
114 if (MangledName.consumeFront("?_B"))
115 return SpecialIntrinsicKind::LocalStaticGuard;
116 if (MangledName.consumeFront("?_C"))
117 return SpecialIntrinsicKind::StringLiteralSymbol;
118 if (MangledName.consumeFront("?_P"))
119 return SpecialIntrinsicKind::UdtReturning;
120 if (MangledName.consumeFront("?_R0"))
121 return SpecialIntrinsicKind::RttiTypeDescriptor;
122 if (MangledName.consumeFront("?_R1"))
123 return SpecialIntrinsicKind::RttiBaseClassDescriptor;
124 if (MangledName.consumeFront("?_R2"))
125 return SpecialIntrinsicKind::RttiBaseClassArray;
126 if (MangledName.consumeFront("?_R3"))
127 return SpecialIntrinsicKind::RttiClassHierarchyDescriptor;
128 if (MangledName.consumeFront("?_R4"))
129 return SpecialIntrinsicKind::RttiCompleteObjLocator;
130 if (MangledName.consumeFront("?_S"))
131 return SpecialIntrinsicKind::LocalVftable;
132 if (MangledName.consumeFront("?__E"))
133 return SpecialIntrinsicKind::DynamicInitializer;
134 if (MangledName.consumeFront("?__F"))
135 return SpecialIntrinsicKind::DynamicAtexitDestructor;
136 if (MangledName.consumeFront("?__J"))
137 return SpecialIntrinsicKind::LocalStaticThreadGuard;
138 return SpecialIntrinsicKind::None;
733139 }
734140
735141 static bool startsWithLocalScopePattern(StringView S) {
773179 return true;
774180 }
775181
776 // Write a function or template parameter list.
777 static void outputParameterList(OutputStream &OS,
778 const FunctionParams &Params) {
779 if (!Params.Current) {
780 OS << "void";
781 return;
782 }
783
784 const FunctionParams *Head = &Params;
785 while (Head) {
786 Type::outputPre(OS, *Head->Current);
787 Type::outputPost(OS, *Head->Current);
788
789 Head = Head->Next;
790
791 if (Head)
792 OS << ", ";
793 }
794 }
795
796 static void outputStringLiteral(OutputStream &OS, const StringLiteral &Str) {
797 switch (Str.CharType) {
798 case PrimTy::Wchar:
799 OS << "const wchar_t * {L\"";
800 break;
801 case PrimTy::Char:
802 OS << "const char * {\"";
803 break;
804 case PrimTy::Char16:
805 OS << "const char16_t * {u\"";
806 break;
807 case PrimTy::Char32:
808 OS << "const char32_t * {U\"";
809 break;
182 static bool isTagType(StringView S) {
183 switch (S.front()) {
184 case 'T': // union
185 case 'U': // struct
186 case 'V': // class
187 case 'W': // enum
188 return true;
189 }
190 return false;
191 }
192
193 static bool isPointerType(StringView S) {
194 if (S.startsWith("$$Q")) // foo &&
195 return true;
196
197 switch (S.front()) {
198 case 'A': // foo &
199 case 'P': // foo *
200 case 'Q': // foo *const
201 case 'R': // foo *volatile
202 case 'S': // foo *const volatile
203 return true;
204 }
205 return false;
206 }
207
208 static bool isArrayType(StringView S) { return S[0] == 'Y'; }
209
210 static bool isFunctionType(StringView S) {
211 return S.startsWith("$$A8@@") || S.startsWith("$$A6");
212 }
213
214 static FunctionRefQualifier
215 demangleFunctionRefQualifier(StringView &MangledName) {
216 if (MangledName.consumeFront('G'))
217 return FunctionRefQualifier::Reference;
218 else if (MangledName.consumeFront('H'))
219 return FunctionRefQualifier::RValueReference;
220 return FunctionRefQualifier::None;
221 }
222
223 static std::pair
224 demanglePointerCVQualifiers(StringView &MangledName) {
225 if (MangledName.consumeFront("$$Q"))
226 return std::make_pair(Q_None, PointerAffinity::RValueReference);
227
228 switch (MangledName.popFront()) {
229 case 'A':
230 return std::make_pair(Q_None, PointerAffinity::Reference);
231 case 'P':
232 return std::make_pair(Q_None, PointerAffinity::Pointer);
233 case 'Q':
234 return std::make_pair(Q_Const, PointerAffinity::Pointer);
235 case 'R':
236 return std::make_pair(Q_Volatile, PointerAffinity::Pointer);
237 case 'S':
238 return std::make_pair(Qualifiers(Q_Const | Q_Volatile),
239 PointerAffinity::Pointer);
810240 default:
811 LLVM_BUILTIN_UNREACHABLE;
812 }
813 OS << Str.Str << "\"";
814 if (Str.IsTruncated)
815 OS << "...";
816 OS << "}";
817 }
818
819 static void outputName(OutputStream &OS, const Name *TheName, const Type *Ty);
820
821 static void outputParameterList(OutputStream &OS,
822 const TemplateParams &Params) {
823 if (Params.IsEmptyParameterPack) {
824 OS << "<>";
825 return;
826 }
827
828 OS << "<";
829 const TemplateParams *Head = &Params;
830 while (Head) {
831 // Type can be null if this is a template template parameter,
832 // and Name can be null if this is a simple type.
833
834 if (Head->IsIntegerLiteral) {
835 if (Head->IntegerLiteralIsNegative)
836 OS << '-';
837 OS << Head->IntegralValue;
838 } else if (Head->PointerToSymbol || Head->ReferenceToSymbol) {
839 if (Head->NullptrLiteral)
840 OS << "nullptr";
841 else {
842 if (Head->ThunkOffsetCount > 0)
843 OS << "{";
844 else if (Head->PointerToSymbol)
845 OS << "&";
846 if (Head->ParamType)
847 Type::outputPre(OS, *Head->ParamType);
848 outputName(OS, Head->ParamName, Head->ParamType);
849 if (Head->ParamType)
850 Type::outputPost(OS, *Head->ParamType);
851 if (Head->ThunkOffsetCount > 0) {
852 for (int I = 0; I < Head->ThunkOffsetCount; ++I) {
853 OS << ", " << Head->ThunkOffsets[I];
854 }
855 OS << "}";
856 }
857 }
858 } else if (Head->DataMemberPointer) {
859 OS << "{" << Head->ThunkOffsets[0];
860 for (int I = 1; I < Head->ThunkOffsetCount; ++I)
861 OS << ", " << Head->ThunkOffsets[I];
862 OS << "}";
863 } else if (Head->ParamType) {
864 // simple type.
865 Type::outputPre(OS, *Head->ParamType);
866 Type::outputPost(OS, *Head->ParamType);
867 } else {
868 // Template alias.
869 outputName(OS, Head->ParamName, Head->ParamType);
870 }
871
872 Head = Head->Next;
873
874 if (Head)
875 OS << ", ";
876 }
877 OS << ">";
878 }
879
880 static void outputQualifiers(OutputStream &OS, Qualifiers Q) {
881 if (Q & Q_Const) {
882 outputSpaceIfNecessary(OS);
883 OS << "const";
884 }
885
886 if (Q & Q_Volatile) {
887 outputSpaceIfNecessary(OS);
888 OS << "volatile";
889 }
890
891 if (Q & Q_Restrict) {
892 outputSpaceIfNecessary(OS);
893 OS << "__restrict";
894 }
895 }
896
897 static void outputNameComponent(OutputStream &OS, const Name &N) {
898 OS << N.Str;
899
900 if (N.IsTemplateInstantiation && N.TParams)
901 outputParameterList(OS, *N.TParams);
902 }
903
904 static const OperatorInfo *lastComponentAsOperator(const Name *TheName) {
905 if (!TheName)
906 return nullptr;
907 while (TheName->Next)
908 TheName = TheName->Next;
909 if (TheName->IsOperator)
910 return static_cast(TheName);
911 return nullptr;
912 }
913
914 static void outputName(OutputStream &OS, const Name *TheName, const Type *Ty) {
915 if (!TheName)
916 return;
917
918 outputSpaceIfNecessary(OS);
919
920 const OperatorInfo *Operator = lastComponentAsOperator(TheName);
921 const VirtualMemberPtrThunk *Thunk = nullptr;
922 bool PrintLastScopeSeparator = true;
923 if (Operator) {
924 if (Operator->IsIndirectTable) {
925 const IndirectTable *Table = static_cast(Operator);
926 outputName(OS, Table->TableLocation, nullptr);
927 OS << "{for `";
928 outputName(OS, Table->TableTarget, nullptr);
929 OS << "'}";
930 return;
931 }
932 if (Operator->Info->Operator == OperatorTy::Vcall) {
933 Thunk = static_cast(Operator);
934 OS << "[thunk]: ";
935 outputCallingConvention(OS, Thunk->CC);
936 OS << " ";
937 } else if (Operator->Info->Operator == OperatorTy::DynamicInitializer) {
938 OS << "`dynamic initializer for '";
939 PrintLastScopeSeparator = false;
940 } else if (Operator->Info->Operator ==
941 OperatorTy::DynamicAtexitDestructor) {
942 OS << "`dynamic atexit destructor for '";
943 PrintLastScopeSeparator = false;
944 }
945 }
946
947 const Name *Previous = nullptr;
948 // Print out namespaces or outer class BackReferences.
949 for (; TheName->Next; TheName = TheName->Next) {
950 Previous = TheName;
951 outputNameComponent(OS, *TheName);
952 if (TheName->Next != Operator || PrintLastScopeSeparator)
953 OS << "::";
954 }
955
956 // Print out a regular name.
957 if (!TheName->IsOperator) {
958 outputNameComponent(OS, *TheName);
959 return;
960 }
961
962
963 // Print out ctor or dtor.
964 switch (Operator->Info->Operator) {
965 case OperatorTy::Dtor:
966 OS << "~";
967 LLVM_FALLTHROUGH;
968 case OperatorTy::Ctor:
969 // Output the class name with template arguments a second time.
970 outputNameComponent(OS, *Previous);
971
972 // Structors don't have a name, so outputting the name here actually is a
973 // no-op. But for template constructors, it needs to output the template
974 // argument list. e.g.
975 //
976 // template
977 // struct Foo {
978 // template
979 // Foo(U);
980 // };
981 // should demangle as -- for example -- Foo(double);
982 outputNameComponent(OS, *TheName);
983 break;
984 case OperatorTy::Conversion:
985 OS << "operator";
986 if (TheName->IsTemplateInstantiation && TheName->TParams)
987 outputParameterList(OS, *TheName->TParams);
988 OS << " ";
989 if (Ty) {
990 const FunctionType *FTy = static_cast(Ty);
991 Type::outputPre(OS, *FTy->ReturnType);
992 Type::outputPost(OS, *FTy->ReturnType);
993 } else {
994 OS << "";
995 }
996 break;
997 case OperatorTy::LiteralOperator:
998 OS << Operator->Info->Name;
999 outputNameComponent(OS, *TheName);
1000 break;
1001 case OperatorTy::RttiBaseClassDescriptor: {
1002 const RttiBaseClassDescriptor &BCD =
1003 static_cast(*Operator);
1004 OS << "`" << Operator->Info->Name << " at (";
1005 OS << BCD.NVOffset << ", " << BCD.VBPtrOffset << ", " << BCD.VBTableOffset
1006 << ", " << BCD.Flags;
1007 OS << ")'";
1008 break;
1009 }
1010 case OperatorTy::Vcall: {
1011 OS << "`vcall'{";
1012 OS << Thunk->OffsetInVTable << ", {flat}}";
1013 break;
1014 }
1015 case OperatorTy::DynamicInitializer:
1016 case OperatorTy::DynamicAtexitDestructor:
1017 OS << "''";
1018 break;
1019
1020 case OperatorTy::LocalStaticGuard: {
1021 const LocalStaticGuardVariable &LSG =
1022 static_cast(*Operator);
1023 OS << Operator->Info->Name;
1024 if (LSG.ScopeIndex > 0)
1025 OS << "{" << LSG.ScopeIndex << "}";
1026 break;
1027 }
1028 default:
1029 OS << Operator->Info->Name;
1030 if (Operator->IsTemplateInstantiation)
1031 outputParameterList(OS, *Operator->TParams);
1032 break;
1033 }
1034 }
1035
1036 static void outputSpecialOperator(OutputStream &OS, const Name *OuterName) {
1037 assert(OuterName);
1038 // The last component should be an operator.
1039 const OperatorInfo *Operator = lastComponentAsOperator(OuterName);
1040
1041 assert(Operator->IsOperator);
1042 const OperatorInfo &Oper = static_cast(*Operator);
1043 switch (Oper.Info->Operator) {
1044 case OperatorTy::StringLiteral: {
1045 const StringLiteral &SL = static_cast(Oper);
1046 outputStringLiteral(OS, SL);
1047 break;
1048 }
1049 case OperatorTy::Vcall: {
1050 const VirtualMemberPtrThunk &Thunk =
1051 static_cast(Oper);
1052 OS << "[thunk]: ";
1053 outputCallingConvention(OS, Thunk.CC);
1054 OS << " ";
1055 // Print out namespaces or outer class BackReferences.
1056 const Name *N = OuterName;
1057 for (; N->Next; N = N->Next) {
1058 outputNameComponent(OS, *N);
1059 OS << "::";
1060 }
1061 OS << "`vcall'{";
1062 OS << Thunk.OffsetInVTable << ", {flat}}";
1063 break;
1064 }
1065 default:
1066 // There are no other special operator categories.
1067 LLVM_BUILTIN_UNREACHABLE;
1068 }
1069 }
1070
1071 namespace {
1072
1073 Type *Type::clone(ArenaAllocator &Arena) const {
1074 return Arena.alloc(*this);
1075 }
1076
1077 // Write the "first half" of a given type.
1078 void Type::outputPre(OutputStream &OS, Type &Ty) {
1079 // Function types require custom handling of const and static so we
1080 // handle them separately. All other types use the same decoration
1081 // for these modifiers, so handle them here in common code.
1082 if (Ty.Prim == PrimTy::Function) {
1083 Ty.outputPre(OS);
1084 return;
1085 }
1086
1087 switch (Ty.Storage) {
1088 case StorageClass::PrivateStatic:
1089 case StorageClass::PublicStatic:
1090 case StorageClass::ProtectedStatic:
1091 OS << "static ";
1092 default:
1093 break;
1094 }
1095 Ty.outputPre(OS);
1096
1097 outputQualifiers(OS, Ty.Quals);
1098 }
1099
1100 // Write the "second half" of a given type.
1101 void Type::outputPost(OutputStream &OS, Type &Ty) { Ty.outputPost(OS); }
1102
1103 void Type::outputPre(OutputStream &OS) {
1104 switch (Prim) {
1105 case PrimTy::Void:
1106 OS << "void";
1107 break;
1108 case PrimTy::Bool:
1109 OS << "bool";
1110 break;
1111 case PrimTy::Char:
1112 OS << "char";
1113 break;
1114 case PrimTy::Schar:
1115 OS << "signed char";
1116 break;
1117 case PrimTy::Uchar:
1118 OS << "unsigned char";
1119 break;
1120 case PrimTy::Char16:
1121 OS << "char16_t";
1122 break;
1123 case PrimTy::Char32:
1124 OS << "char32_t";
1125 break;
1126 case PrimTy::Short:
1127 OS << "short";
1128 break;
1129 case PrimTy::Ushort:
1130 OS << "unsigned short";
1131 break;
1132 case PrimTy::Int:
1133 OS << "int";
1134 break;
1135 case PrimTy::Uint:
1136 OS << "unsigned int";
1137 break;
1138 case PrimTy::Long:
1139 OS << "long";
1140 break;
1141 case PrimTy::Ulong:
1142 OS << "unsigned long";
1143 break;
1144 case PrimTy::Int64:
1145 OS << "__int64";
1146 break;
1147 case PrimTy::Uint64:
1148 OS << "unsigned __int64";
1149 break;
1150 case PrimTy::Wchar:
1151 OS << "wchar_t";
1152 break;
1153 case PrimTy::Float:
1154 OS << "float";
1155 break;
1156 case PrimTy::Double:
1157 OS << "double";
1158 break;
1159 case PrimTy::Ldouble:
1160 OS << "long double";
1161 break;
1162 case PrimTy::Nullptr:
1163 OS << "std::nullptr_t";
1164 break;
1165 case PrimTy::Custom:
1166 OS << Custom;
1167 break;
1168 case PrimTy::Vbtable:
1169 case PrimTy::Vftable:
1170 break;
1171 default:
1172 assert(false && "Invalid primitive type!");
1173 }
1174 }
1175 void Type::outputPost(OutputStream &OS) {}
1176
1177 Type *PointerType::clone(ArenaAllocator &Arena) const {
1178 return Arena.alloc(*this);
1179 }
1180
1181 static void outputPointerIndicator(OutputStream &OS, PointerAffinity Affinity,
1182 const Name *MemberName,
1183 const Type *Pointee) {
1184 // "[]" and "()" (for function parameters) take precedence over "*",
1185 // so "int *x(int)" means "x is a function returning int *". We need
1186 // parentheses to supercede the default precedence. (e.g. we want to
1187 // emit something like "int (*x)(int)".)
1188 if (Pointee->Prim == PrimTy::Function || Pointee->Prim == PrimTy::Array) {
1189 OS << "(";
1190 if (Pointee->Prim == PrimTy::Function) {
1191 const FunctionType *FTy = static_cast(Pointee);
1192 assert(FTy->IsFunctionPointer);
1193 outputCallingConvention(OS, FTy->CallConvention);
1194 OS << " ";
1195 }
1196 }
1197
1198 if (MemberName) {
1199 outputName(OS, MemberName, Pointee);
1200 OS << "::";
1201 }
1202
1203 if (Affinity == PointerAffinity::Pointer)
1204 OS << "*";
1205 else if (Affinity == PointerAffinity::Reference)
1206 OS << "&";
1207 else
1208 OS << "&&";
1209 }
1210
1211 void PointerType::outputPre(OutputStream &OS) {
1212 Type::outputPre(OS, *Pointee);
1213
1214 outputSpaceIfNecessary(OS);
1215
1216 if (Quals & Q_Unaligned)
1217 OS << "__unaligned ";
1218
1219 outputPointerIndicator(OS, Affinity, nullptr, Pointee);
1220
1221 // FIXME: We should output this, but it requires updating lots of tests.
1222 // if (Ty.Quals & Q_Pointer64)
1223 // OS << " __ptr64";
1224 }
1225
1226 void PointerType::outputPost(OutputStream &OS) {
1227 if (Pointee->Prim == PrimTy::Function || Pointee->Prim == PrimTy::Array)
1228 OS << ")";
1229
1230 Type::outputPost(OS, *Pointee);
1231 }
1232
1233 Type *MemberPointerType::clone(ArenaAllocator &Arena) const {
1234 return Arena.alloc(*this);
1235 }
1236
1237 void MemberPointerType::outputPre(OutputStream &OS) {
1238 Type::outputPre(OS, *Pointee);
1239
1240 outputSpaceIfNecessary(OS);
1241
1242 outputPointerIndicator(OS, PointerAffinity::Pointer, MemberName, Pointee);
1243
1244 // FIXME: We should output this, but it requires updating lots of tests.
1245 // if (Ty.Quals & Q_Pointer64)
1246 // OS << " __ptr64";
1247 }
1248
1249 void MemberPointerType::outputPost(OutputStream &OS) {
1250 if (Pointee->Prim == PrimTy::Function || Pointee->Prim == PrimTy::Array)
1251 OS << ")";
1252
1253 Type::outputPost(OS, *Pointee);
1254 }
1255
1256 Type *FunctionType::clone(ArenaAllocator &Arena) const {
1257 return Arena.alloc(*this);
1258 }
1259
1260 void FunctionType::outputPre(OutputStream &OS) {
1261 if ((FunctionClass & StaticThisAdjust) || (FunctionClass & VirtualThisAdjust))
1262 OS << "[thunk]: ";
1263
1264 if (!(FunctionClass & Global)) {
1265 if (FunctionClass & Static)
1266 OS << "static ";
1267 }
1268 if (FunctionClass & ExternC)
1269 OS << "extern \"C\" ";
1270
1271 if (FunctionClass & Virtual)
1272 OS << "virtual ";
1273
1274 if (ReturnType) {
1275 Type::outputPre(OS, *ReturnType);
1276 OS << " ";
1277 }
1278
1279 // Function pointers print the calling convention as void (__cdecl *)(params)
1280 // rather than void __cdecl (*)(params). So we need to let the PointerType
1281 // class handle this.
1282 if (!IsFunctionPointer)
1283 outputCallingConvention(OS, CallConvention);
1284 }
1285
1286 void FunctionType::outputPost(OutputStream &OS) {
1287 // extern "C" functions don't have a prototype.
1288 if (FunctionClass & NoPrototype)
1289 return;
1290
1291 if (FunctionClass & StaticThisAdjust) {
1292 OS << "`adjustor{" << ThisAdjust->StaticOffset << "}'";
1293 } else if (FunctionClass & VirtualThisAdjust) {
1294 if (FunctionClass & VirtualThisAdjustEx) {
1295 OS << "`vtordispex{" << ThisAdjust->VBPtrOffset << ", "
1296 << ThisAdjust->VBOffsetOffset << ", " << ThisAdjust->VtordispOffset
1297 << ", " << ThisAdjust->StaticOffset << "}'";
1298 } else {
1299 OS << "`vtordisp{" << ThisAdjust->VtordispOffset << ", "
1300 << ThisAdjust->StaticOffset << "}'";
1301 }
1302 }
1303
1304 OS << "(";
1305 outputParameterList(OS, Params);
1306 OS << ")";
1307 if (Quals & Q_Const)
1308 OS << " const";
1309 if (Quals & Q_Volatile)
1310 OS << " volatile";
1311 if (Quals & Q_Restrict)
1312 OS << " __restrict";
1313 if (Quals & Q_Unaligned)
1314 OS << " __unaligned";
1315
1316 if (RefKind == ReferenceKind::LValueRef)
1317 OS << " &";
1318 else if (RefKind == ReferenceKind::RValueRef)
1319 OS << " &&";
1320
1321 if (ReturnType)
1322 Type::outputPost(OS, *ReturnType);
1323 return;
1324 }
1325
1326 Type *UdtType::clone(ArenaAllocator &Arena) const {
1327 return Arena.alloc(*this);
1328 }
1329
1330 void UdtType::outputPre(OutputStream &OS) {
1331 switch (Prim) {
1332 case PrimTy::Class:
1333 OS << "class ";
1334 break;
1335 case PrimTy::Struct:
1336 OS << "struct ";
1337 break;
1338 case PrimTy::Union:
1339 OS << "union ";
1340 break;
1341 case PrimTy::Enum:
1342 OS << "enum ";
1343 break;
1344 default:
1345 assert(false && "Not a udt type!");
1346 }
1347
1348 outputName(OS, UdtName, this);
1349 }
1350
1351 Type *ArrayType::clone(ArenaAllocator &Arena) const {
1352 return Arena.alloc(*this);
1353 }
1354
1355 void ArrayType::outputPre(OutputStream &OS) {
1356 Type::outputPre(OS, *ElementType);
1357 }
1358
1359 void ArrayType::outputPost(OutputStream &OS) {
1360 ArrayDimension *D = Dims;
1361 while (D) {
1362 OS << "[";
1363 if (D->Dim > 0)
1364 OS << D->Dim;
1365 OS << "]";
1366 D = D->Next;
1367 }
1368
1369 Type::outputPost(OS, *ElementType);
1370 }
1371
1372 struct Symbol {
1373 SymbolCategory Category;
1374
1375 Qualifiers SymbolQuals = Q_None;
1376 Name *SymbolName = nullptr;
1377 Type *SymbolType = nullptr;
1378 };
1379
1380 } // namespace
241 assert(false && "Ty is not a pointer type!");
242 }
243 return std::make_pair(Q_None, PointerAffinity::Pointer);
244 }
1381245
1382246 namespace {
1383247
1384248 struct BackrefContext {
1385249 static constexpr size_t Max = 10;
1386250
1387 Type *FunctionParams[Max];
251 TypeNode *FunctionParams[Max];
1388252 size_t FunctionParamCount = 0;
1389253
1390254 // The first 10 BackReferences in a mangled name can be back-referenced by
1391255 // special name @[0-9]. This is a storage for the first 10 BackReferences.
1392 StringView Names[Max];
256 NamedIdentifierNode *Names[Max];
1393257 size_t NamesCount = 0;
1394258 };
1395259
1403267
1404268 // You are supposed to call parse() first and then check if error is true. If
1405269 // it is false, call output() to write the formatted name to the given stream.
1406 Symbol *parse(StringView &MangledName);
1407 Symbol *parseOperator(StringView &MangledName);
1408
1409 void output(const Symbol *S, OutputStream &OS);
270 SymbolNode *parse(StringView &MangledName);
1410271
1411272 // True if an error occurred.
1412273 bool Error = false;
1414275 void dumpBackReferences();
1415276
1416277 private:
1417 std::pair
1418 demangleSymbolCategoryAndType(StringView &MangledName);
1419
1420 Type *demangleVariableEncoding(StringView &MangledName, StorageClass SC);
1421 Type *demangleFunctionEncoding(StringView &MangledName);
1422 uint64_t demangleThunkThisAdjust(StringView &MangledName);
278 SymbolNode *demangleEncodedSymbol(StringView &MangledName,
279 QualifiedNameNode *QN);
280
281 VariableSymbolNode *demangleVariableEncoding(StringView &MangledName,
282 StorageClass SC);
283 FunctionSymbolNode *demangleFunctionEncoding(StringView &MangledName);
1423284
1424285 Qualifiers demanglePointerExtQualifiers(StringView &MangledName);
1425286
1426287 // Parser functions. This is a recursive-descent parser.
1427 Type *demangleType(StringView &MangledName, QualifierMangleMode QMM);
1428 Type *demangleBasicType(StringView &MangledName);
1429 UdtType *demangleClassType(StringView &MangledName);
1430 PointerType *demanglePointerType(StringView &MangledName);
1431 MemberPointerType *demangleMemberPointerType(StringView &MangledName);
1432 FunctionType *demangleFunctionType(StringView &MangledName, bool HasThisQuals,
1433 bool IsFunctionPointer);
1434
1435 ArrayType *demangleArrayType(StringView &MangledName);
1436
1437 TemplateParams *demangleTemplateParameterList(StringView &MangledName);
1438 FunctionParams demangleFunctionParameterList(StringView &MangledName);
288 TypeNode *demangleType(StringView &MangledName, QualifierMangleMode QMM);
289 PrimitiveTypeNode *demanglePrimitiveType(StringView &MangledName);
290 TagTypeNode *demangleClassType(StringView &MangledName);
291 PointerTypeNode *demanglePointerType(StringView &MangledName);
292 PointerTypeNode *demangleMemberPointerType(StringView &MangledName);
293 FunctionSignatureNode *demangleFunctionType(StringView &MangledName,
294 bool HasThisQuals);
295
296 ArrayTypeNode *demangleArrayType(StringView &MangledName);
297
298 NodeArrayNode *demangleTemplateParameterList(StringView &MangledName);
299 NodeArrayNode *demangleFunctionParameterList(StringView &MangledName);
1439300
1440301 std::pair demangleNumber(StringView &MangledName);
1441302 uint64_t demangleUnsigned(StringView &MangledName);
1446307 /// Allocate a copy of \p Borrowed into memory that we own.
1447308 StringView copyString(StringView Borrowed);
1448309
1449 Name *demangleFullyQualifiedTypeName(StringView &MangledName);
1450 Name *demangleFullyQualifiedSymbolName(StringView &MangledName);
1451
1452 Name *demangleUnqualifiedTypeName(StringView &MangledName, bool Memorize);
1453 Name *demangleUnqualifiedSymbolName(StringView &MangledName,
1454 NameBackrefBehavior NBB);
1455
1456 Name *demangleNameScopeChain(StringView &MangledName, Name *UnqualifiedName);
1457 Name *demangleNameScopePiece(StringView &MangledName);
1458
1459 Name *demangleBackRefName(StringView &MangledName);
1460 Name *demangleTemplateInstantiationName(StringView &MangledName,
1461 NameBackrefBehavior NBB);
1462 std::pair demangleOperatorName(StringView &MangledName,
1463 bool FullyQualified);
1464 Name *demangleSimpleName(StringView &MangledName, bool Memorize);
1465 Name *demangleAnonymousNamespaceName(StringView &MangledName);
1466 Name *demangleLocallyScopedNamePiece(StringView &MangledName);
1467 StringLiteral *demangleStringLiteral(StringView &MangledName);
310 QualifiedNameNode *demangleFullyQualifiedTypeName(StringView &MangledName);
311 QualifiedNameNode *demangleFullyQualifiedSymbolName(StringView &MangledName);
312
313 IdentifierNode *demangleUnqualifiedTypeName(StringView &MangledName,
314 bool Memorize);
315 IdentifierNode *demangleUnqualifiedSymbolName(StringView &MangledName,
316 NameBackrefBehavior NBB);
317
318 QualifiedNameNode *demangleNameScopeChain(StringView &MangledName,
319 IdentifierNode *UnqualifiedName);
320 IdentifierNode *demangleNameScopePiece(StringView &MangledName);
321
322 NamedIdentifierNode *demangleBackRefName(StringView &MangledName);
323 IdentifierNode *demangleTemplateInstantiationName(StringView &MangledName,
324 NameBackrefBehavior NBB);
325 IdentifierNode *demangleFunctionIdentifierCode(StringView &MangledName);
326 IdentifierNode *
327 demangleFunctionIdentifierCode(StringView &MangledName,
328 FunctionIdentifierCodeGroup Group);
329 StructorIdentifierNode *demangleStructorIdentifier(StringView &MangledName,
330 bool IsDestructor);
331 ConversionOperatorIdentifierNode *
332 demangleConversionOperatorIdentifier(StringView &MangledName);
333 LiteralOperatorIdentifierNode *
334 demangleLiteralOperatorIdentifier(StringView &MangledName);
335
336 SymbolNode *demangleSpecialIntrinsic(StringView &MangledName);
337 SpecialTableSymbolNode *
338 demangleSpecialTableSymbolNode(StringView &MangledName,
339 SpecialIntrinsicKind SIK);
340 LocalStaticGuardVariableNode *
341 demangleLocalStaticGuard(StringView &MangledName);
342 VariableSymbolNode *demangleUntypedVariable(ArenaAllocator &Arena,
343 StringView &MangledName,
344 StringView VariableName);
345 VariableSymbolNode *
346 demangleRttiBaseClassDescriptorNode(ArenaAllocator &Arena,
347 StringView &MangledName);
348 FunctionSymbolNode *demangleDynamicStructorFunction(StringView &MangledName,
349 bool IsDestructor);
350
351 NamedIdentifierNode *demangleSimpleName(StringView &MangledName,
352 bool Memorize);
353 NamedIdentifierNode *demangleAnonymousNamespaceName(StringView &MangledName);
354 NamedIdentifierNode *demangleLocallyScopedNamePiece(StringView &MangledName);
355 EncodedStringLiteralNode *demangleStringLiteral(StringView &MangledName);
356 FunctionSymbolNode *demangleVcallThunkNode(StringView &MangledName);
1468357
1469358 StringView demangleSimpleString(StringView &MangledName, bool Memorize);
1470359
1471360 FuncClass demangleFunctionClass(StringView &MangledName);
1472361 CallingConv demangleCallingConvention(StringView &MangledName);
1473362 StorageClass demangleVariableStorageClass(StringView &MangledName);
1474 ReferenceKind demangleReferenceKind(StringView &MangledName);
1475363 void demangleThrowSpecification(StringView &MangledName);
1476364 wchar_t demangleWcharLiteral(StringView &MangledName);
1477365 uint8_t demangleCharLiteral(StringView &MangledName);
1505393 return {Stable, Borrowed.size()};
1506394 }
1507395
1508 Symbol *Demangler::parseOperator(StringView &MangledName) {
1509 Symbol *S = Arena.alloc();
1510
396 SpecialTableSymbolNode *
397 Demangler::demangleSpecialTableSymbolNode(StringView &MangledName,
398 SpecialIntrinsicKind K) {
399 NamedIdentifierNode *NI = Arena.alloc();
400 switch (K) {
401 case SpecialIntrinsicKind::Vftable:
402 NI->Name = "`vftable'";
403 break;
404 case SpecialIntrinsicKind::Vbtable:
405 NI->Name = "`vbtable'";
406 break;
407 case SpecialIntrinsicKind::LocalVftable:
408 NI->Name = "`local vftable'";
409 break;
410 case SpecialIntrinsicKind::RttiCompleteObjLocator:
411 NI->Name = "`RTTI Complete Object Locator'";
412 break;
413 default:
414 LLVM_BUILTIN_UNREACHABLE;
415 }
416 QualifiedNameNode *QN = demangleNameScopeChain(MangledName, NI);
417 SpecialTableSymbolNode *STSN = Arena.alloc();
418 STSN->Name = QN;
1511419 bool IsMember = false;
1512 OperatorTy OTy;
1513 std::tie(OTy, S->SymbolName) = demangleOperatorName(MangledName, true);
1514 switch (OTy) {
1515 case OperatorTy::StringLiteral:
1516 S->Category = SymbolCategory::SpecialOperator;
1517 break;
1518 case OperatorTy::Vcall:
1519 S->Category = SymbolCategory::UnnamedFunction;
1520 break;
1521 case OperatorTy::LocalStaticGuard:
1522 S->Category = SymbolCategory::UnnamedVariable;
1523 break;
1524 case OperatorTy::Vftable: // Foo@@6B@
1525 case OperatorTy::LocalVftable: // Foo@@6B@
1526 case OperatorTy::RttiCompleteObjLocator: // Foo@@6B@
1527 case OperatorTy::Vbtable: // Foo@@7B@
1528 S->Category = SymbolCategory::UnnamedVariable;
1529 switch (MangledName.popFront()) {
1530 case '6':
1531 case '7': {
1532 std::tie(S->SymbolQuals, IsMember) = demangleQualifiers(MangledName);
1533 if (!MangledName.consumeFront('@')) {
1534 IndirectTable *Table = Arena.alloc(OTy);
1535 Table->TableTarget = demangleFullyQualifiedTypeName(MangledName);
1536 Table->TableLocation = S->SymbolName;
1537 S->SymbolName = Table;
1538 }
1539 break;
1540 }
1541 default:
1542 Error = true;
1543 break;
1544 }
1545 break;
1546 case OperatorTy::RttiTypeDescriptor: // @@8
1547 S->Category = SymbolCategory::UnnamedVariable;
1548 S->SymbolType = demangleType(MangledName, QualifierMangleMode::Result);
420 char Front = MangledName.popFront();
421 if (Front != '6' && Front != '7') {
422 Error = true;
423 return nullptr;
424 }
425
426 std::tie(STSN->Quals, IsMember) = demangleQualifiers(MangledName);
427 if (!MangledName.consumeFront('@'))
428 STSN->TargetName = demangleFullyQualifiedTypeName(MangledName);
429 return STSN;
430 }
431
432 LocalStaticGuardVariableNode *
433 Demangler::demangleLocalStaticGuard(StringView &MangledName) {
434 LocalStaticGuardIdentifierNode *LSGI =
435 Arena.alloc();
436 QualifiedNameNode *QN = demangleNameScopeChain(MangledName, LSGI);
437 LocalStaticGuardVariableNode *LSGVN =
438 Arena.alloc();
439 LSGVN->Name = QN;
440
441 if (MangledName.consumeFront("4IA"))
442 LSGVN->IsVisible = false;
443 else if (MangledName.consumeFront("5"))
444 LSGVN->IsVisible = true;
445 else {
446 Error = true;
447 return nullptr;
448 }
449
450 if (!MangledName.empty())
451 LSGI->ScopeIndex = demangleUnsigned(MangledName);
452 return LSGVN;
453 }
454
455 static NamedIdentifierNode *synthesizeNamedIdentifier(ArenaAllocator &Arena,
456 StringView Name) {
457 NamedIdentifierNode *Id = Arena.alloc();
458 Id->Name = Name;
459 return Id;
460 }
461
462 static QualifiedNameNode *synthesizeQualifiedName(ArenaAllocator &Arena,
463 IdentifierNode *Identifier) {
464 QualifiedNameNode *QN = Arena.alloc();
465 QN->Components = Arena.alloc();
466 QN->Components->Count = 1;
467 QN->Components->Nodes = Arena.allocArray(1);
468 QN->Components->Nodes[0] = Identifier;
469 return QN;
470 }
471
472 static QualifiedNameNode *synthesizeQualifiedName(ArenaAllocator &Arena,
473 StringView Name) {
474 NamedIdentifierNode *Id = synthesizeNamedIdentifier(Arena, Name);
475 return synthesizeQualifiedName(Arena, Id);
476 }
477
478 static VariableSymbolNode *synthesizeVariable(ArenaAllocator &Arena,
479 TypeNode *Type,
480 StringView VariableName) {
481 VariableSymbolNode *VSN = Arena.alloc();
482 VSN->Type = Type;
483 VSN->Name = synthesizeQualifiedName(Arena, VariableName);
484 return VSN;
485 }
486
487 VariableSymbolNode *Demangler::demangleUntypedVariable(
488 ArenaAllocator &Arena, StringView &MangledName, StringView VariableName) {
489 NamedIdentifierNode *NI = synthesizeNamedIdentifier(Arena, VariableName);
490 QualifiedNameNode *QN = demangleNameScopeChain(MangledName, NI);
491 VariableSymbolNode *VSN = Arena.alloc();
492 VSN->Name = QN;
493 if (MangledName.consumeFront("8"))
494 return VSN;
495
496 Error = true;
497 return nullptr;
498 }
499
500 VariableSymbolNode *
501 Demangler::demangleRttiBaseClassDescriptorNode(ArenaAllocator &Arena,
502 StringView &MangledName) {
503 RttiBaseClassDescriptorNode *RBCDN =
504 Arena.alloc();
505 RBCDN->NVOffset = demangleUnsigned(MangledName);
506 RBCDN->VBPtrOffset = demangleSigned(MangledName);
507 RBCDN->VBTableOffset = demangleUnsigned(MangledName);
508 RBCDN->Flags = demangleUnsigned(MangledName);
509 if (Error)
510 return nullptr;
511
512 VariableSymbolNode *VSN = Arena.alloc();
513 VSN->Name = demangleNameScopeChain(MangledName, RBCDN);
514 MangledName.consumeFront('8');
515 return VSN;
516 }
517
518 FunctionSymbolNode *
519 Demangler::demangleDynamicStructorFunction(StringView &MangledName,
520 bool IsDestructor) {
521 DynamicStructorIdentifierNode *DSIN =
522 Arena.alloc();
523 DSIN->IsDestructor = IsDestructor;
524 DSIN->Name = demangleFullyQualifiedTypeName(MangledName);
525 QualifiedNameNode *QNN = synthesizeQualifiedName(Arena, DSIN);
526 FunctionSymbolNode *FSN = demangleFunctionEncoding(MangledName);
527 FSN->Name = QNN;
528 return FSN;
529 }
530
531 SymbolNode *Demangler::demangleSpecialIntrinsic(StringView &MangledName) {
532 SpecialIntrinsicKind SIK = consumeSpecialIntrinsicKind(MangledName);
533 if (SIK == SpecialIntrinsicKind::None)
534 return nullptr;
535
536 switch (SIK) {
537 case SpecialIntrinsicKind::StringLiteralSymbol:
538 return demangleStringLiteral(MangledName);
539 case SpecialIntrinsicKind::Vftable:
540 case SpecialIntrinsicKind::Vbtable:
541 case SpecialIntrinsicKind::LocalVftable:
542 case SpecialIntrinsicKind::RttiCompleteObjLocator:
543 return demangleSpecialTableSymbolNode(MangledName, SIK);
544 case SpecialIntrinsicKind::VcallThunk:
545 return demangleVcallThunkNode(MangledName);
546 case SpecialIntrinsicKind::LocalStaticGuard:
547 return demangleLocalStaticGuard(MangledName);
548 case SpecialIntrinsicKind::RttiTypeDescriptor: {
549 TypeNode *T = demangleType(MangledName, QualifierMangleMode::Result);
1549550 if (Error)
1550551 break;
1551552 if (!MangledName.consumeFront("@8"))
1552 Error = true;
553 break;
1553554 if (!MangledName.empty())
1554 Error = true;
555 break;
556 return synthesizeVariable(Arena, T, "`RTTI Type Descriptor'");
557 }
558 case SpecialIntrinsicKind::RttiBaseClassArray:
559 return demangleUntypedVariable(Arena, MangledName,
560 "`RTTI Base Class Array'");
561 case SpecialIntrinsicKind::RttiClassHierarchyDescriptor:
562 return demangleUntypedVariable(Arena, MangledName,
563 "`RTTI Class Hierarchy Descriptor'");
564 case SpecialIntrinsicKind::RttiBaseClassDescriptor:
565 return demangleRttiBaseClassDescriptorNode(Arena, MangledName);
566 case SpecialIntrinsicKind::DynamicInitializer:
567 return demangleDynamicStructorFunction(MangledName, false);
568 case SpecialIntrinsicKind::DynamicAtexitDestructor:
569 return demangleDynamicStructorFunction(MangledName, true);
570 default:
1555571 break;
1556 default:
1557 if (!Error)
1558 std::tie(S->Category, S->SymbolType) =
1559 demangleSymbolCategoryAndType(MangledName);
572 }
573 Error = true;
574 return nullptr;
575 }
576
577 IdentifierNode *
578 Demangler::demangleFunctionIdentifierCode(StringView &MangledName) {
579 assert(MangledName.startsWith('?'));
580 MangledName = MangledName.dropFront();
581
582 if (MangledName.consumeFront("__"))
583 return demangleFunctionIdentifierCode(
584 MangledName, FunctionIdentifierCodeGroup::DoubleUnder);
585 else if (MangledName.consumeFront("_"))
586 return demangleFunctionIdentifierCode(MangledName,
587 FunctionIdentifierCodeGroup::Under);
588 return demangleFunctionIdentifierCode(MangledName,
589 FunctionIdentifierCodeGroup::Basic);
590 }
591
592 StructorIdentifierNode *
593 Demangler::demangleStructorIdentifier(StringView &MangledName,
594 bool IsDestructor) {
595 StructorIdentifierNode *N = Arena.alloc();
596 N->IsDestructor = IsDestructor;
597 return N;
598 }
599
600 ConversionOperatorIdentifierNode *
601 Demangler::demangleConversionOperatorIdentifier(StringView &MangledName) {
602 ConversionOperatorIdentifierNode *N =
603 Arena.alloc();
604 return N;
605 }
606
607 LiteralOperatorIdentifierNode *
608 Demangler::demangleLiteralOperatorIdentifier(StringView &MangledName) {
609 LiteralOperatorIdentifierNode *N =
610 Arena.alloc();
611 N->Name = demangleSimpleString(MangledName, false);
612 return N;
613 }
614
615 IntrinsicFunctionKind
616 translateIntrinsicFunctionCode(char CH, FunctionIdentifierCodeGroup Group) {
617 // Not all ? identifiers are intrinsics *functions*. This function only maps
618 // operator codes for the special functions, all others are handled elsewhere,
619 // hence the IFK::None entries in the table.
620 using IFK = IntrinsicFunctionKind;
621 static IFK Basic[36] = {
622 IFK::None, // ?0 # Foo::Foo()
623 IFK::None, // ?1 # Foo::~Foo()
624 IFK::New, // ?2 # operator new
625 IFK::Delete, // ?3 # operator delete
626 IFK::Assign, // ?4 # operator=
627 IFK::RightShift, // ?5 # operator>>
628 IFK::LeftShift, // ?6 # operator<<
629 IFK::LogicalNot, // ?7 # operator!
630 IFK::Equals, // ?8 # operator==
631 IFK::NotEquals, // ?9 # operator!=
632 IFK::ArraySubscript, // ?A # operator[]
633 IFK::None, // ?B # Foo::operator ()
634 IFK::Pointer, // ?C # operator->
635 IFK::Dereference, // ?D # operator*
636 IFK::Increment, // ?E # operator++
637 IFK::Decrement, // ?F # operator--
638 IFK::Minus, // ?G # operator-
639 IFK::Plus, // ?H # operator+
640 IFK::BitwiseAnd, // ?I # operator&
641 IFK::MemberPointer, // ?J # operator->*
642 IFK::Divide, // ?K # operator/
643 IFK::Modulus, // ?L # operator%
644 IFK::LessThan, // ?M operator<
645 IFK::LessThanEqual, // ?N operator<=
646 IFK::GreaterThan, // ?O operator>
647 IFK::GreaterThanEqual, // ?P operator>=
648 IFK::Comma, // ?Q operator,
649 IFK::Parens, // ?R operator()
650 IFK::BitwiseNot, // ?S operator~
651 IFK::BitwiseXor, // ?T operator^
652 IFK::BitwiseOr, // ?U operator|
653 IFK::LogicalAnd, // ?V operator&&
654 IFK::LogicalOr, // ?W operator||
655 IFK::TimesEqual, // ?X operator*=
656 IFK::PlusEqual, // ?Y operator+=
657 IFK::MinusEqual, // ?Z operator-=
658 };
659 static IFK Under[36] = {
660 IFK::DivEqual, // ?_0 operator/=
661 IFK::ModEqual, // ?_1 operator%=
662 IFK::RshEqual, // ?_2 operator>>=
663 IFK::LshEqual, // ?_3 operator<<=
664 IFK::BitwiseAndEqual, // ?_4 operator&=
665 IFK::BitwiseOrEqual, // ?_5 operator|=
666 IFK::BitwiseXorEqual, // ?_6 operator^=
667 IFK::None, // ?_7 # vftable
668 IFK::None, // ?_8 # vbtable
669 IFK::None, // ?_9 # vcall
670 IFK::None, // ?_A # typeof
671 IFK::None, // ?_B # local static guard
672 IFK::None, // ?_C # string literal
673 IFK::VbaseDtor, // ?_D # vbase destructor
674 IFK::VecDelDtor, // ?_E # vector deleting destructor
675 IFK::DefaultCtorClosure, // ?_F # default constructor closure
676 IFK::ScalarDelDtor, // ?_G # scalar deleting destructor
677 IFK::VecCtorIter, // ?_H # vector constructor iterator
678 IFK::VecDtorIter, // ?_I # vector destructor iterator
679 IFK::VecVbaseCtorIter, // ?_J # vector vbase constructor iterator
680 IFK::VdispMap, // ?_K # virtual displacement map
681 IFK::EHVecCtorIter, // ?_L # eh vector constructor iterator
682 IFK::EHVecDtorIter, // ?_M # eh vector destructor iterator
683 IFK::EHVecVbaseCtorIter, // ?_N # eh vector vbase constructor iterator
684 IFK::CopyCtorClosure, // ?_O # copy constructor closure
685 IFK::None, // ?_P # udt returning
686 IFK::None, // ?_Q #
687 IFK::None, // ?_R0 - ?_R4 # RTTI Codes
688 IFK::None, // ?_S # local vftable
689 IFK::LocalVftableCtorClosure, // ?_T # local vftable constructor closure
690 IFK::ArrayNew, // ?_U operator new[]
691 IFK::ArrayDelete, // ?_V operator delete[]
692 IFK::None, // ?_W
693 IFK::None, // ?_X
694 IFK::None, // ?_Y
695 IFK::None, // ?_Z
696 };
697 static IFK DoubleUnder[36] = {
698 IFK::None, // ?__0
699 IFK::None, // ?__1
700 IFK::None, // ?__2
701 IFK::None, // ?__3
702 IFK::None, // ?__4
703 IFK::None, // ?__5
704 IFK::None, // ?__6
705 IFK::None, // ?__7
706 IFK::None, // ?__8
707 IFK::None, // ?__9
708 IFK::ManVectorCtorIter, // ?__A managed vector ctor iterator
709 IFK::ManVectorDtorIter, // ?__B managed vector dtor iterator
710 IFK::EHVectorCopyCtorIter, // ?__C EH vector copy ctor iterator
711 IFK::EHVectorVbaseCopyCtorIter, // ?__D EH vector vbase copy ctor iter
712 IFK::None, // ?__E dynamic initializer for `T'
713 IFK::None, // ?__F dynamic atexit destructor for `T'
714 IFK::VectorCopyCtorIter, // ?__G vector copy constructor iter
715 IFK::VectorVbaseCopyCtorIter, // ?__H vector vbase copy ctor iter
716 IFK::ManVectorVbaseCopyCtorIter, // ?__I managed vector vbase copy ctor
717 // iter
718 IFK::None, // ?__J local static thread guard
719 IFK::None, // ?__K operator ""_name
720 IFK::CoAwait, // ?__L co_await
721 IFK::None, // ?__M
722 IFK::None, // ?__N
723 IFK::None, // ?__O
724 IFK::None, // ?__P
725 IFK::None, // ?__Q
726 IFK::None, // ?__R
727 IFK::None, // ?__S
728 IFK::None, // ?__T
729 IFK::None, // ?__U
730 IFK::None, // ?__V
731 IFK::None, // ?__W
732 IFK::None, // ?__X
733 IFK::None, // ?__Y
734 IFK::None, // ?__Z
735 };
736
737 int Index = (CH >= '0' && CH <= '9') ? (CH - '0') : (CH - 'A' + 10);
738 switch (Group) {
739 case FunctionIdentifierCodeGroup::Basic:
740 return Basic[Index];
741 case FunctionIdentifierCodeGroup::Under:
742 return Under[Index];
743 case FunctionIdentifierCodeGroup::DoubleUnder:
744 return DoubleUnder[Index];
745 }
746 LLVM_BUILTIN_UNREACHABLE;
747 }
748
749 IdentifierNode *
750 Demangler::demangleFunctionIdentifierCode(StringView &MangledName,
751 FunctionIdentifierCodeGroup Group) {
752 switch (Group) {
753 case FunctionIdentifierCodeGroup::Basic:
754 switch (char CH = MangledName.popFront()) {
755 case '0':
756 case '1':
757 return demangleStructorIdentifier(MangledName, CH == '1');
758 case 'B':
759 return demangleConversionOperatorIdentifier(MangledName);
760 default:
761 return Arena.alloc(
762 translateIntrinsicFunctionCode(CH, Group));
763 }
1560764 break;
1561 }
1562
1563 return (Error) ? nullptr : S;
1564 }
1565
1566 std::pair
1567 Demangler::demangleSymbolCategoryAndType(StringView &MangledName) {
765 case FunctionIdentifierCodeGroup::Under:
766 return Arena.alloc(
767 translateIntrinsicFunctionCode(MangledName.popFront(), Group));
768 case FunctionIdentifierCodeGroup::DoubleUnder:
769 switch (char CH = MangledName.popFront()) {
770 case 'K':
771 return demangleLiteralOperatorIdentifier(MangledName);
772 default:
773 return Arena.alloc(
774 translateIntrinsicFunctionCode(CH, Group));
775 }
776 }
777 // No Mangling Yet: Spaceship, // operator<=>
778
779 return nullptr;
780 }
781
782 SymbolNode *Demangler::demangleEncodedSymbol(StringView &MangledName,
783 QualifiedNameNode *Name) {
1568784 // Read a variable.
1569785 switch (MangledName.front()) {
1570786 case '0':
1571787 case '1':
1572788 case '2':
1573789 case '3':
1574 case '4':
1575 return std::make_pair(
1576 SymbolCategory::NamedVariable,
1577 demangleVariableEncoding(MangledName,
1578 demangleVariableStorageClass(MangledName)));
790 case '4': {
791 StorageClass SC = demangleVariableStorageClass(MangledName);
792 return demangleVariableEncoding(MangledName, SC);
793 }
1579794 case '8':
1580 MangledName.consumeFront('8');
1581 return std::pair(SymbolCategory::UnnamedVariable,
1582 nullptr);
1583 }
1584 return std::make_pair(SymbolCategory::NamedFunction,
1585 demangleFunctionEncoding(MangledName));
795 return nullptr;
796 }
797 FunctionSymbolNode *FSN = demangleFunctionEncoding(MangledName);
798
799 IdentifierNode *UQN = Name->getUnqualifiedIdentifier();
800 if (UQN->kind() == NodeKind::ConversionOperatorIdentifier) {
801 ConversionOperatorIdentifierNode *COIN =
802 static_cast(UQN);
803 COIN->TargetType = FSN->Signature->ReturnType;
804 }
805 return FSN;
1586806 }
1587807
1588808 // Parser entry point.
1589 Symbol *Demangler::parse(StringView &MangledName) {
809 SymbolNode *Demangler::parse(StringView &MangledName) {
1590810 // We can't demangle MD5 names, just output them as-is.
1591811 // Also, MSVC-style mangled symbols must start with '?'.
1592 if (MangledName.startsWith("??@") || !MangledName.startsWith('?')) {
1593 Symbol *S = Arena.alloc();
1594 S->Category = SymbolCategory::Unknown;
1595 S->SymbolName = Arena.alloc();
1596 S->SymbolName->Str = MangledName;
1597 S->SymbolType = nullptr;
1598 MangledName = StringView();
812 if (MangledName.startsWith("??@")) {
813 // This is an MD5 mangled name. We can't demangle it, just return the
814 // mangled name.
815 SymbolNode *S = Arena.alloc(NodeKind::Md5Symbol);
816 S->Name = synthesizeQualifiedName(Arena, MangledName);
1599817 return S;
818 }
819
820 if (!MangledName.startsWith('?')) {
821 Error = true;
822 return nullptr;
1600823 }
1601824
1602825 MangledName.consumeFront('?');
1603826
1604827 // ?$ is a template instantiation, but all other names that start with ? are
1605828 // operators / special names.
1606 if (MangledName.startsWith('?') && !MangledName.startsWith("?$"))
1607 return parseOperator(MangledName);
1608
1609 Symbol *S = Arena.alloc();
829 if (SymbolNode *SI = demangleSpecialIntrinsic(MangledName))
830 return SI;
831
1610832 // What follows is a main symbol name. This may include namespaces or class
1611833 // back references.
1612 S->SymbolName = demangleFullyQualifiedSymbolName(MangledName);
834 QualifiedNameNode *QN = demangleFullyQualifiedSymbolName(MangledName);
835
836 SymbolNode *Symbol = demangleEncodedSymbol(MangledName, QN);
837 if (Symbol) {
838 Symbol->Name = QN;
839 }
840
1613841 if (Error)
1614842 return nullptr;
1615843
1616 std::tie(S->Category, S->SymbolType) =
1617 demangleSymbolCategoryAndType(MangledName);
1618
1619 if (Error)
1620 return nullptr;
1621
1622 return S;
844 return Symbol;
1623845 }
1624846
1625847 // ::=
1629851 // ::= 3 # global
1630852 // ::= 4 # static local
1631853
1632 Type *Demangler::demangleVariableEncoding(StringView &MangledName,
1633 StorageClass SC) {
1634 Type *Ty = demangleType(MangledName, QualifierMangleMode::Drop);
1635
1636 Ty->Storage = SC;
854 VariableSymbolNode *Demangler::demangleVariableEncoding(StringView &MangledName,
855 StorageClass SC) {
856 VariableSymbolNode *VSN = Arena.alloc();
857
858 VSN->Type = demangleType(MangledName, QualifierMangleMode::Drop);
859 VSN->SC = SC;
1637860
1638861 // ::=
1639862 // ::= # pointers, references
1640 switch (Ty->Prim) {
1641 case PrimTy::Ptr:
1642 case PrimTy::MemberPtr: {
863 switch (VSN->Type->kind()) {
864 case NodeKind::PointerType: {
865 PointerTypeNode *PTN = static_cast(VSN->Type);
866
1643867 Qualifiers ExtraChildQuals = Q_None;
1644 Ty->Quals =
1645 Qualifiers(Ty->Quals | demanglePointerExtQualifiers(MangledName));
868 PTN->Quals = Qualifiers(VSN->Type->Quals |
869 demanglePointerExtQualifiers(MangledName));
1646870
1647871 bool IsMember = false;
1648872 std::tie(ExtraChildQuals, IsMember) = demangleQualifiers(MangledName);
1649873
1650 if (Ty->Prim == PrimTy::MemberPtr) {
1651 assert(IsMember);
1652 Name *BackRefName = demangleFullyQualifiedTypeName(MangledName);
874 if (PTN->ClassParent) {
875 QualifiedNameNode *BackRefName =
876 demangleFullyQualifiedTypeName(MangledName);
1653877 (void)BackRefName;
1654 MemberPointerType *MPTy = static_cast(Ty);
1655 MPTy->Pointee->Quals = Qualifiers(MPTy->Pointee->Quals | ExtraChildQuals);
1656 } else {
1657 PointerType *PTy = static_cast(Ty);
1658 PTy->Pointee->Quals = Qualifiers(PTy->Pointee->Quals | ExtraChildQuals);
1659878 }
879 PTN->Pointee->Quals = Qualifiers(PTN->Pointee->Quals | ExtraChildQuals);
1660880
1661881 break;
1662882 }
1663883 default:
1664 Ty->Quals = demangleQualifiers(MangledName).first;
884 VSN->Type->Quals = demangleQualifiers(MangledName).first;
1665885 break;
1666886 }
1667887
1668 return Ty;
888 return VSN;
1669889 }
1670890
1671891 // Sometimes numbers are encoded in mangled symbols. For example,
1731951 if (Backrefs.NamesCount >= BackrefContext::Max)
1732952 return;
1733953 for (size_t i = 0; i < Backrefs.NamesCount; ++i)
1734 if (S == Backrefs.Names[i])
954 if (S == Backrefs.Names[i]->Name)
1735955 return;
1736 Backrefs.Names[Backrefs.NamesCount++] = S;
1737 }
1738
1739 Name *Demangler::demangleBackRefName(StringView &MangledName) {
956 NamedIdentifierNode *N = Arena.alloc();
957 N->Name = S;
958 Backrefs.Names[Backrefs.NamesCount++] = N;
959 }
960
961 NamedIdentifierNode *Demangler::demangleBackRefName(StringView &MangledName) {
1740962 assert(startsWithDigit(MangledName));
1741963
1742964 size_t I = MangledName[0] - '0';
1746968 }
1747969
1748970 MangledName = MangledName.dropFront();
1749 Name *Node = Arena.alloc();
1750 Node->Str = Backrefs.Names[I];
1751 return Node;
1752 }
1753
1754 Name *Demangler::demangleTemplateInstantiationName(StringView &MangledName,
1755 NameBackrefBehavior NBB) {
971 return Backrefs.Names[I];
972 }
973
974 IdentifierNode *
975 Demangler::demangleTemplateInstantiationName(StringView &MangledName,
976 NameBackrefBehavior NBB) {
1756977 assert(MangledName.startsWith("?$"));
1757978 MangledName.consumeFront("?$");
1758979
1759980 BackrefContext OuterContext;
1760981 std::swap(OuterContext, Backrefs);
1761982
1762 Name *Node = demangleUnqualifiedSymbolName(MangledName, NBB_Simple);
983 IdentifierNode *Identifier =
984 demangleUnqualifiedSymbolName(MangledName, NBB_Simple);
1763985 if (!Error)
1764 Node->TParams = demangleTemplateParameterList(MangledName);
986 Identifier->TemplateParams = demangleTemplateParameterList(MangledName);
1765987
1766988 std::swap(OuterContext, Backrefs);
1767989 if (Error)
1768990 return nullptr;
1769
1770 Node->IsTemplateInstantiation = true;
1771991
1772992 if (NBB & NBB_Template) {
1773993 // Render this class template name into a string buffer so that we can
1774994 // memorize it for the purpose of back-referencing.
1775995 OutputStream OS = OutputStream::create(nullptr, nullptr, 1024);
1776 outputName(OS, Node, nullptr);
996 Identifier->output(OS);
1777997 OS << '\0';
1778998 char *Name = OS.getBuffer();
1779999
17821002 std::free(Name);
17831003 }
17841004
1785 return Node;
1786 }
1787
1788 std::pair
1789 Demangler::demangleOperatorName(StringView &MangledName, bool FullyQualified) {
1790 assert(MangledName.startsWith('?'));
1791 MangledName.consumeFront('?');
1792
1793 const OperatorMapEntry *Entry = nullptr;
1794 for (const auto &MapEntry : OperatorMap) {
1795 if (!MangledName.consumeFront(MapEntry.Prefix))
1796 continue;
1797 Entry = &MapEntry;
1798 break;
1799 }
1800 if (!Entry) {
1801 Error = true;
1802 return std::make_pair(OperatorTy::Unknown, nullptr);
1803 }
1804
1805 Name *N = nullptr;
1806 switch (Entry->Operator) {
1807 case OperatorTy::Vftable: // Foo@@6B@
1808 case OperatorTy::LocalVftable: // Foo@@6B@
1809 case OperatorTy::RttiCompleteObjLocator: // Foo@@6B@
1810 case OperatorTy::Vbtable: { // Foo@@7B@
1811 N = Arena.alloc(*Entry);
1812 if (FullyQualified)
1813 N = demangleNameScopeChain(MangledName, N);
1814 break;
1815 }
1816
1817 case OperatorTy::StringLiteral:
1818 N = demangleStringLiteral(MangledName);
1819 break;
1820 case OperatorTy::LiteralOperator:
1821 N = Arena.alloc(*Entry);
1822 N->Str = demangleSimpleString(MangledName, false);
1823 if (!MangledName.consumeFront('@'))
1824 Error = true;
1825 break;
1826 case OperatorTy::RttiBaseClassDescriptor: {
1827 RttiBaseClassDescriptor *Temp = Arena.alloc();
1828 Temp->NVOffset = demangleUnsigned(MangledName);
1829 Temp->VBPtrOffset = demangleSigned(MangledName);
1830 Temp->VBTableOffset = demangleUnsigned(MangledName);
1831 Temp->Flags = demangleUnsigned(MangledName);
1832 N = (FullyQualified) ? demangleNameScopeChain(MangledName, Temp) : Temp;
1833 break;
1834 }
1835 case OperatorTy::Vcall: {
1836 VirtualMemberPtrThunk *Temp = Arena.alloc();
1837 N = demangleNameScopeChain(MangledName, Temp);
1838 if (Error)
1839 break;
1840 if (!MangledName.consumeFront("$B"))
1841 Error = true;
1842 Temp->OffsetInVTable = demangleUnsigned(MangledName);
1843 if (!MangledName.consumeFront('A'))
1844 Error = true;
1845 Temp->CC = demangleCallingConvention(MangledName);
1846 break;
1847 }
1848 case OperatorTy::RttiTypeDescriptor:
1849 // This one is just followed by a type, not a name scope.
1850 N = Arena.alloc(*Entry);
1851 break;
1852 case OperatorTy::LocalStaticGuard: {
1853 LocalStaticGuardVariable *Temp = Arena.alloc();
1854 N = (FullyQualified) ? demangleNameScopeChain(MangledName, Temp) : Temp;
1855 if (MangledName.consumeFront("4IA"))
1856 Temp->IsVisible = false;
1857 else if (MangledName.consumeFront("5"))
1858 Temp->IsVisible = true;
1859 else
1860 Error = true;
1861 if (!MangledName.empty())
1862 Temp->ScopeIndex = demangleUnsigned(MangledName);
1863 break;
1864 }
1865 default:
1866 N = Arena.alloc(*Entry);
1867 N = (FullyQualified) ? demangleNameScopeChain(MangledName, N) : N;
1868 break;
1869 }
1870 if (Error)
1871 return std::make_pair(OperatorTy::Unknown, nullptr);
1872
1873 return std::make_pair(Entry->Operator, N);
1874 }
1875
1876 Name *Demangler::demangleSimpleName(StringView &MangledName, bool Memorize) {
1005 return Identifier;
1006 }
1007
1008 NamedIdentifierNode *Demangler::demangleSimpleName(StringView &MangledName,
1009 bool Memorize) {
18771010 StringView S = demangleSimpleString(MangledName, Memorize);
18781011 if (Error)
18791012 return nullptr;
18801013
1881 Name *Node = Arena.alloc();
1882 Node->Str = S;
1883 return Node;
1014 NamedIdentifierNode *Name = Arena.alloc();
1015 Name->Name = S;
1016 return Name;
18841017 }
18851018
18861019 static bool isRebasedHexDigit(char C) { return (C >= 'A' && C <= 'P'); }
21061239 return Result;
21071240 }
21081241
2109 StringLiteral *Demangler::demangleStringLiteral(StringView &MangledName) {
1242 FunctionSymbolNode *Demangler::demangleVcallThunkNode(StringView &MangledName) {
1243 FunctionSymbolNode *FSN = Arena.alloc();
1244 VcallThunkIdentifierNode *VTIN = Arena.alloc();
1245 FSN->Signature = Arena.alloc();
1246 FSN->Signature->FunctionClass = FC_NoParameterList;
1247
1248 FSN->Name = demangleNameScopeChain(MangledName, VTIN);
1249 if (!Error)
1250 Error = !MangledName.consumeFront("$B");
1251 if (!Error)
1252 VTIN->OffsetInVTable = demangleUnsigned(MangledName);
1253 if (!Error)
1254 Error = !MangledName.consumeFront('A');
1255 if (!Error)
1256 FSN->Signature->CallConvention = demangleCallingConvention(MangledName);
1257 return (Error) ? nullptr : FSN;
1258 }
1259
1260 EncodedStringLiteralNode *
1261 Demangler::demangleStringLiteral(StringView &MangledName) {
21101262 // This function uses goto, so declare all variables up front.
21111263 OutputStream OS;
21121264 StringView CRC;
21161268 size_t CrcEndPos = 0;
21171269 char *ResultBuffer = nullptr;
21181270
2119 StringLiteral *Result = Arena.alloc>();
1271 EncodedStringLiteralNode *Result = Arena.alloc>();
21201272
21211273 // Prefix indicating the beginning of a string literal
21221274 if (!MangledName.consumeFront("@_"))
21511303
21521304 OS = OutputStream::create(nullptr, nullptr, 1024);
21531305 if (IsWcharT) {
2154 Result->CharType = PrimTy::Wchar;
1306 Result->Char = CharKind::Wchar;
21551307 if (StringByteSize > 64)
21561308 Result->IsTruncated = true;
21571309
21821334 assert(StringByteSize % CharBytes == 0);
21831335 switch (CharBytes) {
21841336 case 1:
2185 Result->CharType = PrimTy::Char;
1337 Result->Char = CharKind::Char;
21861338 break;
21871339 case 2:
2188 Result->CharType = PrimTy::Char16;
1340 Result->Char = CharKind::Char16;
21891341 break;
21901342 case 4:
2191 Result->CharType = PrimTy::Char32;
1343 Result->Char = CharKind::Char32;
21921344 break;
21931345 default:
21941346 LLVM_BUILTIN_UNREACHABLE;
22041356
22051357 OS << '\0';
22061358 ResultBuffer = OS.getBuffer();
2207 Result->Str = copyString(ResultBuffer);
1359 Result->DecodedString = copyString(ResultBuffer);
22081360 std::free(ResultBuffer);
22091361 return Result;
22101362
22311383 return {};
22321384 }
22331385
2234 Name *Demangler::demangleAnonymousNamespaceName(StringView &MangledName) {
1386 NamedIdentifierNode *
1387 Demangler::demangleAnonymousNamespaceName(StringView &MangledName) {
22351388 assert(MangledName.startsWith("?A"));
22361389 MangledName.consumeFront("?A");
22371390
2238 Name *Node = Arena.alloc();
2239 Node->Str = "`anonymous namespace'";
1391 NamedIdentifierNode *Node = Arena.alloc();
1392 Node->Name = "`anonymous namespace'";
22401393 size_t EndPos = MangledName.find('@');
22411394 if (EndPos == StringView::npos) {
22421395 Error = true;
22481401 return Node;
22491402 }
22501403
2251 Name *Demangler::demangleLocallyScopedNamePiece(StringView &MangledName) {
1404 NamedIdentifierNode *
1405 Demangler::demangleLocallyScopedNamePiece(StringView &MangledName) {
22521406 assert(startsWithLocalScopePattern(MangledName));
22531407
2254 Name *Node = Arena.alloce>();
1408 NamedIdentifierNode *Identifier = Arena.alloce>();
22551409 MangledName.consumeFront('?');
22561410 auto Number = demangleNumber(MangledName);
22571411 assert(!Number.second);
22601414 MangledName.consumeFront('?');
22611415
22621416 assert(!Error);
2263 Symbol *Scope = parse(MangledName);
1417 Node *Scope = parse(MangledName);
22641418 if (Error)
22651419 return nullptr;
22661420
22671421 // Render the parent symbol's name into a buffer.
22681422 OutputStream OS = OutputStream::create(nullptr, nullptr, 1024);
22691423 OS << '`';
2270 output(Scope, OS);
1424 Scope->output(OS);
22711425 OS << '\'';
22721426 OS << "::`" << Number.first << "'";
22731427 OS << '\0';
22741428 char *Result = OS.getBuffer();
2275 Node->Str = copyString(Result);
1429 Identifier->Name = copyString(Result);
22761430 std::free(Result);
2277 return Node;
1431 return Identifier;
22781432 }
22791433
22801434 // Parses a type name in the form of A@B@C@@ which represents C::B::A.
2281 Name *Demangler::demangleFullyQualifiedTypeName(StringView &MangledName) {
2282 Name *TypeName = demangleUnqualifiedTypeName(MangledName, true);
1435 QualifiedNameNode *
1436 Demangler::demangleFullyQualifiedTypeName(StringView &MangledName) {
1437 IdentifierNode *Identifier = demangleUnqualifiedTypeName(MangledName, true);
22831438 if (Error)
22841439 return nullptr;
2285 assert(TypeName);
2286
2287 Name *QualName = demangleNameScopeChain(MangledName, TypeName);
1440 assert(Identifier);
1441
1442 QualifiedNameNode *QN = demangleNameScopeChain(MangledName, Identifier);
22881443 if (Error)
22891444 return nullptr;
2290 assert(QualName);
2291 return QualName;
1445 assert(QN);
1446 return QN;
22921447 }
22931448
22941449 // Parses a symbol name in the form of A@B@C@@ which represents C::B::A.
22951450 // Symbol names have slightly different rules regarding what can appear
22961451 // so we separate out the implementations for flexibility.
2297 Name *Demangler::demangleFullyQualifiedSymbolName(StringView &MangledName) {
1452 QualifiedNameNode *
1453 Demangler::demangleFullyQualifiedSymbolName(StringView &MangledName) {
22981454 // This is the final component of a symbol name (i.e. the leftmost component
22991455 // of a mangled name. Since the only possible template instantiation that
23001456 // can appear in this context is a function template, and since those are
23011457 // not saved for the purposes of name backreferences, only backref simple
23021458 // names.
2303 Name *SymbolName = demangleUnqualifiedSymbolName(MangledName, NBB_Simple);
1459 IdentifierNode *Identifier =
1460 demangleUnqualifiedSymbolName(MangledName, NBB_Simple);
23041461 if (Error)
23051462 return nullptr;
23061463
2307 Name *QualName = demangleNameScopeChain(MangledName, SymbolName);
1464 QualifiedNameNode *QN = demangleNameScopeChain(MangledName, Identifier);
23081465 if (Error)
23091466 return nullptr;
2310 assert(QualName);
2311 return QualName;
2312 }
2313
2314 Name *Demangler::demangleUnqualifiedTypeName(StringView &MangledName,
2315 bool Memorize) {
1467
1468 if (Identifier->kind() == NodeKind::StructorIdentifier) {
1469 StructorIdentifierNode *SIN =
1470 static_cast(Identifier);
1471 assert(QN->Components->Count >= 2);
1472 Node *ClassNode = QN->Components->Nodes[QN->Components->Count - 2];
1473 SIN->Class = static_cast(ClassNode);
1474 }
1475 assert(QN);
1476 return QN;
1477 }
1478
1479 IdentifierNode *Demangler::demangleUnqualifiedTypeName(StringView &MangledName,
1480 bool Memorize) {
23161481 // An inner-most name can be a back-reference, because a fully-qualified name
23171482 // (e.g. Scope + Inner) can contain other fully qualified names inside of
23181483 // them (for example template parameters), and these nested parameters can
23261491 return demangleSimpleName(MangledName, Memorize);
23271492 }
23281493
2329 Name *Demangler::demangleUnqualifiedSymbolName(StringView &MangledName,
2330 NameBackrefBehavior NBB) {
1494 IdentifierNode *
1495 Demangler::demangleUnqualifiedSymbolName(StringView &MangledName,
1496 NameBackrefBehavior NBB) {
23311497 if (startsWithDigit(MangledName))
23321498 return demangleBackRefName(MangledName);
23331499 if (MangledName.startsWith("?$"))
23341500 return demangleTemplateInstantiationName(MangledName, NBB);
23351501 if (MangledName.startsWith('?'))
2336 return demangleOperatorName(MangledName, false).second;
1502 return demangleFunctionIdentifierCode(MangledName);
23371503 return demangleSimpleName(MangledName, (NBB & NBB_Simple) != 0);
23381504 }
23391505
2340 Name *Demangler::demangleNameScopePiece(StringView &MangledName) {
1506 IdentifierNode *Demangler::demangleNameScopePiece(StringView &MangledName) {
23411507 if (startsWithDigit(MangledName))
23421508 return demangleBackRefName(MangledName);
23431509
23531519 return demangleSimpleName(MangledName, true);
23541520 }
23551521
2356 Name *Demangler::demangleNameScopeChain(StringView &MangledName,
2357 Name *UnqualifiedName) {
2358 Name *Head = UnqualifiedName;
2359
1522 static NodeArrayNode *nodeListToNodeArray(ArenaAllocator &Arena, NodeList *Head,
1523 size_t Count) {
1524 NodeArrayNode *N = Arena.alloc();
1525 N->Count = Count;
1526 N->Nodes = Arena.allocArray(Count);
1527 for (size_t I = 0; I < Count; ++I) {
1528 N->Nodes[I] = Head->N;
1529 Head = Head->Next;
1530 }
1531 return N;
1532 }
1533
1534 QualifiedNameNode *
1535 Demangler::demangleNameScopeChain(StringView &MangledName,
1536 IdentifierNode *UnqualifiedName) {
1537 NodeList *Head = Arena.alloc();
1538
1539 Head->N = UnqualifiedName;
1540
1541 size_t Count = 1;
23601542 while (!MangledName.consumeFront("@")) {
1543 ++Count;
1544 NodeList *NewHead = Arena.alloc();
1545 NewHead->Next = Head;
1546 Head = NewHead;
1547
23611548 if (MangledName.empty()) {
23621549 Error = true;
23631550 return nullptr;
23641551 }
23651552
23661553 assert(!Error);
2367 Name *Elem = demangleNameScopePiece(MangledName);
1554 IdentifierNode *Elem = demangleNameScopePiece(MangledName);
23681555 if (Error)
23691556 return nullptr;
23701557
2371 Elem->Next = Head;
2372 Head = Elem;
2373 }
2374 return Head;
1558 Head->N = Elem;
1559 }
1560
1561 QualifiedNameNode *QN = Arena.alloc();
1562 QN->Components = nodeListToNodeArray(Arena, Head, Count);
1563 return QN;
23751564 }
23761565
23771566 FuncClass Demangler::demangleFunctionClass(StringView &MangledName) {
2378 SwapAndRestore RestoreOnError(MangledName, MangledName);
2379 RestoreOnError.shouldRestore(false);
2380
23811567 switch (MangledName.popFront()) {
23821568 case '9':
2383 return FuncClass(ExternC | NoPrototype);
1569 return FuncClass(FC_ExternC | FC_NoParameterList);
23841570 case 'A':
2385 return Private;
1571 return FC_Private;
23861572 case 'B':
2387 return FuncClass(Private | Far);
1573 return FuncClass(FC_Private | FC_Far);
23881574 case 'C':
2389 return FuncClass(Private | Static);
1575 return FuncClass(FC_Private | FC_Static);
23901576 case 'D':
2391 return FuncClass(Private | Static);
1577 return FuncClass(FC_Private | FC_Static);
23921578 case 'E':
2393 return FuncClass(Private | Virtual);
1579 return FuncClass(FC_Private | FC_Virtual);
23941580 case 'F':
2395 return FuncClass(Private | Virtual);
1581 return FuncClass(FC_Private | FC_Virtual);
23961582 case 'I':
2397 return FuncClass(Protected);
1583 return FuncClass(FC_Protected);
23981584 case 'J':
2399 return FuncClass(Protected | Far);
1585 return FuncClass(FC_Protected | FC_Far);
24001586 case 'K':
2401 return FuncClass(Protected | Static);
1587 return FuncClass(FC_Protected | FC_Static);
24021588 case 'L':
2403 return FuncClass(Protected | Static | Far);
1589 return FuncClass(FC_Protected | FC_Static | FC_Far);
24041590 case 'M':
2405 return FuncClass(Protected | Virtual);
1591 return FuncClass(FC_Protected | FC_Virtual);
24061592 case 'N':
2407 return FuncClass(Protected | Virtual | Far);
1593 return FuncClass(FC_Protected | FC_Virtual | FC_Far);
24081594 case 'O':
2409 return FuncClass(Protected | Virtual | StaticThisAdjust);
1595 return FuncClass(FC_Protected | FC_Virtual | FC_StaticThisAdjust);
24101596 case 'P':
2411 return FuncClass(Protected | Virtual | StaticThisAdjust | Far);
1597 return FuncClass(FC_Protected | FC_Virtual | FC_StaticThisAdjust | FC_Far);
24121598 case 'Q':
2413 return FuncClass(Public);
1599 return FuncClass(FC_Public);
24141600 case 'R':
2415 return FuncClass(Public | Far);
1601 return FuncClass(FC_Public | FC_Far);
24161602 case 'S':
2417 return FuncClass(Public | Static);
1603 return FuncClass(FC_Public | FC_Static);
24181604 case 'T':
2419 return FuncClass(Public | Static | Far);
1605 return FuncClass(FC_Public | FC_Static | FC_Far);
24201606 case 'U':
2421 return FuncClass(Public | Virtual);
1607 return FuncClass(FC_Public | FC_Virtual);
24221608 case 'V':
2423 return FuncClass(Public | Virtual | Far);
1609 return FuncClass(FC_Public | FC_Virtual | FC_Far);
24241610 case 'W':
2425 return FuncClass(Public | Virtual | StaticThisAdjust);
1611 return FuncClass(FC_Public | FC_Virtual | FC_StaticThisAdjust);
24261612 case 'X':
2427 return FuncClass(Public | Virtual | StaticThisAdjust | Far);
1613 return FuncClass(FC_Public | FC_Virtual | FC_StaticThisAdjust | FC_Far);
24281614 case 'Y':
2429 return FuncClass(Global);
1615 return FuncClass(FC_Global);
24301616 case 'Z':
2431 return FuncClass(Global | Far);
1617 return FuncClass(FC_Global | FC_Far);
24321618 case '$': {
2433 FuncClass VFlag = VirtualThisAdjust;
1619 FuncClass VFlag = FC_VirtualThisAdjust;
24341620 if (MangledName.consumeFront('R'))
2435 VFlag = FuncClass(VFlag | VirtualThisAdjustEx);
1621 VFlag = FuncClass(VFlag | FC_VirtualThisAdjustEx);
24361622
24371623 switch (MangledName.popFront()) {
24381624 case '0':
2439 return FuncClass(Private | Virtual | VFlag);
1625 return FuncClass(FC_Private | FC_Virtual | VFlag);
24401626 case '1':
2441 return FuncClass(Private | Virtual | VFlag | Far);
1627 return FuncClass(FC_Private | FC_Virtual | VFlag | FC_Far);
24421628 case '2':
2443 return FuncClass(Protected | Virtual | VFlag);
1629 return FuncClass(FC_Protected | FC_Virtual | VFlag);
24441630 case '3':
2445 return FuncClass(Protected | Virtual | VFlag | Far);
1631 return FuncClass(FC_Protected | FC_Virtual | VFlag | FC_Far);
24461632 case '4':
2447 return FuncClass(Public | Virtual | VFlag);
1633 return FuncClass(FC_Public | FC_Virtual | VFlag);
24481634 case '5':
2449 return FuncClass(Public | Virtual | VFlag | Far);
1635 return FuncClass(FC_Public | FC_Virtual | VFlag | FC_Far);
24501636 }
24511637 }
24521638 }
24531639
24541640 Error = true;
2455 RestoreOnError.shouldRestore(true);
2456 return Public;
1641 return FC_Public;
24571642 }
24581643
24591644 CallingConv Demangler::demangleCallingConvention(StringView &MangledName) {
25321717 return std::make_pair(Q_None, false);
25331718 }
25341719
2535 static bool isTagType(StringView S) {
2536 switch (S.front()) {
2537 case 'T': // union
2538 case 'U': // struct
2539 case 'V': // class
2540 case 'W': // enum
2541 return true;
2542 }
2543 return false;
2544 }
2545
2546 static bool isPointerType(StringView S) {
2547 if (S.startsWith("$$Q")) // foo &&
2548 return true;
2549
2550 switch (S.front()) {
2551 case 'A': // foo &
2552 case 'P': // foo *
2553 case 'Q': // foo *const
2554 case 'R': // foo *volatile
2555 case 'S': // foo *const volatile
2556 return true;
2557 }
2558 return false;
2559 }
2560
2561 static bool isArrayType(StringView S) { return S[0] == 'Y'; }
2562
2563 static bool isFunctionType(StringView S) {
2564 return S.startsWith("$$A8@@") || S.startsWith("$$A6");
2565 }
2566
25671720 // ::=
25681721 // ::= # pointers, references
2569 Type *Demangler::demangleType(StringView &MangledName,
2570 QualifierMangleMode QMM) {
1722 TypeNode *Demangler::demangleType(StringView &MangledName,
1723 QualifierMangleMode QMM) {
25711724 Qualifiers Quals = Q_None;
25721725 bool IsMember = false;
25731726 if (QMM == QualifierMangleMode::Mangle) {
25771730 std::tie(Quals, IsMember) = demangleQualifiers(MangledName);
25781731 }
25791732
2580 Type *Ty = nullptr;
1733 TypeNode *Ty = nullptr;
25811734 if (isTagType(MangledName))
25821735 Ty = demangleClassType(MangledName);
25831736 else if (isPointerType(MangledName)) {
25891742 Ty = demangleArrayType(MangledName);
25901743 else if (isFunctionType(MangledName)) {
25911744 if (MangledName.consumeFront("$$A8@@"))
2592 Ty = demangleFunctionType(MangledName, true, false);
1745 Ty = demangleFunctionType(MangledName, true);
25931746 else {
25941747 assert(MangledName.startsWith("$$A6"));
25951748 MangledName.consumeFront("$$A6");
2596 Ty = demangleFunctionType(MangledName, false, false);
1749 Ty = demangleFunctionType(MangledName, false);
25971750 }
25981751 } else {
2599 Ty = demangleBasicType(MangledName);
1752 Ty = demanglePrimitiveType(MangledName);
26001753 assert(Ty && !Error);
26011754 if (!Ty || Error)
26021755 return Ty;
26061759 return Ty;
26071760 }
26081761
2609 ReferenceKind Demangler::demangleReferenceKind(StringView &MangledName) {
2610 if (MangledName.consumeFront('G'))
2611 return ReferenceKind::LValueRef;
2612 else if (MangledName.consumeFront('H'))
2613 return ReferenceKind::RValueRef;
2614 return ReferenceKind::None;
2615 }
2616
26171762 void Demangler::demangleThrowSpecification(StringView &MangledName) {
26181763 if (MangledName.consumeFront('Z'))
26191764 return;
26211766 Error = true;
26221767 }
26231768
2624 FunctionType *Demangler::demangleFunctionType(StringView &MangledName,
2625 bool HasThisQuals,
2626 bool IsFunctionPointer) {
2627 FunctionType *FTy = Arena.alloc();
2628 FTy->Prim = PrimTy::Function;
2629 FTy->IsFunctionPointer = IsFunctionPointer;
1769 FunctionSignatureNode *Demangler::demangleFunctionType(StringView &MangledName,
1770 bool HasThisQuals) {
1771 FunctionSignatureNode *FTy = Arena.alloc();
26301772
26311773 if (HasThisQuals) {
26321774 FTy->Quals = demanglePointerExtQualifiers(MangledName);
2633 FTy->RefKind = demangleReferenceKind(MangledName);
1775 FTy->RefQualifier = demangleFunctionRefQualifier(MangledName);
26341776 FTy->Quals = Qualifiers(FTy->Quals | demangleQualifiers(MangledName).first);
26351777 }
26361778
26501792 return FTy;
26511793 }
26521794
2653 Type *Demangler::demangleFunctionEncoding(StringView &MangledName) {
2654 FuncClass ExtraFlags = FuncClass::None;
1795 FunctionSymbolNode *
1796 Demangler::demangleFunctionEncoding(StringView &MangledName) {
1797 FuncClass ExtraFlags = FC_None;
26551798 if (MangledName.consumeFront("$$J0"))
2656 ExtraFlags = FuncClass::ExternC;
1799 ExtraFlags = FC_ExternC;
26571800
26581801 FuncClass FC = demangleFunctionClass(MangledName);
26591802 FC = FuncClass(ExtraFlags | FC);
26601803
2661 FunctionType::ThisAdjustor *Adjustor = nullptr;
2662 if (FC & FuncClass::StaticThisAdjust) {
2663 Adjustor = Arena.alloc();
2664 Adjustor->StaticOffset = demangleSigned(MangledName);
2665 } else if (FC & FuncClass::VirtualThisAdjust) {
2666 Adjustor = Arena.alloc();
2667 if (FC & FuncClass::VirtualThisAdjustEx) {
2668 Adjustor->VBPtrOffset = demangleSigned(MangledName);
2669 Adjustor->VBOffsetOffset = demangleSigned(MangledName);
1804 FunctionSignatureNode *FSN = nullptr;
1805 ThunkSignatureNode *TTN = nullptr;
1806 if (FC & FC_StaticThisAdjust) {
1807 TTN = Arena.alloc();
1808 TTN->ThisAdjust.StaticOffset = demangleSigned(MangledName);
1809 } else if (FC & FC_VirtualThisAdjust) {
1810 TTN = Arena.alloc();
1811 if (FC & FC_VirtualThisAdjustEx) {
1812 TTN->ThisAdjust.VBPtrOffset = demangleSigned(MangledName);
1813 TTN->ThisAdjust.VBOffsetOffset = demangleSigned(MangledName);
26701814 }
2671 Adjustor->VtordispOffset = demangleSigned(MangledName);
2672 Adjustor->StaticOffset = demangleSigned(MangledName);
2673 }
2674
2675 FunctionType *FTy = nullptr;
2676 if (FC & NoPrototype) {
1815 TTN->ThisAdjust.VtordispOffset = demangleSigned(MangledName);
1816 TTN->ThisAdjust.StaticOffset = demangleSigned(MangledName);
1817 }
1818
1819 if (FC & FC_NoParameterList) {
26771820 // This is an extern "C" function whose full signature hasn't been mangled.
26781821 // This happens when we need to mangle a local symbol inside of an extern
26791822 // "C" function.
2680 FTy = Arena.alloce>();
1823 FSN = Arena.alloce>();
26811824 } else {
2682 bool HasThisQuals = !(FC & (Global | Static));
2683 FTy = demangleFunctionType(MangledName, HasThisQuals, false);
2684 }
2685 FTy->ThisAdjust = Adjustor;
2686 FTy->FunctionClass = FC;
2687
2688 return FTy;
1825 bool HasThisQuals = !(FC & (FC_Global | FC_Static));
1826 FSN = demangleFunctionType(MangledName, HasThisQuals);
1827 }
1828 if (TTN) {
1829 *static_cast(TTN) = *FSN;
1830 FSN = TTN;
1831 }
1832 FSN->FunctionClass = FC;
1833
1834 FunctionSymbolNode *Symbol = Arena.alloc();
1835 Symbol->Signature = FSN;
1836 return Symbol;
26891837 }
26901838
26911839 // Reads a primitive type.
2692 Type *Demangler::demangleBasicType(StringView &MangledName) {
2693 Type *Ty = Arena.alloc();
2694
2695 if (MangledName.consumeFront("$$T")) {
2696 Ty->Prim = PrimTy::Nullptr;
2697 return Ty;
2698 }
2699 if (MangledName.consumeFront("?")) {
2700 Ty->Prim = PrimTy::Custom;
2701 Ty->Custom = demangleSimpleString(MangledName, false);
2702 if (!MangledName.consumeFront('@')) {
2703 Error = true;
2704 return nullptr;
2705 }
2706 return Ty;
2707 }
1840 PrimitiveTypeNode *Demangler::demanglePrimitiveType(StringView &MangledName) {
1841 if (MangledName.consumeFront("$$T"))
1842 return Arena.alloc(PrimitiveKind::Nullptr);
27081843
27091844 switch (MangledName.popFront()) {
27101845 case 'X':
2711 Ty->Prim = PrimTy::Void;
2712 break;
1846 return Arena.alloc(PrimitiveKind::Void);
27131847 case 'D':
2714 Ty->Prim = PrimTy::Char;
2715 break;
1848 return Arena.alloc(PrimitiveKind::Char);
27161849 case 'C':
2717 Ty->Prim = PrimTy::Schar;
2718 break;
1850 return Arena.alloc(PrimitiveKind::Schar);
27191851 case 'E':
2720 Ty->Prim = PrimTy::Uchar;
2721 break;
1852 return Arena.alloc(PrimitiveKind::Uchar);
27221853 case 'F':
2723 Ty->Prim = PrimTy::Short;
2724 break;
1854 return Arena.alloc(PrimitiveKind::Short);
27251855 case 'G':
2726 Ty->Prim = PrimTy::Ushort;
2727 break;
1856 return Arena.alloc(PrimitiveKind::Ushort);
27281857 case 'H':
2729 Ty->Prim = PrimTy::Int;
2730 break;
1858 return Arena.alloc(PrimitiveKind::Int);
27311859 case 'I':
2732 Ty->Prim = PrimTy::Uint;
2733 break;
1860 return Arena.alloc(PrimitiveKind::Uint);
27341861 case 'J':
2735 Ty->Prim = PrimTy::Long;
2736 break;
1862 return Arena.alloc(PrimitiveKind::Long);
27371863 case 'K':
2738 Ty->Prim = PrimTy::Ulong;
2739 break;
1864 return Arena.alloc(PrimitiveKind::Ulong);
27401865 case 'M':
2741 Ty->Prim = PrimTy::Float;
2742 break;
1866 return Arena.alloc(PrimitiveKind::Float);
27431867 case 'N':
2744 Ty->Prim = PrimTy::Double;
2745 break;
1868 return Arena.alloc(PrimitiveKind::Double);
27461869 case 'O':
2747 Ty->Prim = PrimTy::Ldouble;
2748 break;
1870 return Arena.alloc(PrimitiveKind::Ldouble);
27491871 case '_': {
27501872 if (MangledName.empty()) {
27511873 Error = true;
27531875 }
27541876 switch (MangledName.popFront()) {
27551877 case 'N':
2756 Ty->Prim = PrimTy::Bool;
2757 break;
1878 return Arena.alloc(PrimitiveKind::Bool);
27581879 case 'J':
2759 Ty->Prim = PrimTy::Int64;
2760 break;
1880 return Arena.alloc(PrimitiveKind::Int64);
27611881 case 'K':
2762 Ty->Prim = PrimTy::Uint64;
2763 break;
1882 return Arena.alloc(PrimitiveKind::Uint64);
27641883 case 'W':
2765 Ty->Prim = PrimTy::Wchar;
2766 break;
1884 return Arena.alloc(PrimitiveKind::Wchar);
27671885 case 'S':
2768 Ty->Prim = PrimTy::Char16;
2769 break;
1886 return Arena.alloc(PrimitiveKind::Char16);
27701887 case 'U':
2771 Ty->Prim = PrimTy::Char32;
2772 break;
2773 default:
2774 Error = true;
2775 return nullptr;
1888 return Arena.alloc(PrimitiveKind::Char32);
27761889 }
27771890 break;
27781891 }
2779 default:
2780 Error = true;
2781 return nullptr;
2782 }
2783 return Ty;
2784 }
2785
2786 UdtType *Demangler::demangleClassType(StringView &MangledName) {
2787 UdtType *UTy = Arena.alloc();
1892 }
1893 Error = true;
1894 return nullptr;
1895 }
1896
1897 TagTypeNode *Demangler::demangleClassType(StringView &MangledName) {
1898 TagTypeNode *TT = nullptr;
27881899
27891900 switch (MangledName.popFront()) {
27901901 case 'T':
2791 UTy->Prim = PrimTy::Union;
1902 TT = Arena.alloc(TagKind::Union);
27921903 break;
27931904 case 'U':
2794 UTy->Prim = PrimTy::Struct;
1905 TT = Arena.alloc(TagKind::Struct);
27951906 break;
27961907 case 'V':
2797 UTy->Prim = PrimTy::Class;
1908 TT = Arena.alloc(TagKind::Class);
27981909 break;
27991910 case 'W':
28001911 if (MangledName.popFront() != '4') {
28011912 Error = true;
28021913 return nullptr;
28031914 }
2804 UTy->Prim = PrimTy::Enum;
1915 TT = Arena.alloc(TagKind::Enum);
28051916 break;
28061917 default:
28071918 assert(false);
28081919 }
28091920
2810 UTy->UdtName = demangleFullyQualifiedTypeName(MangledName);
2811 return UTy;
2812 }
2813
2814 static std::pair
2815 demanglePointerCVQualifiers(StringView &MangledName) {
2816 if (MangledName.consumeFront("$$Q"))
2817 return std::make_pair(Q_None, PointerAffinity::RValueReference);
2818
2819 switch (MangledName.popFront()) {
2820 case 'A':
2821 return std::make_pair(Q_None, PointerAffinity::Reference);
2822 case 'P':
2823 return std::make_pair(Q_None, PointerAffinity::Pointer);
2824 case 'Q':
2825 return std::make_pair(Q_Const, PointerAffinity::Pointer);
2826 case 'R':
2827 return std::make_pair(Q_Volatile, PointerAffinity::Pointer);
2828 case 'S':
2829 return std::make_pair(Qualifiers(Q_Const | Q_Volatile),
2830 PointerAffinity::Pointer);
2831 default:
2832 assert(false && "Ty is not a pointer type!");
2833 }
2834 return std::make_pair(Q_None, PointerAffinity::Pointer);
1921 TT->QualifiedName = demangleFullyQualifiedTypeName(MangledName);
1922 return TT;
28351923 }
28361924
28371925 // ::= E?
28381926 // # the E is required for 64-bit non-static pointers
2839 PointerType *Demangler::demanglePointerType(StringView &MangledName) {
2840 PointerType *Pointer = Arena.alloc();
1927 PointerTypeNode *Demangler::demanglePointerType(StringView &MangledName) {
1928 PointerTypeNode *Pointer = Arena.alloc();
28411929
28421930 std::tie(Pointer->Quals, Pointer->Affinity) =
28431931 demanglePointerCVQualifiers(MangledName);
28441932
2845 Pointer->Prim = PrimTy::Ptr;
28461933 if (MangledName.consumeFront("6")) {
2847 Pointer->Pointee = demangleFunctionType(MangledName, false, true);
1934 Pointer->Pointee = demangleFunctionType(MangledName, false);
28481935 return Pointer;
28491936 }
28501937
28551942 return Pointer;
28561943 }
28571944
2858 MemberPointerType *
2859 Demangler::demangleMemberPointerType(StringView &MangledName) {
2860 MemberPointerType *Pointer = Arena.alloc();
2861 Pointer->Prim = PrimTy::MemberPtr;
2862
2863 PointerAffinity Affinity;
2864 std::tie(Pointer->Quals, Affinity) = demanglePointerCVQualifiers(MangledName);
2865 assert(Affinity == PointerAffinity::Pointer);
1945 PointerTypeNode *Demangler::demangleMemberPointerType(StringView &MangledName) {
1946 PointerTypeNode *Pointer = Arena.alloc();
1947
1948 std::tie(Pointer->Quals, Pointer->Affinity) =
1949 demanglePointerCVQualifiers(MangledName);
1950 assert(Pointer->Affinity == PointerAffinity::Pointer);
28661951
28671952 Qualifiers ExtQuals = demanglePointerExtQualifiers(MangledName);
28681953 Pointer->Quals = Qualifiers(Pointer->Quals | ExtQuals);
28691954
28701955 if (MangledName.consumeFront("8")) {
2871 Pointer->MemberName = demangleFullyQualifiedSymbolName(MangledName);
2872 Pointer->Pointee = demangleFunctionType(MangledName, true, true);
1956 Pointer->ClassParent = demangleFullyQualifiedSymbolName(MangledName);
1957 Pointer->Pointee = demangleFunctionType(MangledName, true);
28731958 } else {
28741959 Qualifiers PointeeQuals = Q_None;
28751960 bool IsMember = false;
28761961 std::tie(PointeeQuals, IsMember) = demangleQualifiers(MangledName);
28771962 assert(IsMember);
2878 Pointer->MemberName = demangleFullyQualifiedSymbolName(MangledName);
1963 Pointer->ClassParent = demangleFullyQualifiedSymbolName(MangledName);
28791964
28801965 Pointer->Pointee = demangleType(MangledName, QualifierMangleMode::Drop);
28811966 Pointer->Pointee->Quals = PointeeQuals;
28961981 return Quals;
28971982 }
28981983
2899 ArrayType *Demangler::demangleArrayType(StringView &MangledName) {
1984 ArrayTypeNode *Demangler::demangleArrayType(StringView &MangledName) {
29001985 assert(MangledName.front() == 'Y');
29011986 MangledName.popFront();
29021987
29081993 return nullptr;
29091994 }
29101995
2911 ArrayType *ATy = Arena.alloc();
2912 ATy->Prim = PrimTy::Array;
2913 ATy->Dims = Arena.alloc();
2914 ArrayDimension *Dim = ATy->Dims;
1996 ArrayTypeNode *ATy = Arena.alloc();
1997 NodeList *Head = Arena.alloc();
1998 NodeList *Tail = Head;
1999
29152000 for (uint64_t I = 0; I < Rank; ++I) {
2916 std::tie(Dim->Dim, IsNegative) = demangleNumber(MangledName);
2001 uint64_t D = 0;
2002 std::tie(D, IsNegative) = demangleNumber(MangledName);
29172003 if (IsNegative) {
29182004 Error = true;
29192005 return nullptr;
29202006 }
2007 Tail->N = Arena.alloc(D, IsNegative);
29212008 if (I + 1 < Rank) {
2922 Dim->Next = Arena.alloc();
2923 Dim = Dim->Next;
2009 Tail->Next = Arena.alloc();
2010 Tail = Tail->Next;
29242011 }
29252012 }
2013 ATy->Dimensions = nodeListToNodeArray(Arena, Head, Rank);
29262014
29272015 if (MangledName.consumeFront("$$C")) {
29282016 bool IsMember = false;
29382026 }
29392027
29402028 // Reads a function or a template parameters.
2941 FunctionParams
2029 NodeArrayNode *
29422030 Demangler::demangleFunctionParameterList(StringView &MangledName) {
29432031 // Empty parameter list.
29442032 if (MangledName.consumeFront('X'))
29452033 return {};
29462034
2947 FunctionParams *Head;
2948 FunctionParams **Current = &Head;
2035 NodeList *Head = Arena.alloc();
2036 NodeList **Current = &Head;
2037 size_t Count = 0;
29492038 while (!Error && !MangledName.startsWith('@') &&
29502039 !MangledName.startsWith('Z')) {
2040 ++Count;
29512041
29522042 if (startsWithDigit(MangledName)) {
29532043 size_t N = MangledName[0] - '0';
29572047 }
29582048 MangledName = MangledName.dropFront();
29592049
2960 *Current = Arena.alloc();
2961 (*Current)->Current = Backrefs.FunctionParams[N]->clone(Arena);
2050 *Current = Arena.alloc();
2051 (*Current)->N = Backrefs.FunctionParams[N];
29622052 Current = &(*Current)->Next;
29632053 continue;
29642054 }
29652055
29662056 size_t OldSize = MangledName.size();
29672057
2968 *Current = Arena.alloc();
2969 (*Current)->Current = demangleType(MangledName, QualifierMangleMode::Drop);
2058 *Current = Arena.alloc();
2059 TypeNode *TN = demangleType(MangledName, QualifierMangleMode::Drop);
2060
2061 (*Current)->N = TN;
29702062
29712063 size_t CharsConsumed = OldSize - MangledName.size();
29722064 assert(CharsConsumed != 0);
29742066 // Single-letter types are ignored for backreferences because memorizing
29752067 // them doesn't save anything.
29762068 if (Backrefs.FunctionParamCount <= 9 && CharsConsumed > 1)
2977 Backrefs.FunctionParams[Backrefs.FunctionParamCount++] =
2978 (*Current)->Current;
2069 Backrefs.FunctionParams[Backrefs.FunctionParamCount++] = TN;
29792070
29802071 Current = &(*Current)->Next;
29812072 }
29832074 if (Error)
29842075 return {};
29852076
2077 NodeArrayNode *NA = nodeListToNodeArray(Arena, Head, Count);
29862078 // A non-empty parameter list is terminated by either 'Z' (variadic) parameter
29872079 // list or '@' (non variadic). Careful not to consume "@Z", as in that case
29882080 // the following Z could be a throw specifier.
29892081 if (MangledName.consumeFront('@'))
2990 return *Head;
2082 return NA;
29912083
29922084 if (MangledName.consumeFront('Z')) {
2993 Head->IsVariadic = true;
2994 return *Head;
2085 // This is a variadic parameter list. We probably need a variadic node to
2086 // append to the end.
2087 return NA;
29952088 }
29962089
29972090 Error = true;
29982091 return {};
29992092 }
30002093
3001 TemplateParams *
2094 NodeArrayNode *
30022095 Demangler::demangleTemplateParameterList(StringView &MangledName) {
3003 TemplateParams *Head;
3004 TemplateParams **Current = &Head;
2096 NodeList *Head;
2097 NodeList **Current = &Head;
2098 size_t Count = 0;
2099
30052100 while (!Error && !MangledName.startsWith('@')) {
2101 ++Count;
30062102 // Template parameter lists don't participate in back-referencing.
3007 *Current = Arena.alloc();
3008
3009 TemplateParams &TP = **Current;
3010
3011 // Empty parameter pack.
2103 *Current = Arena.alloc();
2104
2105 NodeList &TP = **Current;
2106
2107 TemplateParameterReferenceNode *TPRN = nullptr;
30122108 if (MangledName.consumeFront("$S") || MangledName.consumeFront("$$V") ||
30132109 MangledName.consumeFront("$$$V")) {
3014 TP.IsEmptyParameterPack = true;
2110 // Empty parameter pack.
2111 TP.N = nullptr;
30152112 } else if (MangledName.consumeFront("$$Y")) {
30162113 // Template alias
3017 TP.IsTemplateTemplate = true;
3018 TP.IsAliasTemplate = true;
3019 TP.ParamName = demangleFullyQualifiedTypeName(MangledName);
2114 TP.N = demangleFullyQualifiedTypeName(MangledName);
30202115 } else if (MangledName.consumeFront("$$B")) {
30212116 // Array
3022 TP.ParamType = demangleType(MangledName, QualifierMangleMode::Drop);
2117 TP.N = demangleType(MangledName, QualifierMangleMode::Drop);
30232118 } else if (MangledName.consumeFront("$$C")) {
30242119 // Type has qualifiers.
3025 TP.ParamType = demangleType(MangledName, QualifierMangleMode::Mangle);
2120 TP.N = demangleType(MangledName, QualifierMangleMode::Mangle);
30262121 } else if (MangledName.startsWith("$1") || MangledName.startsWith("$H") ||
30272122 MangledName.startsWith("$I") || MangledName.startsWith("$J")) {
2123 // Pointer to member
2124 TP.N = TPRN = Arena.alloc();
2125 TPRN->IsMemberPointer = true;
2126
30282127 MangledName = MangledName.dropFront();
30292128 // 1 - single inheritance
30302129 // H - multiple inheritance
30312130 // I - virtual inheritance
30322131 // J - unspecified inheritance
30332132 char InheritanceSpecifier = MangledName.popFront();
3034 // Pointer to member
3035 Symbol *S = MangledName.startsWith('?') ? parse(MangledName) : nullptr;
2133 SymbolNode *S =
2134 MangledName.startsWith('?') ? parse(MangledName) : nullptr;
30362135 switch (InheritanceSpecifier) {
30372136 case 'J':
3038 TP.ThunkOffsets[TP.ThunkOffsetCount++] = demangleSigned(MangledName);
2137 TPRN->ThunkOffsets[TPRN->ThunkOffsetCount++] =
2138 demangleSigned(MangledName);
30392139 LLVM_FALLTHROUGH;
30402140 case 'I':
3041 TP.ThunkOffsets[TP.ThunkOffsetCount++] = demangleSigned(MangledName);
2141 TPRN->ThunkOffsets[TPRN->ThunkOffsetCount++] =
2142 demangleSigned(MangledName);
30422143 LLVM_FALLTHROUGH;
30432144 case 'H':
3044 TP.ThunkOffsets[TP.ThunkOffsetCount++] = demangleSigned(MangledName);
2145 TPRN->ThunkOffsets[TPRN->ThunkOffsetCount++] =
2146 demangleSigned(MangledName);
30452147 LLVM_FALLTHROUGH;
30462148 case '1':
30472149 break;
30492151 Error = true;
30502152 break;
30512153 }
3052 TP.PointerToSymbol = true;
3053 if (S) {
3054 TP.ParamName = S->SymbolName;
3055 TP.ParamType = S->SymbolType;
3056 } else
3057 TP.NullptrLiteral = true;
2154 TPRN->Affinity = PointerAffinity::Pointer;
2155 TPRN->Symbol = S;
30582156 } else if (MangledName.startsWith("$E?")) {
30592157 MangledName.consumeFront("$E");
30602158 // Reference to symbol
3061 Symbol *S = parse(MangledName);
3062 TP.ParamName = S->SymbolName;
3063 TP.ParamType = S->SymbolType;
3064 TP.ReferenceToSymbol = true;
2159 TP.N = TPRN = Arena.alloc();
2160 TPRN->Symbol = parse(MangledName);
2161 TPRN->Affinity = PointerAffinity::Reference;
30652162 } else if (MangledName.startsWith("$F") || MangledName.startsWith("$G")) {
2163 TP.N = TPRN = Arena.alloc();
2164
30662165 // Data member pointer.
30672166 MangledName = MangledName.dropFront();
30682167 char InheritanceSpecifier = MangledName.popFront();
30692168
30702169 switch (InheritanceSpecifier) {
30712170 case 'G':
3072 TP.ThunkOffsets[TP.ThunkOffsetCount++] = demangleSigned(MangledName);
2171 TPRN->ThunkOffsets[TPRN->ThunkOffsetCount++] =
2172 demangleSigned(MangledName);
30732173 LLVM_FALLTHROUGH;
30742174 case 'F':
3075 TP.ThunkOffsets[TP.ThunkOffsetCount++] = demangleSigned(MangledName);
3076 TP.ThunkOffsets[TP.ThunkOffsetCount++] = demangleSigned(MangledName);
2175 TPRN->ThunkOffsets[TPRN->ThunkOffsetCount++] =
2176 demangleSigned(MangledName);
2177 TPRN->ThunkOffsets[TPRN->ThunkOffsetCount++] =
2178 demangleSigned(MangledName);
30772179 LLVM_FALLTHROUGH;
30782180 case '0':
30792181 break;
30812183 Error = true;
30822184 break;
30832185 }
3084 TP.DataMemberPointer = true;
2186 TPRN->IsMemberPointer = true;
30852187
30862188 } else if (MangledName.consumeFront("$0")) {
30872189 // Integral non-type template parameter
30892191 uint64_t Value = 0;
30902192 std::tie(Value, IsNegative) = demangleNumber(MangledName);
30912193
3092 TP.IsIntegerLiteral = true;
3093 TP.IntegerLiteralIsNegative = IsNegative;
3094 TP.IntegralValue = Value;
2194 TP.N = Arena.alloc(Value, IsNegative);
30952195 } else {
3096 TP.ParamType = demangleType(MangledName, QualifierMangleMode::Drop);
2196 TP.N = demangleType(MangledName, QualifierMangleMode::Drop);
30972197 }
30982198 if (Error)
30992199 return nullptr;
31072207 // Template parameter lists cannot be variadic, so it can only be terminated
31082208 // by @.
31092209 if (MangledName.consumeFront('@'))
3110 return Head;
2210 return nodeListToNodeArray(Arena, Head, Count);
31112211 Error = true;
31122212 return nullptr;
3113 }
3114
3115 void Demangler::output(const Symbol *S, OutputStream &OS) {
3116 if (S->Category == SymbolCategory::Unknown) {
3117 outputName(OS, S->SymbolName, S->SymbolType);
3118 return;
3119 }
3120
3121 if (S->Category == SymbolCategory::SpecialOperator) {
3122 outputSpecialOperator(OS, S->SymbolName);
3123 return;
3124 }
3125
3126 // Converts an AST to a string.
3127 //
3128 // Converting an AST representing a C++ type to a string is tricky due
3129 // to the bad grammar of the C++ declaration inherited from C. You have
3130 // to construct a string from inside to outside. For example, if a type
3131 // X is a pointer to a function returning int, the order you create a
3132 // string becomes something like this:
3133 //
3134 // (1) X is a pointer: *X
3135 // (2) (1) is a function returning int: int (*X)()
3136 //
3137 // So you cannot construct a result just by appending strings to a result.
3138 //
3139 // To deal with this, we split the function into two. outputPre() writes
3140 // the "first half" of type declaration, and outputPost() writes the
3141 // "second half". For example, outputPre() writes a return type for a
3142 // function and outputPost() writes an parameter list.
3143 if (S->SymbolType) {
3144 Type::outputPre(OS, *S->SymbolType);
3145 outputName(OS, S->SymbolName, S->SymbolType);
3146 Type::outputPost(OS, *S->SymbolType);
3147 } else {
3148 outputQualifiers(OS, S->SymbolQuals);
3149 outputName(OS, S->SymbolName, nullptr);
3150 }
31512213 }
31522214
31532215 void Demangler::dumpBackReferences() {
31592221 for (size_t I = 0; I < Backrefs.FunctionParamCount; ++I) {
31602222 OS.setCurrentPosition(0);
31612223
3162 Type *T = Backrefs.FunctionParams[I];
3163 Type::outputPre(OS, *T);
3164 Type::outputPost(OS, *T);
2224 TypeNode *T = Backrefs.FunctionParams[I];
2225 T->output(OS);
31652226
31662227 std::printf(" [%d] - %.*s\n", (int)I, (int)OS.getCurrentPosition(),
31672228 OS.getBuffer());
31722233 std::printf("\n");
31732234 std::printf("%d name backreferences\n", (int)Backrefs.NamesCount);
31742235 for (size_t I = 0; I < Backrefs.NamesCount; ++I) {
3175 std::printf(" [%d] - %.*s\n", (int)I, (int)Backrefs.Names[I].size(),
3176 Backrefs.Names[I].begin());
2236 std::printf(" [%d] - %.*s\n", (int)I, (int)Backrefs.Names[I]->Name.size(),
2237 Backrefs.Names[I]->Name.begin());
31772238 }
31782239 if (Backrefs.NamesCount > 0)
31792240 std::printf("\n");
31832244 int *Status, MSDemangleFlags Flags) {
31842245 Demangler D;
31852246 StringView Name{MangledName};
3186 Symbol *S = D.parse(Name);
2247 SymbolNode *S = D.parse(Name);
31872248
31882249 if (Flags & MSDF_DumpBackrefs)
31892250 D.dumpBackReferences();
31922253 OS << MangledName;
31932254 *Status = llvm::demangle_invalid_mangled_name;
31942255 } else {
3195 D.output(S, OS);
2256 S->output(OS);
31962257 *Status = llvm::demangle_success;
31972258 }
31982259
0 //===- MicrosoftDemangle.cpp ----------------------------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is dual licensed under the MIT and the University of Illinois Open
5 // Source Licenses. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8