1 //===-- Type.cpp ------------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <stdio.h>
10 
11 #include "lldb/Core/Module.h"
12 #include "lldb/Utility/DataBufferHeap.h"
13 #include "lldb/Utility/DataExtractor.h"
14 #include "lldb/Utility/Scalar.h"
15 #include "lldb/Utility/StreamString.h"
16 
17 #include "lldb/Symbol/CompilerType.h"
18 #include "lldb/Symbol/ObjectFile.h"
19 #include "lldb/Symbol/SymbolContextScope.h"
20 #include "lldb/Symbol/SymbolFile.h"
21 #include "lldb/Symbol/SymbolVendor.h"
22 #include "lldb/Symbol/Type.h"
23 #include "lldb/Symbol/TypeList.h"
24 #include "lldb/Symbol/TypeSystem.h"
25 
26 #include "lldb/Target/ExecutionContext.h"
27 #include "lldb/Target/Process.h"
28 #include "lldb/Target/Target.h"
29 
30 #include "llvm/ADT/StringRef.h"
31 
32 #include "clang/AST/Decl.h"
33 #include "clang/AST/DeclObjC.h"
34 
35 using namespace lldb;
36 using namespace lldb_private;
37 
38 void CompilerContext::Dump() const {
39   switch (type) {
40   case CompilerContextKind::Invalid:
41     printf("Invalid");
42     break;
43   case CompilerContextKind::TranslationUnit:
44     printf("TranslationUnit");
45     break;
46   case CompilerContextKind::Module:
47     printf("Module");
48     break;
49   case CompilerContextKind::Namespace:
50     printf("Namespace");
51     break;
52   case CompilerContextKind::Class:
53     printf("Class");
54     break;
55   case CompilerContextKind::Structure:
56     printf("Structure");
57     break;
58   case CompilerContextKind::Union:
59     printf("Union");
60     break;
61   case CompilerContextKind::Function:
62     printf("Function");
63     break;
64   case CompilerContextKind::Variable:
65     printf("Variable");
66     break;
67   case CompilerContextKind::Enumeration:
68     printf("Enumeration");
69     break;
70   case CompilerContextKind::Typedef:
71     printf("Typedef");
72     break;
73   }
74   printf("(\"%s\")\n", name.GetCString());
75 }
76 
77 class TypeAppendVisitor {
78 public:
79   TypeAppendVisitor(TypeListImpl &type_list) : m_type_list(type_list) {}
80 
81   bool operator()(const lldb::TypeSP &type) {
82     m_type_list.Append(TypeImplSP(new TypeImpl(type)));
83     return true;
84   }
85 
86 private:
87   TypeListImpl &m_type_list;
88 };
89 
90 void TypeListImpl::Append(const lldb_private::TypeList &type_list) {
91   TypeAppendVisitor cb(*this);
92   type_list.ForEach(cb);
93 }
94 
95 SymbolFileType::SymbolFileType(SymbolFile &symbol_file,
96                                const lldb::TypeSP &type_sp)
97     : UserID(type_sp ? type_sp->GetID() : LLDB_INVALID_UID),
98       m_symbol_file(symbol_file), m_type_sp(type_sp) {}
99 
100 Type *SymbolFileType::GetType() {
101   if (!m_type_sp) {
102     Type *resolved_type = m_symbol_file.ResolveTypeUID(GetID());
103     if (resolved_type)
104       m_type_sp = resolved_type->shared_from_this();
105   }
106   return m_type_sp.get();
107 }
108 
109 Type::Type(lldb::user_id_t uid, SymbolFile *symbol_file,
110            const ConstString &name, llvm::Optional<uint64_t> byte_size,
111            SymbolContextScope *context, user_id_t encoding_uid,
112            EncodingDataType encoding_uid_type, const Declaration &decl,
113            const CompilerType &compiler_type,
114            ResolveState compiler_type_resolve_state)
115     : std::enable_shared_from_this<Type>(), UserID(uid), m_name(name),
116       m_symbol_file(symbol_file), m_context(context), m_encoding_type(nullptr),
117       m_encoding_uid(encoding_uid), m_encoding_uid_type(encoding_uid_type),
118       m_decl(decl), m_compiler_type(compiler_type) {
119   if (byte_size) {
120     m_byte_size = *byte_size;
121     m_byte_size_has_value = true;
122   } else {
123     m_byte_size = 0;
124     m_byte_size_has_value = false;
125   }
126   m_flags.compiler_type_resolve_state =
127       (compiler_type ? compiler_type_resolve_state : eResolveStateUnresolved);
128   m_flags.is_complete_objc_class = false;
129 }
130 
131 Type::Type()
132     : std::enable_shared_from_this<Type>(), UserID(0), m_name("<INVALID TYPE>"),
133       m_symbol_file(nullptr), m_context(nullptr), m_encoding_type(nullptr),
134       m_encoding_uid(LLDB_INVALID_UID), m_encoding_uid_type(eEncodingInvalid),
135       m_byte_size(0), m_byte_size_has_value(false), m_decl(),
136       m_compiler_type() {
137   m_flags.compiler_type_resolve_state = eResolveStateUnresolved;
138   m_flags.is_complete_objc_class = false;
139 }
140 
141 Type::Type(const Type &rhs)
142     : std::enable_shared_from_this<Type>(rhs), UserID(rhs), m_name(rhs.m_name),
143       m_symbol_file(rhs.m_symbol_file), m_context(rhs.m_context),
144       m_encoding_type(rhs.m_encoding_type), m_encoding_uid(rhs.m_encoding_uid),
145       m_encoding_uid_type(rhs.m_encoding_uid_type),
146       m_byte_size(rhs.m_byte_size),
147       m_byte_size_has_value(rhs.m_byte_size_has_value), m_decl(rhs.m_decl),
148       m_compiler_type(rhs.m_compiler_type), m_flags(rhs.m_flags) {}
149 
150 const Type &Type::operator=(const Type &rhs) {
151   if (this != &rhs) {
152   }
153   return *this;
154 }
155 
156 void Type::GetDescription(Stream *s, lldb::DescriptionLevel level,
157                           bool show_name) {
158   *s << "id = " << (const UserID &)*this;
159 
160   // Call the name accessor to make sure we resolve the type name
161   if (show_name) {
162     const ConstString &type_name = GetName();
163     if (type_name) {
164       *s << ", name = \"" << type_name << '"';
165       ConstString qualified_type_name(GetQualifiedName());
166       if (qualified_type_name != type_name) {
167         *s << ", qualified = \"" << qualified_type_name << '"';
168       }
169     }
170   }
171 
172   // Call the get byte size accesor so we resolve our byte size
173   if (GetByteSize())
174     s->Printf(", byte-size = %" PRIu64, m_byte_size);
175   bool show_fullpaths = (level == lldb::eDescriptionLevelVerbose);
176   m_decl.Dump(s, show_fullpaths);
177 
178   if (m_compiler_type.IsValid()) {
179     *s << ", compiler_type = \"";
180     GetForwardCompilerType().DumpTypeDescription(s);
181     *s << '"';
182   } else if (m_encoding_uid != LLDB_INVALID_UID) {
183     s->Printf(", type_uid = 0x%8.8" PRIx64, m_encoding_uid);
184     switch (m_encoding_uid_type) {
185     case eEncodingInvalid:
186       break;
187     case eEncodingIsUID:
188       s->PutCString(" (unresolved type)");
189       break;
190     case eEncodingIsConstUID:
191       s->PutCString(" (unresolved const type)");
192       break;
193     case eEncodingIsRestrictUID:
194       s->PutCString(" (unresolved restrict type)");
195       break;
196     case eEncodingIsVolatileUID:
197       s->PutCString(" (unresolved volatile type)");
198       break;
199     case eEncodingIsTypedefUID:
200       s->PutCString(" (unresolved typedef)");
201       break;
202     case eEncodingIsPointerUID:
203       s->PutCString(" (unresolved pointer)");
204       break;
205     case eEncodingIsLValueReferenceUID:
206       s->PutCString(" (unresolved L value reference)");
207       break;
208     case eEncodingIsRValueReferenceUID:
209       s->PutCString(" (unresolved R value reference)");
210       break;
211     case eEncodingIsSyntheticUID:
212       s->PutCString(" (synthetic type)");
213       break;
214     }
215   }
216 }
217 
218 void Type::Dump(Stream *s, bool show_context) {
219   s->Printf("%p: ", static_cast<void *>(this));
220   s->Indent();
221   *s << "Type" << static_cast<const UserID &>(*this) << ' ';
222   if (m_name)
223     *s << ", name = \"" << m_name << "\"";
224 
225   if (m_byte_size_has_value)
226     s->Printf(", size = %" PRIu64, m_byte_size);
227 
228   if (show_context && m_context != nullptr) {
229     s->PutCString(", context = ( ");
230     m_context->DumpSymbolContext(s);
231     s->PutCString(" )");
232   }
233 
234   bool show_fullpaths = false;
235   m_decl.Dump(s, show_fullpaths);
236 
237   if (m_compiler_type.IsValid()) {
238     *s << ", compiler_type = " << m_compiler_type.GetOpaqueQualType() << ' ';
239     GetForwardCompilerType().DumpTypeDescription(s);
240   } else if (m_encoding_uid != LLDB_INVALID_UID) {
241     *s << ", type_data = " << (uint64_t)m_encoding_uid;
242     switch (m_encoding_uid_type) {
243     case eEncodingInvalid:
244       break;
245     case eEncodingIsUID:
246       s->PutCString(" (unresolved type)");
247       break;
248     case eEncodingIsConstUID:
249       s->PutCString(" (unresolved const type)");
250       break;
251     case eEncodingIsRestrictUID:
252       s->PutCString(" (unresolved restrict type)");
253       break;
254     case eEncodingIsVolatileUID:
255       s->PutCString(" (unresolved volatile type)");
256       break;
257     case eEncodingIsTypedefUID:
258       s->PutCString(" (unresolved typedef)");
259       break;
260     case eEncodingIsPointerUID:
261       s->PutCString(" (unresolved pointer)");
262       break;
263     case eEncodingIsLValueReferenceUID:
264       s->PutCString(" (unresolved L value reference)");
265       break;
266     case eEncodingIsRValueReferenceUID:
267       s->PutCString(" (unresolved R value reference)");
268       break;
269     case eEncodingIsSyntheticUID:
270       s->PutCString(" (synthetic type)");
271       break;
272     }
273   }
274 
275   //
276   //  if (m_access)
277   //      s->Printf(", access = %u", m_access);
278   s->EOL();
279 }
280 
281 const ConstString &Type::GetName() {
282   if (!m_name)
283     m_name = GetForwardCompilerType().GetConstTypeName();
284   return m_name;
285 }
286 
287 void Type::DumpTypeName(Stream *s) { GetName().Dump(s, "<invalid-type-name>"); }
288 
289 void Type::DumpValue(ExecutionContext *exe_ctx, Stream *s,
290                      const DataExtractor &data, uint32_t data_byte_offset,
291                      bool show_types, bool show_summary, bool verbose,
292                      lldb::Format format) {
293   if (ResolveClangType(eResolveStateForward)) {
294     if (show_types) {
295       s->PutChar('(');
296       if (verbose)
297         s->Printf("Type{0x%8.8" PRIx64 "} ", GetID());
298       DumpTypeName(s);
299       s->PutCString(") ");
300     }
301 
302     GetForwardCompilerType().DumpValue(
303         exe_ctx, s, format == lldb::eFormatDefault ? GetFormat() : format, data,
304         data_byte_offset, GetByteSize().getValueOr(0),
305         0, // Bitfield bit size
306         0, // Bitfield bit offset
307         show_types, show_summary, verbose, 0);
308   }
309 }
310 
311 Type *Type::GetEncodingType() {
312   if (m_encoding_type == nullptr && m_encoding_uid != LLDB_INVALID_UID)
313     m_encoding_type = m_symbol_file->ResolveTypeUID(m_encoding_uid);
314   return m_encoding_type;
315 }
316 
317 llvm::Optional<uint64_t> Type::GetByteSize() {
318   if (m_byte_size_has_value)
319     return m_byte_size;
320 
321   switch (m_encoding_uid_type) {
322   case eEncodingInvalid:
323   case eEncodingIsSyntheticUID:
324     break;
325   case eEncodingIsUID:
326   case eEncodingIsConstUID:
327   case eEncodingIsRestrictUID:
328   case eEncodingIsVolatileUID:
329   case eEncodingIsTypedefUID: {
330     Type *encoding_type = GetEncodingType();
331     if (encoding_type)
332       if (llvm::Optional<uint64_t> size = encoding_type->GetByteSize()) {
333         m_byte_size = *size;
334         m_byte_size_has_value = true;
335         return m_byte_size;
336       }
337 
338     if (llvm::Optional<uint64_t> size =
339             GetLayoutCompilerType().GetByteSize(nullptr)) {
340       m_byte_size = *size;
341       m_byte_size_has_value = true;
342         return m_byte_size;
343     }
344   } break;
345 
346     // If we are a pointer or reference, then this is just a pointer size;
347     case eEncodingIsPointerUID:
348     case eEncodingIsLValueReferenceUID:
349     case eEncodingIsRValueReferenceUID: {
350       if (ArchSpec arch = m_symbol_file->GetObjectFile()->GetArchitecture()) {
351         m_byte_size = arch.GetAddressByteSize();
352         m_byte_size_has_value = true;
353       }
354     } break;
355   }
356   return {};
357 }
358 
359 uint32_t Type::GetNumChildren(bool omit_empty_base_classes) {
360   return GetForwardCompilerType().GetNumChildren(omit_empty_base_classes, nullptr);
361 }
362 
363 bool Type::IsAggregateType() {
364   return GetForwardCompilerType().IsAggregateType();
365 }
366 
367 lldb::TypeSP Type::GetTypedefType() {
368   lldb::TypeSP type_sp;
369   if (IsTypedef()) {
370     Type *typedef_type = m_symbol_file->ResolveTypeUID(m_encoding_uid);
371     if (typedef_type)
372       type_sp = typedef_type->shared_from_this();
373   }
374   return type_sp;
375 }
376 
377 lldb::Format Type::GetFormat() { return GetForwardCompilerType().GetFormat(); }
378 
379 lldb::Encoding Type::GetEncoding(uint64_t &count) {
380   // Make sure we resolve our type if it already hasn't been.
381   return GetForwardCompilerType().GetEncoding(count);
382 }
383 
384 bool Type::DumpValueInMemory(ExecutionContext *exe_ctx, Stream *s,
385                              lldb::addr_t address, AddressType address_type,
386                              bool show_types, bool show_summary, bool verbose) {
387   if (address != LLDB_INVALID_ADDRESS) {
388     DataExtractor data;
389     Target *target = nullptr;
390     if (exe_ctx)
391       target = exe_ctx->GetTargetPtr();
392     if (target)
393       data.SetByteOrder(target->GetArchitecture().GetByteOrder());
394     if (ReadFromMemory(exe_ctx, address, address_type, data)) {
395       DumpValue(exe_ctx, s, data, 0, show_types, show_summary, verbose);
396       return true;
397     }
398   }
399   return false;
400 }
401 
402 bool Type::ReadFromMemory(ExecutionContext *exe_ctx, lldb::addr_t addr,
403                           AddressType address_type, DataExtractor &data) {
404   if (address_type == eAddressTypeFile) {
405     // Can't convert a file address to anything valid without more context
406     // (which Module it came from)
407     return false;
408   }
409 
410   const uint64_t byte_size = GetByteSize().getValueOr(0);
411   if (data.GetByteSize() < byte_size) {
412     lldb::DataBufferSP data_sp(new DataBufferHeap(byte_size, '\0'));
413     data.SetData(data_sp);
414   }
415 
416   uint8_t *dst = const_cast<uint8_t *>(data.PeekData(0, byte_size));
417   if (dst != nullptr) {
418     if (address_type == eAddressTypeHost) {
419       // The address is an address in this process, so just copy it
420       if (addr == 0)
421         return false;
422       memcpy(dst, reinterpret_cast<uint8_t *>(addr), byte_size);
423       return true;
424     } else {
425       if (exe_ctx) {
426         Process *process = exe_ctx->GetProcessPtr();
427         if (process) {
428           Status error;
429           return exe_ctx->GetProcessPtr()->ReadMemory(addr, dst, byte_size,
430                                                       error) == byte_size;
431         }
432       }
433     }
434   }
435   return false;
436 }
437 
438 bool Type::WriteToMemory(ExecutionContext *exe_ctx, lldb::addr_t addr,
439                          AddressType address_type, DataExtractor &data) {
440   return false;
441 }
442 
443 TypeList *Type::GetTypeList() { return GetSymbolFile()->GetTypeList(); }
444 
445 const Declaration &Type::GetDeclaration() const { return m_decl; }
446 
447 bool Type::ResolveClangType(ResolveState compiler_type_resolve_state) {
448   // TODO: This needs to consider the correct type system to use.
449   Type *encoding_type = nullptr;
450   if (!m_compiler_type.IsValid()) {
451     encoding_type = GetEncodingType();
452     if (encoding_type) {
453       switch (m_encoding_uid_type) {
454       case eEncodingIsUID: {
455         CompilerType encoding_compiler_type =
456             encoding_type->GetForwardCompilerType();
457         if (encoding_compiler_type.IsValid()) {
458           m_compiler_type = encoding_compiler_type;
459           m_flags.compiler_type_resolve_state =
460               encoding_type->m_flags.compiler_type_resolve_state;
461         }
462       } break;
463 
464       case eEncodingIsConstUID:
465         m_compiler_type =
466             encoding_type->GetForwardCompilerType().AddConstModifier();
467         break;
468 
469       case eEncodingIsRestrictUID:
470         m_compiler_type =
471             encoding_type->GetForwardCompilerType().AddRestrictModifier();
472         break;
473 
474       case eEncodingIsVolatileUID:
475         m_compiler_type =
476             encoding_type->GetForwardCompilerType().AddVolatileModifier();
477         break;
478 
479       case eEncodingIsTypedefUID:
480         m_compiler_type = encoding_type->GetForwardCompilerType().CreateTypedef(
481             m_name.AsCString("__lldb_invalid_typedef_name"),
482             GetSymbolFile()->GetDeclContextContainingUID(GetID()));
483         m_name.Clear();
484         break;
485 
486       case eEncodingIsPointerUID:
487         m_compiler_type =
488             encoding_type->GetForwardCompilerType().GetPointerType();
489         break;
490 
491       case eEncodingIsLValueReferenceUID:
492         m_compiler_type =
493             encoding_type->GetForwardCompilerType().GetLValueReferenceType();
494         break;
495 
496       case eEncodingIsRValueReferenceUID:
497         m_compiler_type =
498             encoding_type->GetForwardCompilerType().GetRValueReferenceType();
499         break;
500 
501       default:
502         llvm_unreachable("Unhandled encoding_data_type.");
503       }
504     } else {
505       // We have no encoding type, return void?
506       TypeSystem *type_system =
507           m_symbol_file->GetTypeSystemForLanguage(eLanguageTypeC);
508       CompilerType void_compiler_type =
509           type_system->GetBasicTypeFromAST(eBasicTypeVoid);
510       switch (m_encoding_uid_type) {
511       case eEncodingIsUID:
512         m_compiler_type = void_compiler_type;
513         break;
514 
515       case eEncodingIsConstUID:
516         m_compiler_type = void_compiler_type.AddConstModifier();
517         break;
518 
519       case eEncodingIsRestrictUID:
520         m_compiler_type = void_compiler_type.AddRestrictModifier();
521         break;
522 
523       case eEncodingIsVolatileUID:
524         m_compiler_type = void_compiler_type.AddVolatileModifier();
525         break;
526 
527       case eEncodingIsTypedefUID:
528         m_compiler_type = void_compiler_type.CreateTypedef(
529             m_name.AsCString("__lldb_invalid_typedef_name"),
530             GetSymbolFile()->GetDeclContextContainingUID(GetID()));
531         break;
532 
533       case eEncodingIsPointerUID:
534         m_compiler_type = void_compiler_type.GetPointerType();
535         break;
536 
537       case eEncodingIsLValueReferenceUID:
538         m_compiler_type = void_compiler_type.GetLValueReferenceType();
539         break;
540 
541       case eEncodingIsRValueReferenceUID:
542         m_compiler_type = void_compiler_type.GetRValueReferenceType();
543         break;
544 
545       default:
546         llvm_unreachable("Unhandled encoding_data_type.");
547       }
548     }
549 
550     // When we have a EncodingUID, our "m_flags.compiler_type_resolve_state" is
551     // set to eResolveStateUnresolved so we need to update it to say that we
552     // now have a forward declaration since that is what we created above.
553     if (m_compiler_type.IsValid())
554       m_flags.compiler_type_resolve_state = eResolveStateForward;
555   }
556 
557   // Check if we have a forward reference to a class/struct/union/enum?
558   if (compiler_type_resolve_state == eResolveStateLayout ||
559       compiler_type_resolve_state == eResolveStateFull) {
560     // Check if we have a forward reference to a class/struct/union/enum?
561     if (m_compiler_type.IsValid() &&
562         m_flags.compiler_type_resolve_state < compiler_type_resolve_state) {
563       m_flags.compiler_type_resolve_state = eResolveStateFull;
564       if (!m_compiler_type.IsDefined()) {
565         // We have a forward declaration, we need to resolve it to a complete
566         // definition.
567         m_symbol_file->CompleteType(m_compiler_type);
568       }
569     }
570   }
571 
572   // If we have an encoding type, then we need to make sure it is resolved
573   // appropriately.
574   if (m_encoding_uid != LLDB_INVALID_UID) {
575     if (encoding_type == nullptr)
576       encoding_type = GetEncodingType();
577     if (encoding_type) {
578       ResolveState encoding_compiler_type_resolve_state =
579           compiler_type_resolve_state;
580 
581       if (compiler_type_resolve_state == eResolveStateLayout) {
582         switch (m_encoding_uid_type) {
583         case eEncodingIsPointerUID:
584         case eEncodingIsLValueReferenceUID:
585         case eEncodingIsRValueReferenceUID:
586           encoding_compiler_type_resolve_state = eResolveStateForward;
587           break;
588         default:
589           break;
590         }
591       }
592       encoding_type->ResolveClangType(encoding_compiler_type_resolve_state);
593     }
594   }
595   return m_compiler_type.IsValid();
596 }
597 uint32_t Type::GetEncodingMask() {
598   uint32_t encoding_mask = 1u << m_encoding_uid_type;
599   Type *encoding_type = GetEncodingType();
600   assert(encoding_type != this);
601   if (encoding_type)
602     encoding_mask |= encoding_type->GetEncodingMask();
603   return encoding_mask;
604 }
605 
606 CompilerType Type::GetFullCompilerType() {
607   ResolveClangType(eResolveStateFull);
608   return m_compiler_type;
609 }
610 
611 CompilerType Type::GetLayoutCompilerType() {
612   ResolveClangType(eResolveStateLayout);
613   return m_compiler_type;
614 }
615 
616 CompilerType Type::GetForwardCompilerType() {
617   ResolveClangType(eResolveStateForward);
618   return m_compiler_type;
619 }
620 
621 int Type::Compare(const Type &a, const Type &b) {
622   // Just compare the UID values for now...
623   lldb::user_id_t a_uid = a.GetID();
624   lldb::user_id_t b_uid = b.GetID();
625   if (a_uid < b_uid)
626     return -1;
627   if (a_uid > b_uid)
628     return 1;
629   return 0;
630 }
631 
632 ConstString Type::GetQualifiedName() {
633   return GetForwardCompilerType().GetConstTypeName();
634 }
635 
636 bool Type::GetTypeScopeAndBasename(const llvm::StringRef& name,
637                                    llvm::StringRef &scope,
638                                    llvm::StringRef &basename,
639                                    TypeClass &type_class) {
640   type_class = eTypeClassAny;
641 
642   if (name.empty())
643     return false;
644 
645   basename = name;
646   if (basename.consume_front("struct "))
647     type_class = eTypeClassStruct;
648   else if (basename.consume_front("class "))
649     type_class = eTypeClassClass;
650   else if (basename.consume_front("union "))
651     type_class = eTypeClassUnion;
652   else if (basename.consume_front("enum "))
653     type_class = eTypeClassEnumeration;
654   else if (basename.consume_front("typedef "))
655     type_class = eTypeClassTypedef;
656 
657   size_t namespace_separator = basename.find("::");
658   if (namespace_separator == llvm::StringRef::npos)
659     return false;
660 
661   size_t template_begin = basename.find('<');
662   while (namespace_separator != llvm::StringRef::npos) {
663     if (template_begin != llvm::StringRef::npos &&
664         namespace_separator > template_begin) {
665       size_t template_depth = 1;
666       llvm::StringRef template_arg =
667           basename.drop_front(template_begin + 1);
668       while (template_depth > 0 && !template_arg.empty()) {
669         if (template_arg.front() == '<')
670           template_depth++;
671         else if (template_arg.front() == '>')
672           template_depth--;
673         template_arg = template_arg.drop_front(1);
674       }
675       if (template_depth != 0)
676         return false; // We have an invalid type name. Bail out.
677       if (template_arg.empty())
678         break; // The template ends at the end of the full name.
679       basename = template_arg;
680     } else {
681       basename = basename.drop_front(namespace_separator + 2);
682     }
683     template_begin = basename.find('<');
684     namespace_separator = basename.find("::");
685   }
686   if (basename.size() < name.size()) {
687     scope = name.take_front(name.size() - basename.size());
688     return true;
689   }
690   return false;
691 }
692 
693 ModuleSP Type::GetModule() {
694   if (m_symbol_file)
695     return m_symbol_file->GetObjectFile()->GetModule();
696   return ModuleSP();
697 }
698 
699 TypeAndOrName::TypeAndOrName() : m_type_pair(), m_type_name() {}
700 
701 TypeAndOrName::TypeAndOrName(TypeSP &in_type_sp) : m_type_pair(in_type_sp) {
702   if (in_type_sp)
703     m_type_name = in_type_sp->GetName();
704 }
705 
706 TypeAndOrName::TypeAndOrName(const char *in_type_str)
707     : m_type_name(in_type_str) {}
708 
709 TypeAndOrName::TypeAndOrName(const TypeAndOrName &rhs)
710     : m_type_pair(rhs.m_type_pair), m_type_name(rhs.m_type_name) {}
711 
712 TypeAndOrName::TypeAndOrName(ConstString &in_type_const_string)
713     : m_type_name(in_type_const_string) {}
714 
715 TypeAndOrName &TypeAndOrName::operator=(const TypeAndOrName &rhs) {
716   if (this != &rhs) {
717     m_type_name = rhs.m_type_name;
718     m_type_pair = rhs.m_type_pair;
719   }
720   return *this;
721 }
722 
723 bool TypeAndOrName::operator==(const TypeAndOrName &other) const {
724   if (m_type_pair != other.m_type_pair)
725     return false;
726   if (m_type_name != other.m_type_name)
727     return false;
728   return true;
729 }
730 
731 bool TypeAndOrName::operator!=(const TypeAndOrName &other) const {
732   return !(*this == other);
733 }
734 
735 ConstString TypeAndOrName::GetName() const {
736   if (m_type_name)
737     return m_type_name;
738   if (m_type_pair)
739     return m_type_pair.GetName();
740   return ConstString("<invalid>");
741 }
742 
743 void TypeAndOrName::SetName(const ConstString &type_name) {
744   m_type_name = type_name;
745 }
746 
747 void TypeAndOrName::SetName(const char *type_name_cstr) {
748   m_type_name.SetCString(type_name_cstr);
749 }
750 
751 void TypeAndOrName::SetTypeSP(lldb::TypeSP type_sp) {
752   m_type_pair.SetType(type_sp);
753   if (m_type_pair)
754     m_type_name = m_type_pair.GetName();
755 }
756 
757 void TypeAndOrName::SetCompilerType(CompilerType compiler_type) {
758   m_type_pair.SetType(compiler_type);
759   if (m_type_pair)
760     m_type_name = m_type_pair.GetName();
761 }
762 
763 bool TypeAndOrName::IsEmpty() const {
764   return !((bool)m_type_name || (bool)m_type_pair);
765 }
766 
767 void TypeAndOrName::Clear() {
768   m_type_name.Clear();
769   m_type_pair.Clear();
770 }
771 
772 bool TypeAndOrName::HasName() const { return (bool)m_type_name; }
773 
774 bool TypeAndOrName::HasTypeSP() const {
775   return m_type_pair.GetTypeSP().get() != nullptr;
776 }
777 
778 bool TypeAndOrName::HasCompilerType() const {
779   return m_type_pair.GetCompilerType().IsValid();
780 }
781 
782 TypeImpl::TypeImpl() : m_module_wp(), m_static_type(), m_dynamic_type() {}
783 
784 TypeImpl::TypeImpl(const TypeImpl &rhs)
785     : m_module_wp(rhs.m_module_wp), m_static_type(rhs.m_static_type),
786       m_dynamic_type(rhs.m_dynamic_type) {}
787 
788 TypeImpl::TypeImpl(const lldb::TypeSP &type_sp)
789     : m_module_wp(), m_static_type(), m_dynamic_type() {
790   SetType(type_sp);
791 }
792 
793 TypeImpl::TypeImpl(const CompilerType &compiler_type)
794     : m_module_wp(), m_static_type(), m_dynamic_type() {
795   SetType(compiler_type);
796 }
797 
798 TypeImpl::TypeImpl(const lldb::TypeSP &type_sp, const CompilerType &dynamic)
799     : m_module_wp(), m_static_type(type_sp), m_dynamic_type(dynamic) {
800   SetType(type_sp, dynamic);
801 }
802 
803 TypeImpl::TypeImpl(const CompilerType &static_type,
804                    const CompilerType &dynamic_type)
805     : m_module_wp(), m_static_type(), m_dynamic_type() {
806   SetType(static_type, dynamic_type);
807 }
808 
809 TypeImpl::TypeImpl(const TypePair &pair, const CompilerType &dynamic)
810     : m_module_wp(), m_static_type(), m_dynamic_type() {
811   SetType(pair, dynamic);
812 }
813 
814 void TypeImpl::SetType(const lldb::TypeSP &type_sp) {
815   m_static_type.SetType(type_sp);
816   if (type_sp)
817     m_module_wp = type_sp->GetModule();
818   else
819     m_module_wp = lldb::ModuleWP();
820 }
821 
822 void TypeImpl::SetType(const CompilerType &compiler_type) {
823   m_module_wp = lldb::ModuleWP();
824   m_static_type.SetType(compiler_type);
825 }
826 
827 void TypeImpl::SetType(const lldb::TypeSP &type_sp,
828                        const CompilerType &dynamic) {
829   SetType(type_sp);
830   m_dynamic_type = dynamic;
831 }
832 
833 void TypeImpl::SetType(const CompilerType &compiler_type,
834                        const CompilerType &dynamic) {
835   m_module_wp = lldb::ModuleWP();
836   m_static_type.SetType(compiler_type);
837   m_dynamic_type = dynamic;
838 }
839 
840 void TypeImpl::SetType(const TypePair &pair, const CompilerType &dynamic) {
841   m_module_wp = pair.GetModule();
842   m_static_type = pair;
843   m_dynamic_type = dynamic;
844 }
845 
846 TypeImpl &TypeImpl::operator=(const TypeImpl &rhs) {
847   if (rhs != *this) {
848     m_module_wp = rhs.m_module_wp;
849     m_static_type = rhs.m_static_type;
850     m_dynamic_type = rhs.m_dynamic_type;
851   }
852   return *this;
853 }
854 
855 bool TypeImpl::CheckModule(lldb::ModuleSP &module_sp) const {
856   // Check if we have a module for this type. If we do and the shared pointer
857   // is can be successfully initialized with m_module_wp, return true. Else
858   // return false if we didn't have a module, or if we had a module and it has
859   // been deleted. Any functions doing anything with a TypeSP in this TypeImpl
860   // class should call this function and only do anything with the ivars if
861   // this function returns true. If we have a module, the "module_sp" will be
862   // filled in with a strong reference to the module so that the module will at
863   // least stay around long enough for the type query to succeed.
864   module_sp = m_module_wp.lock();
865   if (!module_sp) {
866     lldb::ModuleWP empty_module_wp;
867     // If either call to "std::weak_ptr::owner_before(...) value returns true,
868     // this indicates that m_module_wp once contained (possibly still does) a
869     // reference to a valid shared pointer. This helps us know if we had a
870     // valid reference to a section which is now invalid because the module it
871     // was in was deleted
872     if (empty_module_wp.owner_before(m_module_wp) ||
873         m_module_wp.owner_before(empty_module_wp)) {
874       // m_module_wp had a valid reference to a module, but all strong
875       // references have been released and the module has been deleted
876       return false;
877     }
878   }
879   // We either successfully locked the module, or didn't have one to begin with
880   return true;
881 }
882 
883 bool TypeImpl::operator==(const TypeImpl &rhs) const {
884   return m_static_type == rhs.m_static_type &&
885          m_dynamic_type == rhs.m_dynamic_type;
886 }
887 
888 bool TypeImpl::operator!=(const TypeImpl &rhs) const {
889   return !(*this == rhs);
890 }
891 
892 bool TypeImpl::IsValid() const {
893   // just a name is not valid
894   ModuleSP module_sp;
895   if (CheckModule(module_sp))
896     return m_static_type.IsValid() || m_dynamic_type.IsValid();
897   return false;
898 }
899 
900 TypeImpl::operator bool() const { return IsValid(); }
901 
902 void TypeImpl::Clear() {
903   m_module_wp = lldb::ModuleWP();
904   m_static_type.Clear();
905   m_dynamic_type.Clear();
906 }
907 
908 ConstString TypeImpl::GetName() const {
909   ModuleSP module_sp;
910   if (CheckModule(module_sp)) {
911     if (m_dynamic_type)
912       return m_dynamic_type.GetTypeName();
913     return m_static_type.GetName();
914   }
915   return ConstString();
916 }
917 
918 ConstString TypeImpl::GetDisplayTypeName() const {
919   ModuleSP module_sp;
920   if (CheckModule(module_sp)) {
921     if (m_dynamic_type)
922       return m_dynamic_type.GetDisplayTypeName();
923     return m_static_type.GetDisplayTypeName();
924   }
925   return ConstString();
926 }
927 
928 TypeImpl TypeImpl::GetPointerType() const {
929   ModuleSP module_sp;
930   if (CheckModule(module_sp)) {
931     if (m_dynamic_type.IsValid()) {
932       return TypeImpl(m_static_type.GetPointerType(),
933                       m_dynamic_type.GetPointerType());
934     }
935     return TypeImpl(m_static_type.GetPointerType());
936   }
937   return TypeImpl();
938 }
939 
940 TypeImpl TypeImpl::GetPointeeType() const {
941   ModuleSP module_sp;
942   if (CheckModule(module_sp)) {
943     if (m_dynamic_type.IsValid()) {
944       return TypeImpl(m_static_type.GetPointeeType(),
945                       m_dynamic_type.GetPointeeType());
946     }
947     return TypeImpl(m_static_type.GetPointeeType());
948   }
949   return TypeImpl();
950 }
951 
952 TypeImpl TypeImpl::GetReferenceType() const {
953   ModuleSP module_sp;
954   if (CheckModule(module_sp)) {
955     if (m_dynamic_type.IsValid()) {
956       return TypeImpl(m_static_type.GetReferenceType(),
957                       m_dynamic_type.GetLValueReferenceType());
958     }
959     return TypeImpl(m_static_type.GetReferenceType());
960   }
961   return TypeImpl();
962 }
963 
964 TypeImpl TypeImpl::GetTypedefedType() const {
965   ModuleSP module_sp;
966   if (CheckModule(module_sp)) {
967     if (m_dynamic_type.IsValid()) {
968       return TypeImpl(m_static_type.GetTypedefedType(),
969                       m_dynamic_type.GetTypedefedType());
970     }
971     return TypeImpl(m_static_type.GetTypedefedType());
972   }
973   return TypeImpl();
974 }
975 
976 TypeImpl TypeImpl::GetDereferencedType() const {
977   ModuleSP module_sp;
978   if (CheckModule(module_sp)) {
979     if (m_dynamic_type.IsValid()) {
980       return TypeImpl(m_static_type.GetDereferencedType(),
981                       m_dynamic_type.GetNonReferenceType());
982     }
983     return TypeImpl(m_static_type.GetDereferencedType());
984   }
985   return TypeImpl();
986 }
987 
988 TypeImpl TypeImpl::GetUnqualifiedType() const {
989   ModuleSP module_sp;
990   if (CheckModule(module_sp)) {
991     if (m_dynamic_type.IsValid()) {
992       return TypeImpl(m_static_type.GetUnqualifiedType(),
993                       m_dynamic_type.GetFullyUnqualifiedType());
994     }
995     return TypeImpl(m_static_type.GetUnqualifiedType());
996   }
997   return TypeImpl();
998 }
999 
1000 TypeImpl TypeImpl::GetCanonicalType() const {
1001   ModuleSP module_sp;
1002   if (CheckModule(module_sp)) {
1003     if (m_dynamic_type.IsValid()) {
1004       return TypeImpl(m_static_type.GetCanonicalType(),
1005                       m_dynamic_type.GetCanonicalType());
1006     }
1007     return TypeImpl(m_static_type.GetCanonicalType());
1008   }
1009   return TypeImpl();
1010 }
1011 
1012 CompilerType TypeImpl::GetCompilerType(bool prefer_dynamic) {
1013   ModuleSP module_sp;
1014   if (CheckModule(module_sp)) {
1015     if (prefer_dynamic) {
1016       if (m_dynamic_type.IsValid())
1017         return m_dynamic_type;
1018     }
1019     return m_static_type.GetCompilerType();
1020   }
1021   return CompilerType();
1022 }
1023 
1024 TypeSystem *TypeImpl::GetTypeSystem(bool prefer_dynamic) {
1025   ModuleSP module_sp;
1026   if (CheckModule(module_sp)) {
1027     if (prefer_dynamic) {
1028       if (m_dynamic_type.IsValid())
1029         return m_dynamic_type.GetTypeSystem();
1030     }
1031     return m_static_type.GetCompilerType().GetTypeSystem();
1032   }
1033   return NULL;
1034 }
1035 
1036 bool TypeImpl::GetDescription(lldb_private::Stream &strm,
1037                               lldb::DescriptionLevel description_level) {
1038   ModuleSP module_sp;
1039   if (CheckModule(module_sp)) {
1040     if (m_dynamic_type.IsValid()) {
1041       strm.Printf("Dynamic:\n");
1042       m_dynamic_type.DumpTypeDescription(&strm);
1043       strm.Printf("\nStatic:\n");
1044     }
1045     m_static_type.GetCompilerType().DumpTypeDescription(&strm);
1046   } else {
1047     strm.PutCString("Invalid TypeImpl module for type has been deleted\n");
1048   }
1049   return true;
1050 }
1051 
1052 bool TypeMemberFunctionImpl::IsValid() {
1053   return m_type.IsValid() && m_kind != lldb::eMemberFunctionKindUnknown;
1054 }
1055 
1056 ConstString TypeMemberFunctionImpl::GetName() const { return m_name; }
1057 
1058 ConstString TypeMemberFunctionImpl::GetMangledName() const {
1059   return m_decl.GetMangledName();
1060 }
1061 
1062 CompilerType TypeMemberFunctionImpl::GetType() const { return m_type; }
1063 
1064 lldb::MemberFunctionKind TypeMemberFunctionImpl::GetKind() const {
1065   return m_kind;
1066 }
1067 
1068 bool TypeMemberFunctionImpl::GetDescription(Stream &stream) {
1069   switch (m_kind) {
1070   case lldb::eMemberFunctionKindUnknown:
1071     return false;
1072   case lldb::eMemberFunctionKindConstructor:
1073     stream.Printf("constructor for %s",
1074                   m_type.GetTypeName().AsCString("<unknown>"));
1075     break;
1076   case lldb::eMemberFunctionKindDestructor:
1077     stream.Printf("destructor for %s",
1078                   m_type.GetTypeName().AsCString("<unknown>"));
1079     break;
1080   case lldb::eMemberFunctionKindInstanceMethod:
1081     stream.Printf("instance method %s of type %s", m_name.AsCString(),
1082                   m_decl.GetDeclContext().GetName().AsCString());
1083     break;
1084   case lldb::eMemberFunctionKindStaticMethod:
1085     stream.Printf("static method %s of type %s", m_name.AsCString(),
1086                   m_decl.GetDeclContext().GetName().AsCString());
1087     break;
1088   }
1089   return true;
1090 }
1091 
1092 CompilerType TypeMemberFunctionImpl::GetReturnType() const {
1093   if (m_type)
1094     return m_type.GetFunctionReturnType();
1095   return m_decl.GetFunctionReturnType();
1096 }
1097 
1098 size_t TypeMemberFunctionImpl::GetNumArguments() const {
1099   if (m_type)
1100     return m_type.GetNumberOfFunctionArguments();
1101   else
1102     return m_decl.GetNumFunctionArguments();
1103 }
1104 
1105 CompilerType TypeMemberFunctionImpl::GetArgumentAtIndex(size_t idx) const {
1106   if (m_type)
1107     return m_type.GetFunctionArgumentAtIndex(idx);
1108   else
1109     return m_decl.GetFunctionArgumentType(idx);
1110 }
1111 
1112 TypeEnumMemberImpl::TypeEnumMemberImpl(const lldb::TypeImplSP &integer_type_sp,
1113                                        const ConstString &name,
1114                                        const llvm::APSInt &value)
1115     : m_integer_type_sp(integer_type_sp), m_name(name), m_value(value),
1116       m_valid((bool)name && (bool)integer_type_sp)
1117 
1118 {}
1119