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 <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/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), m_name("<INVALID TYPE>"),
165       m_symbol_file(nullptr), m_context(nullptr), m_encoding_type(nullptr),
166       m_encoding_uid(LLDB_INVALID_UID), m_encoding_uid_type(eEncodingInvalid),
167       m_compiler_type_resolve_state(ResolveState::Unresolved) {
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 accesor 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 void Type::DumpTypeName(Stream *s) { GetName().Dump(s, "<invalid-type-name>"); }
310 
311 void Type::DumpValue(ExecutionContext *exe_ctx, Stream *s,
312                      const DataExtractor &data, uint32_t data_byte_offset,
313                      bool show_types, bool show_summary, bool verbose,
314                      lldb::Format format) {
315   if (ResolveCompilerType(ResolveState::Forward)) {
316     if (show_types) {
317       s->PutChar('(');
318       if (verbose)
319         s->Printf("Type{0x%8.8" PRIx64 "} ", GetID());
320       DumpTypeName(s);
321       s->PutCString(") ");
322     }
323 
324     GetForwardCompilerType().DumpValue(
325         exe_ctx, s, format == lldb::eFormatDefault ? GetFormat() : format, data,
326         data_byte_offset,
327         GetByteSize(exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr)
328             .getValueOr(0),
329         0, // Bitfield bit size
330         0, // Bitfield bit offset
331         show_types, show_summary, verbose, 0);
332   }
333 }
334 
335 Type *Type::GetEncodingType() {
336   if (m_encoding_type == nullptr && m_encoding_uid != LLDB_INVALID_UID)
337     m_encoding_type = m_symbol_file->ResolveTypeUID(m_encoding_uid);
338   return m_encoding_type;
339 }
340 
341 llvm::Optional<uint64_t> Type::GetByteSize(ExecutionContextScope *exe_scope) {
342   if (m_byte_size_has_value)
343     return m_byte_size;
344 
345   switch (m_encoding_uid_type) {
346   case eEncodingInvalid:
347   case eEncodingIsSyntheticUID:
348     break;
349   case eEncodingIsUID:
350   case eEncodingIsConstUID:
351   case eEncodingIsRestrictUID:
352   case eEncodingIsVolatileUID:
353   case eEncodingIsAtomicUID:
354   case eEncodingIsTypedefUID: {
355     Type *encoding_type = GetEncodingType();
356     if (encoding_type)
357       if (llvm::Optional<uint64_t> size = encoding_type->GetByteSize(exe_scope)) {
358         m_byte_size = *size;
359         m_byte_size_has_value = true;
360         return m_byte_size;
361       }
362 
363     if (llvm::Optional<uint64_t> size =
364             GetLayoutCompilerType().GetByteSize(exe_scope)) {
365       m_byte_size = *size;
366       m_byte_size_has_value = true;
367         return m_byte_size;
368     }
369   } break;
370 
371     // If we are a pointer or reference, then this is just a pointer size;
372     case eEncodingIsPointerUID:
373     case eEncodingIsLValueReferenceUID:
374     case eEncodingIsRValueReferenceUID: {
375       if (ArchSpec arch = m_symbol_file->GetObjectFile()->GetArchitecture()) {
376         m_byte_size = arch.GetAddressByteSize();
377         m_byte_size_has_value = true;
378       }
379     } break;
380   }
381   return {};
382 }
383 
384 uint32_t Type::GetNumChildren(bool omit_empty_base_classes) {
385   return GetForwardCompilerType().GetNumChildren(omit_empty_base_classes, nullptr);
386 }
387 
388 bool Type::IsAggregateType() {
389   return GetForwardCompilerType().IsAggregateType();
390 }
391 
392 lldb::TypeSP Type::GetTypedefType() {
393   lldb::TypeSP type_sp;
394   if (IsTypedef()) {
395     Type *typedef_type = m_symbol_file->ResolveTypeUID(m_encoding_uid);
396     if (typedef_type)
397       type_sp = typedef_type->shared_from_this();
398   }
399   return type_sp;
400 }
401 
402 lldb::Format Type::GetFormat() { return GetForwardCompilerType().GetFormat(); }
403 
404 lldb::Encoding Type::GetEncoding(uint64_t &count) {
405   // Make sure we resolve our type if it already hasn't been.
406   return GetForwardCompilerType().GetEncoding(count);
407 }
408 
409 bool Type::DumpValueInMemory(ExecutionContext *exe_ctx, Stream *s,
410                              lldb::addr_t address, AddressType address_type,
411                              bool show_types, bool show_summary, bool verbose) {
412   if (address != LLDB_INVALID_ADDRESS) {
413     DataExtractor data;
414     Target *target = nullptr;
415     if (exe_ctx)
416       target = exe_ctx->GetTargetPtr();
417     if (target)
418       data.SetByteOrder(target->GetArchitecture().GetByteOrder());
419     if (ReadFromMemory(exe_ctx, address, address_type, data)) {
420       DumpValue(exe_ctx, s, data, 0, show_types, show_summary, verbose);
421       return true;
422     }
423   }
424   return false;
425 }
426 
427 bool Type::ReadFromMemory(ExecutionContext *exe_ctx, lldb::addr_t addr,
428                           AddressType address_type, DataExtractor &data) {
429   if (address_type == eAddressTypeFile) {
430     // Can't convert a file address to anything valid without more context
431     // (which Module it came from)
432     return false;
433   }
434 
435   const uint64_t byte_size =
436       GetByteSize(exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr)
437           .getValueOr(0);
438   if (data.GetByteSize() < byte_size) {
439     lldb::DataBufferSP data_sp(new DataBufferHeap(byte_size, '\0'));
440     data.SetData(data_sp);
441   }
442 
443   uint8_t *dst = const_cast<uint8_t *>(data.PeekData(0, byte_size));
444   if (dst != nullptr) {
445     if (address_type == eAddressTypeHost) {
446       // The address is an address in this process, so just copy it
447       if (addr == 0)
448         return false;
449       memcpy(dst, reinterpret_cast<uint8_t *>(addr), byte_size);
450       return true;
451     } else {
452       if (exe_ctx) {
453         Process *process = exe_ctx->GetProcessPtr();
454         if (process) {
455           Status error;
456           return exe_ctx->GetProcessPtr()->ReadMemory(addr, dst, byte_size,
457                                                       error) == byte_size;
458         }
459       }
460     }
461   }
462   return false;
463 }
464 
465 bool Type::WriteToMemory(ExecutionContext *exe_ctx, lldb::addr_t addr,
466                          AddressType address_type, DataExtractor &data) {
467   return false;
468 }
469 
470 const Declaration &Type::GetDeclaration() const { return m_decl; }
471 
472 bool Type::ResolveCompilerType(ResolveState compiler_type_resolve_state) {
473   // TODO: This needs to consider the correct type system to use.
474   Type *encoding_type = nullptr;
475   if (!m_compiler_type.IsValid()) {
476     encoding_type = GetEncodingType();
477     if (encoding_type) {
478       switch (m_encoding_uid_type) {
479       case eEncodingIsUID: {
480         CompilerType encoding_compiler_type =
481             encoding_type->GetForwardCompilerType();
482         if (encoding_compiler_type.IsValid()) {
483           m_compiler_type = encoding_compiler_type;
484           m_compiler_type_resolve_state =
485               encoding_type->m_compiler_type_resolve_state;
486         }
487       } break;
488 
489       case eEncodingIsConstUID:
490         m_compiler_type =
491             encoding_type->GetForwardCompilerType().AddConstModifier();
492         break;
493 
494       case eEncodingIsRestrictUID:
495         m_compiler_type =
496             encoding_type->GetForwardCompilerType().AddRestrictModifier();
497         break;
498 
499       case eEncodingIsVolatileUID:
500         m_compiler_type =
501             encoding_type->GetForwardCompilerType().AddVolatileModifier();
502         break;
503 
504       case eEncodingIsAtomicUID:
505         m_compiler_type =
506             encoding_type->GetForwardCompilerType().GetAtomicType();
507         break;
508 
509       case eEncodingIsTypedefUID:
510         m_compiler_type = encoding_type->GetForwardCompilerType().CreateTypedef(
511             m_name.AsCString("__lldb_invalid_typedef_name"),
512             GetSymbolFile()->GetDeclContextContainingUID(GetID()), m_payload);
513         m_name.Clear();
514         break;
515 
516       case eEncodingIsPointerUID:
517         m_compiler_type =
518             encoding_type->GetForwardCompilerType().GetPointerType();
519         break;
520 
521       case eEncodingIsLValueReferenceUID:
522         m_compiler_type =
523             encoding_type->GetForwardCompilerType().GetLValueReferenceType();
524         break;
525 
526       case eEncodingIsRValueReferenceUID:
527         m_compiler_type =
528             encoding_type->GetForwardCompilerType().GetRValueReferenceType();
529         break;
530 
531       default:
532         llvm_unreachable("Unhandled encoding_data_type.");
533       }
534     } else {
535       // We have no encoding type, return void?
536       auto type_system_or_err =
537           m_symbol_file->GetTypeSystemForLanguage(eLanguageTypeC);
538       if (auto err = type_system_or_err.takeError()) {
539         LLDB_LOG_ERROR(
540             lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
541             std::move(err),
542             "Unable to construct void type from TypeSystemClang");
543       } else {
544         CompilerType void_compiler_type =
545             type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid);
546         switch (m_encoding_uid_type) {
547         case eEncodingIsUID:
548           m_compiler_type = void_compiler_type;
549           break;
550 
551         case eEncodingIsConstUID:
552           m_compiler_type = void_compiler_type.AddConstModifier();
553           break;
554 
555         case eEncodingIsRestrictUID:
556           m_compiler_type = void_compiler_type.AddRestrictModifier();
557           break;
558 
559         case eEncodingIsVolatileUID:
560           m_compiler_type = void_compiler_type.AddVolatileModifier();
561           break;
562 
563         case eEncodingIsAtomicUID:
564           m_compiler_type = void_compiler_type.GetAtomicType();
565           break;
566 
567         case eEncodingIsTypedefUID:
568           m_compiler_type = void_compiler_type.CreateTypedef(
569               m_name.AsCString("__lldb_invalid_typedef_name"),
570               GetSymbolFile()->GetDeclContextContainingUID(GetID()), m_payload);
571           break;
572 
573         case eEncodingIsPointerUID:
574           m_compiler_type = void_compiler_type.GetPointerType();
575           break;
576 
577         case eEncodingIsLValueReferenceUID:
578           m_compiler_type = void_compiler_type.GetLValueReferenceType();
579           break;
580 
581         case eEncodingIsRValueReferenceUID:
582           m_compiler_type = void_compiler_type.GetRValueReferenceType();
583           break;
584 
585         default:
586           llvm_unreachable("Unhandled encoding_data_type.");
587         }
588       }
589     }
590 
591     // When we have a EncodingUID, our "m_flags.compiler_type_resolve_state" is
592     // set to eResolveStateUnresolved so we need to update it to say that we
593     // now have a forward declaration since that is what we created above.
594     if (m_compiler_type.IsValid())
595       m_compiler_type_resolve_state = ResolveState::Forward;
596   }
597 
598   // Check if we have a forward reference to a class/struct/union/enum?
599   if (compiler_type_resolve_state == ResolveState::Layout ||
600       compiler_type_resolve_state == ResolveState::Full) {
601     // Check if we have a forward reference to a class/struct/union/enum?
602     if (m_compiler_type.IsValid() &&
603         m_compiler_type_resolve_state < compiler_type_resolve_state) {
604       m_compiler_type_resolve_state = ResolveState::Full;
605       if (!m_compiler_type.IsDefined()) {
606         // We have a forward declaration, we need to resolve it to a complete
607         // definition.
608         m_symbol_file->CompleteType(m_compiler_type);
609       }
610     }
611   }
612 
613   // If we have an encoding type, then we need to make sure it is resolved
614   // appropriately.
615   if (m_encoding_uid != LLDB_INVALID_UID) {
616     if (encoding_type == nullptr)
617       encoding_type = GetEncodingType();
618     if (encoding_type) {
619       ResolveState encoding_compiler_type_resolve_state =
620           compiler_type_resolve_state;
621 
622       if (compiler_type_resolve_state == ResolveState::Layout) {
623         switch (m_encoding_uid_type) {
624         case eEncodingIsPointerUID:
625         case eEncodingIsLValueReferenceUID:
626         case eEncodingIsRValueReferenceUID:
627           encoding_compiler_type_resolve_state = ResolveState::Forward;
628           break;
629         default:
630           break;
631         }
632       }
633       encoding_type->ResolveCompilerType(encoding_compiler_type_resolve_state);
634     }
635   }
636   return m_compiler_type.IsValid();
637 }
638 uint32_t Type::GetEncodingMask() {
639   uint32_t encoding_mask = 1u << m_encoding_uid_type;
640   Type *encoding_type = GetEncodingType();
641   assert(encoding_type != this);
642   if (encoding_type)
643     encoding_mask |= encoding_type->GetEncodingMask();
644   return encoding_mask;
645 }
646 
647 CompilerType Type::GetFullCompilerType() {
648   ResolveCompilerType(ResolveState::Full);
649   return m_compiler_type;
650 }
651 
652 CompilerType Type::GetLayoutCompilerType() {
653   ResolveCompilerType(ResolveState::Layout);
654   return m_compiler_type;
655 }
656 
657 CompilerType Type::GetForwardCompilerType() {
658   ResolveCompilerType(ResolveState::Forward);
659   return m_compiler_type;
660 }
661 
662 ConstString Type::GetQualifiedName() {
663   return GetForwardCompilerType().GetTypeName();
664 }
665 
666 bool Type::GetTypeScopeAndBasename(const llvm::StringRef& name,
667                                    llvm::StringRef &scope,
668                                    llvm::StringRef &basename,
669                                    TypeClass &type_class) {
670   type_class = eTypeClassAny;
671 
672   if (name.empty())
673     return false;
674 
675   basename = name;
676   if (basename.consume_front("struct "))
677     type_class = eTypeClassStruct;
678   else if (basename.consume_front("class "))
679     type_class = eTypeClassClass;
680   else if (basename.consume_front("union "))
681     type_class = eTypeClassUnion;
682   else if (basename.consume_front("enum "))
683     type_class = eTypeClassEnumeration;
684   else if (basename.consume_front("typedef "))
685     type_class = eTypeClassTypedef;
686 
687   size_t namespace_separator = basename.find("::");
688   if (namespace_separator == llvm::StringRef::npos)
689     return false;
690 
691   size_t template_begin = basename.find('<');
692   while (namespace_separator != llvm::StringRef::npos) {
693     if (template_begin != llvm::StringRef::npos &&
694         namespace_separator > template_begin) {
695       size_t template_depth = 1;
696       llvm::StringRef template_arg =
697           basename.drop_front(template_begin + 1);
698       while (template_depth > 0 && !template_arg.empty()) {
699         if (template_arg.front() == '<')
700           template_depth++;
701         else if (template_arg.front() == '>')
702           template_depth--;
703         template_arg = template_arg.drop_front(1);
704       }
705       if (template_depth != 0)
706         return false; // We have an invalid type name. Bail out.
707       if (template_arg.empty())
708         break; // The template ends at the end of the full name.
709       basename = template_arg;
710     } else {
711       basename = basename.drop_front(namespace_separator + 2);
712     }
713     template_begin = basename.find('<');
714     namespace_separator = basename.find("::");
715   }
716   if (basename.size() < name.size()) {
717     scope = name.take_front(name.size() - basename.size());
718     return true;
719   }
720   return false;
721 }
722 
723 ModuleSP Type::GetModule() {
724   if (m_symbol_file)
725     return m_symbol_file->GetObjectFile()->GetModule();
726   return ModuleSP();
727 }
728 
729 TypeAndOrName::TypeAndOrName(TypeSP &in_type_sp) {
730   if (in_type_sp) {
731     m_compiler_type = in_type_sp->GetForwardCompilerType();
732     m_type_name = in_type_sp->GetName();
733   }
734 }
735 
736 TypeAndOrName::TypeAndOrName(const char *in_type_str)
737     : m_type_name(in_type_str) {}
738 
739 TypeAndOrName::TypeAndOrName(ConstString &in_type_const_string)
740     : m_type_name(in_type_const_string) {}
741 
742 bool TypeAndOrName::operator==(const TypeAndOrName &other) const {
743   if (m_compiler_type != other.m_compiler_type)
744     return false;
745   if (m_type_name != other.m_type_name)
746     return false;
747   return true;
748 }
749 
750 bool TypeAndOrName::operator!=(const TypeAndOrName &other) const {
751   return !(*this == other);
752 }
753 
754 ConstString TypeAndOrName::GetName() const {
755   if (m_type_name)
756     return m_type_name;
757   if (m_compiler_type)
758     return m_compiler_type.GetTypeName();
759   return ConstString("<invalid>");
760 }
761 
762 void TypeAndOrName::SetName(ConstString type_name) {
763   m_type_name = type_name;
764 }
765 
766 void TypeAndOrName::SetName(const char *type_name_cstr) {
767   m_type_name.SetCString(type_name_cstr);
768 }
769 
770 void TypeAndOrName::SetTypeSP(lldb::TypeSP type_sp) {
771   if (type_sp) {
772     m_compiler_type = type_sp->GetForwardCompilerType();
773     m_type_name = type_sp->GetName();
774   } else
775     Clear();
776 }
777 
778 void TypeAndOrName::SetCompilerType(CompilerType compiler_type) {
779   m_compiler_type = compiler_type;
780   if (m_compiler_type)
781     m_type_name = m_compiler_type.GetTypeName();
782 }
783 
784 bool TypeAndOrName::IsEmpty() const {
785   return !((bool)m_type_name || (bool)m_compiler_type);
786 }
787 
788 void TypeAndOrName::Clear() {
789   m_type_name.Clear();
790   m_compiler_type.Clear();
791 }
792 
793 bool TypeAndOrName::HasName() const { return (bool)m_type_name; }
794 
795 bool TypeAndOrName::HasCompilerType() const {
796   return m_compiler_type.IsValid();
797 }
798 
799 TypeImpl::TypeImpl(const lldb::TypeSP &type_sp)
800     : m_module_wp(), m_static_type(), m_dynamic_type() {
801   SetType(type_sp);
802 }
803 
804 TypeImpl::TypeImpl(const CompilerType &compiler_type)
805     : m_module_wp(), m_static_type(), m_dynamic_type() {
806   SetType(compiler_type);
807 }
808 
809 TypeImpl::TypeImpl(const lldb::TypeSP &type_sp, const CompilerType &dynamic)
810     : m_module_wp(), m_static_type(), m_dynamic_type(dynamic) {
811   SetType(type_sp, dynamic);
812 }
813 
814 TypeImpl::TypeImpl(const CompilerType &static_type,
815                    const CompilerType &dynamic_type)
816     : m_module_wp(), m_static_type(), m_dynamic_type() {
817   SetType(static_type, dynamic_type);
818 }
819 
820 void TypeImpl::SetType(const lldb::TypeSP &type_sp) {
821   if (type_sp) {
822     m_static_type = type_sp->GetForwardCompilerType();
823     m_module_wp = type_sp->GetModule();
824   } else {
825     m_static_type.Clear();
826     m_module_wp = lldb::ModuleWP();
827   }
828 }
829 
830 void TypeImpl::SetType(const CompilerType &compiler_type) {
831   m_module_wp = lldb::ModuleWP();
832   m_static_type = compiler_type;
833 }
834 
835 void TypeImpl::SetType(const lldb::TypeSP &type_sp,
836                        const CompilerType &dynamic) {
837   SetType(type_sp);
838   m_dynamic_type = dynamic;
839 }
840 
841 void TypeImpl::SetType(const CompilerType &compiler_type,
842                        const CompilerType &dynamic) {
843   m_module_wp = lldb::ModuleWP();
844   m_static_type = compiler_type;
845   m_dynamic_type = dynamic;
846 }
847 
848 bool TypeImpl::CheckModule(lldb::ModuleSP &module_sp) const {
849   // Check if we have a module for this type. If we do and the shared pointer
850   // is can be successfully initialized with m_module_wp, return true. Else
851   // return false if we didn't have a module, or if we had a module and it has
852   // been deleted. Any functions doing anything with a TypeSP in this TypeImpl
853   // class should call this function and only do anything with the ivars if
854   // this function returns true. If we have a module, the "module_sp" will be
855   // filled in with a strong reference to the module so that the module will at
856   // least stay around long enough for the type query to succeed.
857   module_sp = m_module_wp.lock();
858   if (!module_sp) {
859     lldb::ModuleWP empty_module_wp;
860     // If either call to "std::weak_ptr::owner_before(...) value returns true,
861     // this indicates that m_module_wp once contained (possibly still does) a
862     // reference to a valid shared pointer. This helps us know if we had a
863     // valid reference to a section which is now invalid because the module it
864     // was in was deleted
865     if (empty_module_wp.owner_before(m_module_wp) ||
866         m_module_wp.owner_before(empty_module_wp)) {
867       // m_module_wp had a valid reference to a module, but all strong
868       // references have been released and the module has been deleted
869       return false;
870     }
871   }
872   // We either successfully locked the module, or didn't have one to begin with
873   return true;
874 }
875 
876 bool TypeImpl::operator==(const TypeImpl &rhs) const {
877   return m_static_type == rhs.m_static_type &&
878          m_dynamic_type == rhs.m_dynamic_type;
879 }
880 
881 bool TypeImpl::operator!=(const TypeImpl &rhs) const {
882   return !(*this == rhs);
883 }
884 
885 bool TypeImpl::IsValid() const {
886   // just a name is not valid
887   ModuleSP module_sp;
888   if (CheckModule(module_sp))
889     return m_static_type.IsValid() || m_dynamic_type.IsValid();
890   return false;
891 }
892 
893 TypeImpl::operator bool() const { return IsValid(); }
894 
895 void TypeImpl::Clear() {
896   m_module_wp = lldb::ModuleWP();
897   m_static_type.Clear();
898   m_dynamic_type.Clear();
899 }
900 
901 ConstString TypeImpl::GetName() const {
902   ModuleSP module_sp;
903   if (CheckModule(module_sp)) {
904     if (m_dynamic_type)
905       return m_dynamic_type.GetTypeName();
906     return m_static_type.GetTypeName();
907   }
908   return ConstString();
909 }
910 
911 ConstString TypeImpl::GetDisplayTypeName() const {
912   ModuleSP module_sp;
913   if (CheckModule(module_sp)) {
914     if (m_dynamic_type)
915       return m_dynamic_type.GetDisplayTypeName();
916     return m_static_type.GetDisplayTypeName();
917   }
918   return ConstString();
919 }
920 
921 TypeImpl TypeImpl::GetPointerType() const {
922   ModuleSP module_sp;
923   if (CheckModule(module_sp)) {
924     if (m_dynamic_type.IsValid()) {
925       return TypeImpl(m_static_type.GetPointerType(),
926                       m_dynamic_type.GetPointerType());
927     }
928     return TypeImpl(m_static_type.GetPointerType());
929   }
930   return TypeImpl();
931 }
932 
933 TypeImpl TypeImpl::GetPointeeType() const {
934   ModuleSP module_sp;
935   if (CheckModule(module_sp)) {
936     if (m_dynamic_type.IsValid()) {
937       return TypeImpl(m_static_type.GetPointeeType(),
938                       m_dynamic_type.GetPointeeType());
939     }
940     return TypeImpl(m_static_type.GetPointeeType());
941   }
942   return TypeImpl();
943 }
944 
945 TypeImpl TypeImpl::GetReferenceType() const {
946   ModuleSP module_sp;
947   if (CheckModule(module_sp)) {
948     if (m_dynamic_type.IsValid()) {
949       return TypeImpl(m_static_type.GetLValueReferenceType(),
950                       m_dynamic_type.GetLValueReferenceType());
951     }
952     return TypeImpl(m_static_type.GetLValueReferenceType());
953   }
954   return TypeImpl();
955 }
956 
957 TypeImpl TypeImpl::GetTypedefedType() const {
958   ModuleSP module_sp;
959   if (CheckModule(module_sp)) {
960     if (m_dynamic_type.IsValid()) {
961       return TypeImpl(m_static_type.GetTypedefedType(),
962                       m_dynamic_type.GetTypedefedType());
963     }
964     return TypeImpl(m_static_type.GetTypedefedType());
965   }
966   return TypeImpl();
967 }
968 
969 TypeImpl TypeImpl::GetDereferencedType() const {
970   ModuleSP module_sp;
971   if (CheckModule(module_sp)) {
972     if (m_dynamic_type.IsValid()) {
973       return TypeImpl(m_static_type.GetNonReferenceType(),
974                       m_dynamic_type.GetNonReferenceType());
975     }
976     return TypeImpl(m_static_type.GetNonReferenceType());
977   }
978   return TypeImpl();
979 }
980 
981 TypeImpl TypeImpl::GetUnqualifiedType() const {
982   ModuleSP module_sp;
983   if (CheckModule(module_sp)) {
984     if (m_dynamic_type.IsValid()) {
985       return TypeImpl(m_static_type.GetFullyUnqualifiedType(),
986                       m_dynamic_type.GetFullyUnqualifiedType());
987     }
988     return TypeImpl(m_static_type.GetFullyUnqualifiedType());
989   }
990   return TypeImpl();
991 }
992 
993 TypeImpl TypeImpl::GetCanonicalType() const {
994   ModuleSP module_sp;
995   if (CheckModule(module_sp)) {
996     if (m_dynamic_type.IsValid()) {
997       return TypeImpl(m_static_type.GetCanonicalType(),
998                       m_dynamic_type.GetCanonicalType());
999     }
1000     return TypeImpl(m_static_type.GetCanonicalType());
1001   }
1002   return TypeImpl();
1003 }
1004 
1005 CompilerType TypeImpl::GetCompilerType(bool prefer_dynamic) {
1006   ModuleSP module_sp;
1007   if (CheckModule(module_sp)) {
1008     if (prefer_dynamic) {
1009       if (m_dynamic_type.IsValid())
1010         return m_dynamic_type;
1011     }
1012     return m_static_type;
1013   }
1014   return CompilerType();
1015 }
1016 
1017 TypeSystem *TypeImpl::GetTypeSystem(bool prefer_dynamic) {
1018   ModuleSP module_sp;
1019   if (CheckModule(module_sp)) {
1020     if (prefer_dynamic) {
1021       if (m_dynamic_type.IsValid())
1022         return m_dynamic_type.GetTypeSystem();
1023     }
1024     return m_static_type.GetTypeSystem();
1025   }
1026   return nullptr;
1027 }
1028 
1029 bool TypeImpl::GetDescription(lldb_private::Stream &strm,
1030                               lldb::DescriptionLevel description_level) {
1031   ModuleSP module_sp;
1032   if (CheckModule(module_sp)) {
1033     if (m_dynamic_type.IsValid()) {
1034       strm.Printf("Dynamic:\n");
1035       m_dynamic_type.DumpTypeDescription(&strm);
1036       strm.Printf("\nStatic:\n");
1037     }
1038     m_static_type.DumpTypeDescription(&strm);
1039   } else {
1040     strm.PutCString("Invalid TypeImpl module for type has been deleted\n");
1041   }
1042   return true;
1043 }
1044 
1045 bool TypeMemberFunctionImpl::IsValid() {
1046   return m_type.IsValid() && m_kind != lldb::eMemberFunctionKindUnknown;
1047 }
1048 
1049 ConstString TypeMemberFunctionImpl::GetName() const { return m_name; }
1050 
1051 ConstString TypeMemberFunctionImpl::GetMangledName() const {
1052   return m_decl.GetMangledName();
1053 }
1054 
1055 CompilerType TypeMemberFunctionImpl::GetType() const { return m_type; }
1056 
1057 lldb::MemberFunctionKind TypeMemberFunctionImpl::GetKind() const {
1058   return m_kind;
1059 }
1060 
1061 bool TypeMemberFunctionImpl::GetDescription(Stream &stream) {
1062   switch (m_kind) {
1063   case lldb::eMemberFunctionKindUnknown:
1064     return false;
1065   case lldb::eMemberFunctionKindConstructor:
1066     stream.Printf("constructor for %s",
1067                   m_type.GetTypeName().AsCString("<unknown>"));
1068     break;
1069   case lldb::eMemberFunctionKindDestructor:
1070     stream.Printf("destructor for %s",
1071                   m_type.GetTypeName().AsCString("<unknown>"));
1072     break;
1073   case lldb::eMemberFunctionKindInstanceMethod:
1074     stream.Printf("instance method %s of type %s", m_name.AsCString(),
1075                   m_decl.GetDeclContext().GetName().AsCString());
1076     break;
1077   case lldb::eMemberFunctionKindStaticMethod:
1078     stream.Printf("static method %s of type %s", m_name.AsCString(),
1079                   m_decl.GetDeclContext().GetName().AsCString());
1080     break;
1081   }
1082   return true;
1083 }
1084 
1085 CompilerType TypeMemberFunctionImpl::GetReturnType() const {
1086   if (m_type)
1087     return m_type.GetFunctionReturnType();
1088   return m_decl.GetFunctionReturnType();
1089 }
1090 
1091 size_t TypeMemberFunctionImpl::GetNumArguments() const {
1092   if (m_type)
1093     return m_type.GetNumberOfFunctionArguments();
1094   else
1095     return m_decl.GetNumFunctionArguments();
1096 }
1097 
1098 CompilerType TypeMemberFunctionImpl::GetArgumentAtIndex(size_t idx) const {
1099   if (m_type)
1100     return m_type.GetFunctionArgumentAtIndex(idx);
1101   else
1102     return m_decl.GetFunctionArgumentType(idx);
1103 }
1104 
1105 TypeEnumMemberImpl::TypeEnumMemberImpl(const lldb::TypeImplSP &integer_type_sp,
1106                                        ConstString name,
1107                                        const llvm::APSInt &value)
1108     : m_integer_type_sp(integer_type_sp), m_name(name), m_value(value),
1109       m_valid((bool)name && (bool)integer_type_sp)
1110 
1111 {}
1112