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