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