1 //===-- TypeSystemClang.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 "TypeSystemClang.h"
10
11 #include "llvm/Support/FormatAdapters.h"
12 #include "llvm/Support/FormatVariadic.h"
13
14 #include <mutex>
15 #include <string>
16 #include <vector>
17
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTImporter.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/CXXInheritance.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Mangle.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/AST/Type.h"
27 #include "clang/AST/VTableBuilder.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/Diagnostic.h"
30 #include "clang/Basic/FileManager.h"
31 #include "clang/Basic/FileSystemOptions.h"
32 #include "clang/Basic/LangStandard.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "clang/Basic/TargetOptions.h"
36 #include "clang/Frontend/FrontendOptions.h"
37 #include "clang/Lex/HeaderSearch.h"
38 #include "clang/Lex/HeaderSearchOptions.h"
39 #include "clang/Lex/ModuleMap.h"
40 #include "clang/Sema/Sema.h"
41
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/Threading.h"
44
45 #include "Plugins/ExpressionParser/Clang/ClangASTImporter.h"
46 #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
47 #include "Plugins/ExpressionParser/Clang/ClangExternalASTSourceCallbacks.h"
48 #include "Plugins/ExpressionParser/Clang/ClangFunctionCaller.h"
49 #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
50 #include "Plugins/ExpressionParser/Clang/ClangUserExpression.h"
51 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
52 #include "Plugins/ExpressionParser/Clang/ClangUtilityFunction.h"
53 #include "lldb/Utility/ArchSpec.h"
54 #include "lldb/Utility/Flags.h"
55
56 #include "lldb/Core/DumpDataExtractor.h"
57 #include "lldb/Core/Module.h"
58 #include "lldb/Core/PluginManager.h"
59 #include "lldb/Core/StreamFile.h"
60 #include "lldb/Core/ThreadSafeDenseMap.h"
61 #include "lldb/Core/UniqueCStringMap.h"
62 #include "lldb/Symbol/ObjectFile.h"
63 #include "lldb/Symbol/SymbolFile.h"
64 #include "lldb/Target/ExecutionContext.h"
65 #include "lldb/Target/Language.h"
66 #include "lldb/Target/Process.h"
67 #include "lldb/Target/Target.h"
68 #include "lldb/Utility/DataExtractor.h"
69 #include "lldb/Utility/LLDBAssert.h"
70 #include "lldb/Utility/Log.h"
71 #include "lldb/Utility/RegularExpression.h"
72 #include "lldb/Utility/Scalar.h"
73
74 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
75 #include "Plugins/SymbolFile/DWARF/DWARFASTParserClang.h"
76 #include "Plugins/SymbolFile/PDB/PDBASTParser.h"
77
78 #include <stdio.h>
79
80 #include <mutex>
81
82 using namespace lldb;
83 using namespace lldb_private;
84 using namespace clang;
85 using llvm::StringSwitch;
86
87 LLDB_PLUGIN_DEFINE(TypeSystemClang)
88
89 namespace {
VerifyDecl(clang::Decl * decl)90 static void VerifyDecl(clang::Decl *decl) {
91 assert(decl && "VerifyDecl called with nullptr?");
92 #ifndef NDEBUG
93 // We don't care about the actual access value here but only want to trigger
94 // that Clang calls its internal Decl::AccessDeclContextSanity check.
95 decl->getAccess();
96 #endif
97 }
98
99 static inline bool
TypeSystemClangSupportsLanguage(lldb::LanguageType language)100 TypeSystemClangSupportsLanguage(lldb::LanguageType language) {
101 return language == eLanguageTypeUnknown || // Clang is the default type system
102 lldb_private::Language::LanguageIsC(language) ||
103 lldb_private::Language::LanguageIsCPlusPlus(language) ||
104 lldb_private::Language::LanguageIsObjC(language) ||
105 lldb_private::Language::LanguageIsPascal(language) ||
106 // Use Clang for Rust until there is a proper language plugin for it
107 language == eLanguageTypeRust ||
108 language == eLanguageTypeExtRenderScript ||
109 // Use Clang for D until there is a proper language plugin for it
110 language == eLanguageTypeD ||
111 // Open Dylan compiler debug info is designed to be Clang-compatible
112 language == eLanguageTypeDylan;
113 }
114
115 // Checks whether m1 is an overload of m2 (as opposed to an override). This is
116 // called by addOverridesForMethod to distinguish overrides (which share a
117 // vtable entry) from overloads (which require distinct entries).
isOverload(clang::CXXMethodDecl * m1,clang::CXXMethodDecl * m2)118 bool isOverload(clang::CXXMethodDecl *m1, clang::CXXMethodDecl *m2) {
119 // FIXME: This should detect covariant return types, but currently doesn't.
120 lldbassert(&m1->getASTContext() == &m2->getASTContext() &&
121 "Methods should have the same AST context");
122 clang::ASTContext &context = m1->getASTContext();
123
124 const auto *m1Type = llvm::cast<clang::FunctionProtoType>(
125 context.getCanonicalType(m1->getType()));
126
127 const auto *m2Type = llvm::cast<clang::FunctionProtoType>(
128 context.getCanonicalType(m2->getType()));
129
130 auto compareArgTypes = [&context](const clang::QualType &m1p,
131 const clang::QualType &m2p) {
132 return context.hasSameType(m1p.getUnqualifiedType(),
133 m2p.getUnqualifiedType());
134 };
135
136 // FIXME: In C++14 and later, we can just pass m2Type->param_type_end()
137 // as a fourth parameter to std::equal().
138 return (m1->getNumParams() != m2->getNumParams()) ||
139 !std::equal(m1Type->param_type_begin(), m1Type->param_type_end(),
140 m2Type->param_type_begin(), compareArgTypes);
141 }
142
143 // If decl is a virtual method, walk the base classes looking for methods that
144 // decl overrides. This table of overridden methods is used by IRGen to
145 // determine the vtable layout for decl's parent class.
addOverridesForMethod(clang::CXXMethodDecl * decl)146 void addOverridesForMethod(clang::CXXMethodDecl *decl) {
147 if (!decl->isVirtual())
148 return;
149
150 clang::CXXBasePaths paths;
151 llvm::SmallVector<clang::NamedDecl *, 4> decls;
152
153 auto find_overridden_methods =
154 [&decls, decl](const clang::CXXBaseSpecifier *specifier,
155 clang::CXXBasePath &path) {
156 if (auto *base_record = llvm::dyn_cast<clang::CXXRecordDecl>(
157 specifier->getType()->getAs<clang::RecordType>()->getDecl())) {
158
159 clang::DeclarationName name = decl->getDeclName();
160
161 // If this is a destructor, check whether the base class destructor is
162 // virtual.
163 if (name.getNameKind() == clang::DeclarationName::CXXDestructorName)
164 if (auto *baseDtorDecl = base_record->getDestructor()) {
165 if (baseDtorDecl->isVirtual()) {
166 path.Decls = baseDtorDecl;
167 decls.push_back(baseDtorDecl);
168 return true;
169 } else
170 return false;
171 }
172
173 // Otherwise, search for name in the base class.
174 for (path.Decls = base_record->lookup(name); !path.Decls.empty();
175 path.Decls = path.Decls.slice(1)) {
176 if (auto *method_decl =
177 llvm::dyn_cast<clang::CXXMethodDecl>(path.Decls.front()))
178 if (method_decl->isVirtual() && !isOverload(decl, method_decl)) {
179 path.Decls = method_decl;
180 decls.push_back(method_decl);
181 return true;
182 }
183 }
184 }
185
186 return false;
187 };
188
189 if (decl->getParent()->lookupInBases(find_overridden_methods, paths)) {
190 for (auto *overridden_decl : decls)
191 decl->addOverriddenMethod(
192 llvm::cast<clang::CXXMethodDecl>(overridden_decl));
193 }
194 }
195 }
196
GetVTableAddress(Process & process,VTableContextBase & vtable_ctx,ValueObject & valobj,const ASTRecordLayout & record_layout)197 static lldb::addr_t GetVTableAddress(Process &process,
198 VTableContextBase &vtable_ctx,
199 ValueObject &valobj,
200 const ASTRecordLayout &record_layout) {
201 // Retrieve type info
202 CompilerType pointee_type;
203 CompilerType this_type(valobj.GetCompilerType());
204 uint32_t type_info = this_type.GetTypeInfo(&pointee_type);
205 if (!type_info)
206 return LLDB_INVALID_ADDRESS;
207
208 // Check if it's a pointer or reference
209 bool ptr_or_ref = false;
210 if (type_info & (eTypeIsPointer | eTypeIsReference)) {
211 ptr_or_ref = true;
212 type_info = pointee_type.GetTypeInfo();
213 }
214
215 // We process only C++ classes
216 const uint32_t cpp_class = eTypeIsClass | eTypeIsCPlusPlus;
217 if ((type_info & cpp_class) != cpp_class)
218 return LLDB_INVALID_ADDRESS;
219
220 // Calculate offset to VTable pointer
221 lldb::offset_t vbtable_ptr_offset =
222 vtable_ctx.isMicrosoft() ? record_layout.getVBPtrOffset().getQuantity()
223 : 0;
224
225 if (ptr_or_ref) {
226 // We have a pointer / ref to object, so read
227 // VTable pointer from process memory
228
229 if (valobj.GetAddressTypeOfChildren() != eAddressTypeLoad)
230 return LLDB_INVALID_ADDRESS;
231
232 auto vbtable_ptr_addr = valobj.GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
233 if (vbtable_ptr_addr == LLDB_INVALID_ADDRESS)
234 return LLDB_INVALID_ADDRESS;
235
236 vbtable_ptr_addr += vbtable_ptr_offset;
237
238 Status err;
239 return process.ReadPointerFromMemory(vbtable_ptr_addr, err);
240 }
241
242 // We have an object already read from process memory,
243 // so just extract VTable pointer from it
244
245 DataExtractor data;
246 Status err;
247 auto size = valobj.GetData(data, err);
248 if (err.Fail() || vbtable_ptr_offset + data.GetAddressByteSize() > size)
249 return LLDB_INVALID_ADDRESS;
250
251 return data.GetAddress(&vbtable_ptr_offset);
252 }
253
ReadVBaseOffsetFromVTable(Process & process,VTableContextBase & vtable_ctx,lldb::addr_t vtable_ptr,const CXXRecordDecl * cxx_record_decl,const CXXRecordDecl * base_class_decl)254 static int64_t ReadVBaseOffsetFromVTable(Process &process,
255 VTableContextBase &vtable_ctx,
256 lldb::addr_t vtable_ptr,
257 const CXXRecordDecl *cxx_record_decl,
258 const CXXRecordDecl *base_class_decl) {
259 if (vtable_ctx.isMicrosoft()) {
260 clang::MicrosoftVTableContext &msoft_vtable_ctx =
261 static_cast<clang::MicrosoftVTableContext &>(vtable_ctx);
262
263 // Get the index into the virtual base table. The
264 // index is the index in uint32_t from vbtable_ptr
265 const unsigned vbtable_index =
266 msoft_vtable_ctx.getVBTableIndex(cxx_record_decl, base_class_decl);
267 const lldb::addr_t base_offset_addr = vtable_ptr + vbtable_index * 4;
268 Status err;
269 return process.ReadSignedIntegerFromMemory(base_offset_addr, 4, INT64_MAX,
270 err);
271 }
272
273 clang::ItaniumVTableContext &itanium_vtable_ctx =
274 static_cast<clang::ItaniumVTableContext &>(vtable_ctx);
275
276 clang::CharUnits base_offset_offset =
277 itanium_vtable_ctx.getVirtualBaseOffsetOffset(cxx_record_decl,
278 base_class_decl);
279 const lldb::addr_t base_offset_addr =
280 vtable_ptr + base_offset_offset.getQuantity();
281 const uint32_t base_offset_size = process.GetAddressByteSize();
282 Status err;
283 return process.ReadSignedIntegerFromMemory(base_offset_addr, base_offset_size,
284 INT64_MAX, err);
285 }
286
GetVBaseBitOffset(VTableContextBase & vtable_ctx,ValueObject & valobj,const ASTRecordLayout & record_layout,const CXXRecordDecl * cxx_record_decl,const CXXRecordDecl * base_class_decl,int32_t & bit_offset)287 static bool GetVBaseBitOffset(VTableContextBase &vtable_ctx,
288 ValueObject &valobj,
289 const ASTRecordLayout &record_layout,
290 const CXXRecordDecl *cxx_record_decl,
291 const CXXRecordDecl *base_class_decl,
292 int32_t &bit_offset) {
293 ExecutionContext exe_ctx(valobj.GetExecutionContextRef());
294 Process *process = exe_ctx.GetProcessPtr();
295 if (!process)
296 return false;
297
298 lldb::addr_t vtable_ptr =
299 GetVTableAddress(*process, vtable_ctx, valobj, record_layout);
300 if (vtable_ptr == LLDB_INVALID_ADDRESS)
301 return false;
302
303 auto base_offset = ReadVBaseOffsetFromVTable(
304 *process, vtable_ctx, vtable_ptr, cxx_record_decl, base_class_decl);
305 if (base_offset == INT64_MAX)
306 return false;
307
308 bit_offset = base_offset * 8;
309
310 return true;
311 }
312
313 typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, TypeSystemClang *>
314 ClangASTMap;
315
GetASTMap()316 static ClangASTMap &GetASTMap() {
317 static ClangASTMap *g_map_ptr = nullptr;
318 static llvm::once_flag g_once_flag;
319 llvm::call_once(g_once_flag, []() {
320 g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins
321 });
322 return *g_map_ptr;
323 }
324
TypePayloadClang(OptionalClangModuleID owning_module,bool is_complete_objc_class)325 TypePayloadClang::TypePayloadClang(OptionalClangModuleID owning_module,
326 bool is_complete_objc_class)
327 : m_payload(owning_module.GetValue()) {
328 SetIsCompleteObjCClass(is_complete_objc_class);
329 }
330
SetOwningModule(OptionalClangModuleID id)331 void TypePayloadClang::SetOwningModule(OptionalClangModuleID id) {
332 assert(id.GetValue() < ObjCClassBit);
333 bool is_complete = IsCompleteObjCClass();
334 m_payload = id.GetValue();
335 SetIsCompleteObjCClass(is_complete);
336 }
337
SetMemberOwningModule(clang::Decl * member,const clang::Decl * parent)338 static void SetMemberOwningModule(clang::Decl *member,
339 const clang::Decl *parent) {
340 if (!member || !parent)
341 return;
342
343 OptionalClangModuleID id(parent->getOwningModuleID());
344 if (!id.HasValue())
345 return;
346
347 member->setFromASTFile();
348 member->setOwningModuleID(id.GetValue());
349 member->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible);
350 if (llvm::isa<clang::NamedDecl>(member))
351 if (auto *dc = llvm::dyn_cast<clang::DeclContext>(parent)) {
352 dc->setHasExternalVisibleStorage(true);
353 // This triggers ExternalASTSource::FindExternalVisibleDeclsByName() to be
354 // called when searching for members.
355 dc->setHasExternalLexicalStorage(true);
356 }
357 }
358
359 char TypeSystemClang::ID;
360
IsOperator(llvm::StringRef name,clang::OverloadedOperatorKind & op_kind)361 bool TypeSystemClang::IsOperator(llvm::StringRef name,
362 clang::OverloadedOperatorKind &op_kind) {
363 // All operators have to start with "operator".
364 if (!name.consume_front("operator"))
365 return false;
366
367 // Remember if there was a space after "operator". This is necessary to
368 // check for collisions with strangely named functions like "operatorint()".
369 bool space_after_operator = name.consume_front(" ");
370
371 op_kind = StringSwitch<clang::OverloadedOperatorKind>(name)
372 .Case("+", clang::OO_Plus)
373 .Case("+=", clang::OO_PlusEqual)
374 .Case("++", clang::OO_PlusPlus)
375 .Case("-", clang::OO_Minus)
376 .Case("-=", clang::OO_MinusEqual)
377 .Case("--", clang::OO_MinusMinus)
378 .Case("->", clang::OO_Arrow)
379 .Case("->*", clang::OO_ArrowStar)
380 .Case("*", clang::OO_Star)
381 .Case("*=", clang::OO_StarEqual)
382 .Case("/", clang::OO_Slash)
383 .Case("/=", clang::OO_SlashEqual)
384 .Case("%", clang::OO_Percent)
385 .Case("%=", clang::OO_PercentEqual)
386 .Case("^", clang::OO_Caret)
387 .Case("^=", clang::OO_CaretEqual)
388 .Case("&", clang::OO_Amp)
389 .Case("&=", clang::OO_AmpEqual)
390 .Case("&&", clang::OO_AmpAmp)
391 .Case("|", clang::OO_Pipe)
392 .Case("|=", clang::OO_PipeEqual)
393 .Case("||", clang::OO_PipePipe)
394 .Case("~", clang::OO_Tilde)
395 .Case("!", clang::OO_Exclaim)
396 .Case("!=", clang::OO_ExclaimEqual)
397 .Case("=", clang::OO_Equal)
398 .Case("==", clang::OO_EqualEqual)
399 .Case("<", clang::OO_Less)
400 .Case("<<", clang::OO_LessLess)
401 .Case("<<=", clang::OO_LessLessEqual)
402 .Case("<=", clang::OO_LessEqual)
403 .Case(">", clang::OO_Greater)
404 .Case(">>", clang::OO_GreaterGreater)
405 .Case(">>=", clang::OO_GreaterGreaterEqual)
406 .Case(">=", clang::OO_GreaterEqual)
407 .Case("()", clang::OO_Call)
408 .Case("[]", clang::OO_Subscript)
409 .Case(",", clang::OO_Comma)
410 .Default(clang::NUM_OVERLOADED_OPERATORS);
411
412 // We found a fitting operator, so we can exit now.
413 if (op_kind != clang::NUM_OVERLOADED_OPERATORS)
414 return true;
415
416 // After the "operator " or "operator" part is something unknown. This means
417 // it's either one of the named operators (new/delete), a conversion operator
418 // (e.g. operator bool) or a function which name starts with "operator"
419 // (e.g. void operatorbool).
420
421 // If it's a function that starts with operator it can't have a space after
422 // "operator" because identifiers can't contain spaces.
423 // E.g. "operator int" (conversion operator)
424 // vs. "operatorint" (function with colliding name).
425 if (!space_after_operator)
426 return false; // not an operator.
427
428 // Now the operator is either one of the named operators or a conversion
429 // operator.
430 op_kind = StringSwitch<clang::OverloadedOperatorKind>(name)
431 .Case("new", clang::OO_New)
432 .Case("new[]", clang::OO_Array_New)
433 .Case("delete", clang::OO_Delete)
434 .Case("delete[]", clang::OO_Array_Delete)
435 // conversion operators hit this case.
436 .Default(clang::NUM_OVERLOADED_OPERATORS);
437
438 return true;
439 }
440
441 clang::AccessSpecifier
ConvertAccessTypeToAccessSpecifier(AccessType access)442 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(AccessType access) {
443 switch (access) {
444 default:
445 break;
446 case eAccessNone:
447 return AS_none;
448 case eAccessPublic:
449 return AS_public;
450 case eAccessPrivate:
451 return AS_private;
452 case eAccessProtected:
453 return AS_protected;
454 }
455 return AS_none;
456 }
457
ParseLangArgs(LangOptions & Opts,InputKind IK,const char * triple)458 static void ParseLangArgs(LangOptions &Opts, InputKind IK, const char *triple) {
459 // FIXME: Cleanup per-file based stuff.
460
461 // Set some properties which depend solely on the input kind; it would be
462 // nice to move these to the language standard, and have the driver resolve
463 // the input kind + language standard.
464 if (IK.getLanguage() == clang::Language::Asm) {
465 Opts.AsmPreprocessor = 1;
466 } else if (IK.isObjectiveC()) {
467 Opts.ObjC = 1;
468 }
469
470 LangStandard::Kind LangStd = LangStandard::lang_unspecified;
471
472 if (LangStd == LangStandard::lang_unspecified) {
473 // Based on the base language, pick one.
474 switch (IK.getLanguage()) {
475 case clang::Language::Unknown:
476 case clang::Language::LLVM_IR:
477 case clang::Language::RenderScript:
478 llvm_unreachable("Invalid input kind!");
479 case clang::Language::OpenCL:
480 LangStd = LangStandard::lang_opencl10;
481 break;
482 case clang::Language::CUDA:
483 LangStd = LangStandard::lang_cuda;
484 break;
485 case clang::Language::Asm:
486 case clang::Language::C:
487 case clang::Language::ObjC:
488 LangStd = LangStandard::lang_gnu99;
489 break;
490 case clang::Language::CXX:
491 case clang::Language::ObjCXX:
492 LangStd = LangStandard::lang_gnucxx98;
493 break;
494 case clang::Language::HIP:
495 LangStd = LangStandard::lang_hip;
496 break;
497 }
498 }
499
500 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
501 Opts.LineComment = Std.hasLineComments();
502 Opts.C99 = Std.isC99();
503 Opts.CPlusPlus = Std.isCPlusPlus();
504 Opts.CPlusPlus11 = Std.isCPlusPlus11();
505 Opts.Digraphs = Std.hasDigraphs();
506 Opts.GNUMode = Std.isGNUMode();
507 Opts.GNUInline = !Std.isC99();
508 Opts.HexFloats = Std.hasHexFloats();
509 Opts.ImplicitInt = Std.hasImplicitInt();
510
511 Opts.WChar = true;
512
513 // OpenCL has some additional defaults.
514 if (LangStd == LangStandard::lang_opencl10) {
515 Opts.OpenCL = 1;
516 Opts.AltiVec = 1;
517 Opts.CXXOperatorNames = 1;
518 Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::All);
519 }
520
521 // OpenCL and C++ both have bool, true, false keywords.
522 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
523
524 Opts.setValueVisibilityMode(DefaultVisibility);
525
526 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs is
527 // specified, or -std is set to a conforming mode.
528 Opts.Trigraphs = !Opts.GNUMode;
529 Opts.CharIsSigned = ArchSpec(triple).CharIsSignedByDefault();
530 Opts.OptimizeSize = 0;
531
532 // FIXME: Eliminate this dependency.
533 // unsigned Opt =
534 // Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
535 // Opts.Optimize = Opt != 0;
536 unsigned Opt = 0;
537
538 // This is the __NO_INLINE__ define, which just depends on things like the
539 // optimization level and -fno-inline, not actually whether the backend has
540 // inlining enabled.
541 //
542 // FIXME: This is affected by other options (-fno-inline).
543 Opts.NoInlineDefine = !Opt;
544
545 // This is needed to allocate the extra space for the owning module
546 // on each decl.
547 Opts.ModulesLocalVisibility = 1;
548 }
549
TypeSystemClang(llvm::StringRef name,llvm::Triple target_triple)550 TypeSystemClang::TypeSystemClang(llvm::StringRef name,
551 llvm::Triple target_triple) {
552 m_display_name = name.str();
553 if (!target_triple.str().empty())
554 SetTargetTriple(target_triple.str());
555 // The caller didn't pass an ASTContext so create a new one for this
556 // TypeSystemClang.
557 CreateASTContext();
558 }
559
TypeSystemClang(llvm::StringRef name,ASTContext & existing_ctxt)560 TypeSystemClang::TypeSystemClang(llvm::StringRef name,
561 ASTContext &existing_ctxt) {
562 m_display_name = name.str();
563 SetTargetTriple(existing_ctxt.getTargetInfo().getTriple().str());
564
565 m_ast_up.reset(&existing_ctxt);
566 GetASTMap().Insert(&existing_ctxt, this);
567 }
568
569 // Destructor
~TypeSystemClang()570 TypeSystemClang::~TypeSystemClang() { Finalize(); }
571
GetPluginNameStatic()572 ConstString TypeSystemClang::GetPluginNameStatic() {
573 return ConstString("clang");
574 }
575
GetPluginName()576 ConstString TypeSystemClang::GetPluginName() {
577 return TypeSystemClang::GetPluginNameStatic();
578 }
579
GetPluginVersion()580 uint32_t TypeSystemClang::GetPluginVersion() { return 1; }
581
CreateInstance(lldb::LanguageType language,lldb_private::Module * module,Target * target)582 lldb::TypeSystemSP TypeSystemClang::CreateInstance(lldb::LanguageType language,
583 lldb_private::Module *module,
584 Target *target) {
585 if (!TypeSystemClangSupportsLanguage(language))
586 return lldb::TypeSystemSP();
587 ArchSpec arch;
588 if (module)
589 arch = module->GetArchitecture();
590 else if (target)
591 arch = target->GetArchitecture();
592
593 if (!arch.IsValid())
594 return lldb::TypeSystemSP();
595
596 llvm::Triple triple = arch.GetTriple();
597 // LLVM wants this to be set to iOS or MacOSX; if we're working on
598 // a bare-boards type image, change the triple for llvm's benefit.
599 if (triple.getVendor() == llvm::Triple::Apple &&
600 triple.getOS() == llvm::Triple::UnknownOS) {
601 if (triple.getArch() == llvm::Triple::arm ||
602 triple.getArch() == llvm::Triple::aarch64 ||
603 triple.getArch() == llvm::Triple::aarch64_32 ||
604 triple.getArch() == llvm::Triple::thumb) {
605 triple.setOS(llvm::Triple::IOS);
606 } else {
607 triple.setOS(llvm::Triple::MacOSX);
608 }
609 }
610
611 if (module) {
612 std::string ast_name =
613 "ASTContext for '" + module->GetFileSpec().GetPath() + "'";
614 return std::make_shared<TypeSystemClang>(ast_name, triple);
615 } else if (target && target->IsValid())
616 return std::make_shared<ScratchTypeSystemClang>(*target, triple);
617 return lldb::TypeSystemSP();
618 }
619
GetSupportedLanguagesForTypes()620 LanguageSet TypeSystemClang::GetSupportedLanguagesForTypes() {
621 LanguageSet languages;
622 languages.Insert(lldb::eLanguageTypeC89);
623 languages.Insert(lldb::eLanguageTypeC);
624 languages.Insert(lldb::eLanguageTypeC11);
625 languages.Insert(lldb::eLanguageTypeC_plus_plus);
626 languages.Insert(lldb::eLanguageTypeC99);
627 languages.Insert(lldb::eLanguageTypeObjC);
628 languages.Insert(lldb::eLanguageTypeObjC_plus_plus);
629 languages.Insert(lldb::eLanguageTypeC_plus_plus_03);
630 languages.Insert(lldb::eLanguageTypeC_plus_plus_11);
631 languages.Insert(lldb::eLanguageTypeC11);
632 languages.Insert(lldb::eLanguageTypeC_plus_plus_14);
633 return languages;
634 }
635
GetSupportedLanguagesForExpressions()636 LanguageSet TypeSystemClang::GetSupportedLanguagesForExpressions() {
637 LanguageSet languages;
638 languages.Insert(lldb::eLanguageTypeC_plus_plus);
639 languages.Insert(lldb::eLanguageTypeObjC_plus_plus);
640 languages.Insert(lldb::eLanguageTypeC_plus_plus_03);
641 languages.Insert(lldb::eLanguageTypeC_plus_plus_11);
642 languages.Insert(lldb::eLanguageTypeC_plus_plus_14);
643 return languages;
644 }
645
Initialize()646 void TypeSystemClang::Initialize() {
647 PluginManager::RegisterPlugin(
648 GetPluginNameStatic(), "clang base AST context plug-in", CreateInstance,
649 GetSupportedLanguagesForTypes(), GetSupportedLanguagesForExpressions());
650 }
651
Terminate()652 void TypeSystemClang::Terminate() {
653 PluginManager::UnregisterPlugin(CreateInstance);
654 }
655
Finalize()656 void TypeSystemClang::Finalize() {
657 assert(m_ast_up);
658 GetASTMap().Erase(m_ast_up.get());
659 if (!m_ast_owned)
660 m_ast_up.release();
661
662 m_builtins_up.reset();
663 m_selector_table_up.reset();
664 m_identifier_table_up.reset();
665 m_target_info_up.reset();
666 m_target_options_rp.reset();
667 m_diagnostics_engine_up.reset();
668 m_source_manager_up.reset();
669 m_language_options_up.reset();
670 }
671
setSema(Sema * s)672 void TypeSystemClang::setSema(Sema *s) {
673 // Ensure that the new sema actually belongs to our ASTContext.
674 assert(s == nullptr || &s->getASTContext() == m_ast_up.get());
675 m_sema = s;
676 }
677
GetTargetTriple()678 const char *TypeSystemClang::GetTargetTriple() {
679 return m_target_triple.c_str();
680 }
681
SetTargetTriple(llvm::StringRef target_triple)682 void TypeSystemClang::SetTargetTriple(llvm::StringRef target_triple) {
683 m_target_triple = target_triple.str();
684 }
685
SetExternalSource(llvm::IntrusiveRefCntPtr<ExternalASTSource> & ast_source_up)686 void TypeSystemClang::SetExternalSource(
687 llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_up) {
688 ASTContext &ast = getASTContext();
689 ast.setExternalSource(ast_source_up);
690 ast.getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
691 }
692
getASTContext()693 ASTContext &TypeSystemClang::getASTContext() {
694 assert(m_ast_up);
695 return *m_ast_up;
696 }
697
698 class NullDiagnosticConsumer : public DiagnosticConsumer {
699 public:
NullDiagnosticConsumer()700 NullDiagnosticConsumer() {
701 m_log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
702 }
703
HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,const clang::Diagnostic & info)704 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
705 const clang::Diagnostic &info) override {
706 if (m_log) {
707 llvm::SmallVector<char, 32> diag_str(10);
708 info.FormatDiagnostic(diag_str);
709 diag_str.push_back('\0');
710 LLDB_LOGF(m_log, "Compiler diagnostic: %s\n", diag_str.data());
711 }
712 }
713
clone(DiagnosticsEngine & Diags) const714 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
715 return new NullDiagnosticConsumer();
716 }
717
718 private:
719 Log *m_log;
720 };
721
CreateASTContext()722 void TypeSystemClang::CreateASTContext() {
723 assert(!m_ast_up);
724 m_ast_owned = true;
725
726 m_language_options_up = std::make_unique<LangOptions>();
727 ParseLangArgs(*m_language_options_up, clang::Language::ObjCXX,
728 GetTargetTriple());
729
730 m_identifier_table_up =
731 std::make_unique<IdentifierTable>(*m_language_options_up, nullptr);
732 m_builtins_up = std::make_unique<Builtin::Context>();
733
734 m_selector_table_up = std::make_unique<SelectorTable>();
735
736 clang::FileSystemOptions file_system_options;
737 m_file_manager_up = std::make_unique<clang::FileManager>(
738 file_system_options, FileSystem::Instance().GetVirtualFileSystem());
739
740 llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
741 m_diagnostics_engine_up =
742 std::make_unique<DiagnosticsEngine>(diag_id_sp, new DiagnosticOptions());
743
744 m_source_manager_up = std::make_unique<clang::SourceManager>(
745 *m_diagnostics_engine_up, *m_file_manager_up);
746 m_ast_up = std::make_unique<ASTContext>(
747 *m_language_options_up, *m_source_manager_up, *m_identifier_table_up,
748 *m_selector_table_up, *m_builtins_up);
749
750 m_diagnostic_consumer_up = std::make_unique<NullDiagnosticConsumer>();
751 m_ast_up->getDiagnostics().setClient(m_diagnostic_consumer_up.get(), false);
752
753 // This can be NULL if we don't know anything about the architecture or if
754 // the target for an architecture isn't enabled in the llvm/clang that we
755 // built
756 TargetInfo *target_info = getTargetInfo();
757 if (target_info)
758 m_ast_up->InitBuiltinTypes(*target_info);
759
760 GetASTMap().Insert(m_ast_up.get(), this);
761
762 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_up(
763 new ClangExternalASTSourceCallbacks(*this));
764 SetExternalSource(ast_source_up);
765 }
766
GetASTContext(clang::ASTContext * ast)767 TypeSystemClang *TypeSystemClang::GetASTContext(clang::ASTContext *ast) {
768 TypeSystemClang *clang_ast = GetASTMap().Lookup(ast);
769 return clang_ast;
770 }
771
getMangleContext()772 clang::MangleContext *TypeSystemClang::getMangleContext() {
773 if (m_mangle_ctx_up == nullptr)
774 m_mangle_ctx_up.reset(getASTContext().createMangleContext());
775 return m_mangle_ctx_up.get();
776 }
777
getTargetOptions()778 std::shared_ptr<clang::TargetOptions> &TypeSystemClang::getTargetOptions() {
779 if (m_target_options_rp == nullptr && !m_target_triple.empty()) {
780 m_target_options_rp = std::make_shared<clang::TargetOptions>();
781 if (m_target_options_rp != nullptr)
782 m_target_options_rp->Triple = m_target_triple;
783 }
784 return m_target_options_rp;
785 }
786
getTargetInfo()787 TargetInfo *TypeSystemClang::getTargetInfo() {
788 // target_triple should be something like "x86_64-apple-macosx"
789 if (m_target_info_up == nullptr && !m_target_triple.empty())
790 m_target_info_up.reset(TargetInfo::CreateTargetInfo(
791 getASTContext().getDiagnostics(), getTargetOptions()));
792 return m_target_info_up.get();
793 }
794
795 #pragma mark Basic Types
796
QualTypeMatchesBitSize(const uint64_t bit_size,ASTContext & ast,QualType qual_type)797 static inline bool QualTypeMatchesBitSize(const uint64_t bit_size,
798 ASTContext &ast, QualType qual_type) {
799 uint64_t qual_type_bit_size = ast.getTypeSize(qual_type);
800 return qual_type_bit_size == bit_size;
801 }
802
803 CompilerType
GetBuiltinTypeForEncodingAndBitSize(Encoding encoding,size_t bit_size)804 TypeSystemClang::GetBuiltinTypeForEncodingAndBitSize(Encoding encoding,
805 size_t bit_size) {
806 ASTContext &ast = getASTContext();
807 switch (encoding) {
808 case eEncodingInvalid:
809 if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy))
810 return GetType(ast.VoidPtrTy);
811 break;
812
813 case eEncodingUint:
814 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
815 return GetType(ast.UnsignedCharTy);
816 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
817 return GetType(ast.UnsignedShortTy);
818 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
819 return GetType(ast.UnsignedIntTy);
820 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
821 return GetType(ast.UnsignedLongTy);
822 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
823 return GetType(ast.UnsignedLongLongTy);
824 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
825 return GetType(ast.UnsignedInt128Ty);
826 break;
827
828 case eEncodingSint:
829 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
830 return GetType(ast.SignedCharTy);
831 if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
832 return GetType(ast.ShortTy);
833 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
834 return GetType(ast.IntTy);
835 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
836 return GetType(ast.LongTy);
837 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
838 return GetType(ast.LongLongTy);
839 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
840 return GetType(ast.Int128Ty);
841 break;
842
843 case eEncodingIEEE754:
844 if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
845 return GetType(ast.FloatTy);
846 if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
847 return GetType(ast.DoubleTy);
848 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
849 return GetType(ast.LongDoubleTy);
850 if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy))
851 return GetType(ast.HalfTy);
852 break;
853
854 case eEncodingVector:
855 // Sanity check that bit_size is a multiple of 8's.
856 if (bit_size && !(bit_size & 0x7u))
857 return GetType(ast.getExtVectorType(ast.UnsignedCharTy, bit_size / 8));
858 break;
859 }
860
861 return CompilerType();
862 }
863
864 lldb::BasicType
GetBasicTypeEnumeration(ConstString name)865 TypeSystemClang::GetBasicTypeEnumeration(ConstString name) {
866 if (name) {
867 typedef UniqueCStringMap<lldb::BasicType> TypeNameToBasicTypeMap;
868 static TypeNameToBasicTypeMap g_type_map;
869 static llvm::once_flag g_once_flag;
870 llvm::call_once(g_once_flag, []() {
871 // "void"
872 g_type_map.Append(ConstString("void"), eBasicTypeVoid);
873
874 // "char"
875 g_type_map.Append(ConstString("char"), eBasicTypeChar);
876 g_type_map.Append(ConstString("signed char"), eBasicTypeSignedChar);
877 g_type_map.Append(ConstString("unsigned char"), eBasicTypeUnsignedChar);
878 g_type_map.Append(ConstString("wchar_t"), eBasicTypeWChar);
879 g_type_map.Append(ConstString("signed wchar_t"), eBasicTypeSignedWChar);
880 g_type_map.Append(ConstString("unsigned wchar_t"),
881 eBasicTypeUnsignedWChar);
882 // "short"
883 g_type_map.Append(ConstString("short"), eBasicTypeShort);
884 g_type_map.Append(ConstString("short int"), eBasicTypeShort);
885 g_type_map.Append(ConstString("unsigned short"), eBasicTypeUnsignedShort);
886 g_type_map.Append(ConstString("unsigned short int"),
887 eBasicTypeUnsignedShort);
888
889 // "int"
890 g_type_map.Append(ConstString("int"), eBasicTypeInt);
891 g_type_map.Append(ConstString("signed int"), eBasicTypeInt);
892 g_type_map.Append(ConstString("unsigned int"), eBasicTypeUnsignedInt);
893 g_type_map.Append(ConstString("unsigned"), eBasicTypeUnsignedInt);
894
895 // "long"
896 g_type_map.Append(ConstString("long"), eBasicTypeLong);
897 g_type_map.Append(ConstString("long int"), eBasicTypeLong);
898 g_type_map.Append(ConstString("unsigned long"), eBasicTypeUnsignedLong);
899 g_type_map.Append(ConstString("unsigned long int"),
900 eBasicTypeUnsignedLong);
901
902 // "long long"
903 g_type_map.Append(ConstString("long long"), eBasicTypeLongLong);
904 g_type_map.Append(ConstString("long long int"), eBasicTypeLongLong);
905 g_type_map.Append(ConstString("unsigned long long"),
906 eBasicTypeUnsignedLongLong);
907 g_type_map.Append(ConstString("unsigned long long int"),
908 eBasicTypeUnsignedLongLong);
909
910 // "int128"
911 g_type_map.Append(ConstString("__int128_t"), eBasicTypeInt128);
912 g_type_map.Append(ConstString("__uint128_t"), eBasicTypeUnsignedInt128);
913
914 // Miscellaneous
915 g_type_map.Append(ConstString("bool"), eBasicTypeBool);
916 g_type_map.Append(ConstString("float"), eBasicTypeFloat);
917 g_type_map.Append(ConstString("double"), eBasicTypeDouble);
918 g_type_map.Append(ConstString("long double"), eBasicTypeLongDouble);
919 g_type_map.Append(ConstString("id"), eBasicTypeObjCID);
920 g_type_map.Append(ConstString("SEL"), eBasicTypeObjCSel);
921 g_type_map.Append(ConstString("nullptr"), eBasicTypeNullPtr);
922 g_type_map.Sort();
923 });
924
925 return g_type_map.Find(name, eBasicTypeInvalid);
926 }
927 return eBasicTypeInvalid;
928 }
929
GetPointerByteSize()930 uint32_t TypeSystemClang::GetPointerByteSize() {
931 if (m_pointer_byte_size == 0)
932 if (auto size = GetBasicType(lldb::eBasicTypeVoid)
933 .GetPointerType()
934 .GetByteSize(nullptr))
935 m_pointer_byte_size = *size;
936 return m_pointer_byte_size;
937 }
938
GetBasicType(lldb::BasicType basic_type)939 CompilerType TypeSystemClang::GetBasicType(lldb::BasicType basic_type) {
940 clang::ASTContext &ast = getASTContext();
941
942 lldb::opaque_compiler_type_t clang_type =
943 GetOpaqueCompilerType(&ast, basic_type);
944
945 if (clang_type)
946 return CompilerType(this, clang_type);
947 return CompilerType();
948 }
949
GetBuiltinTypeForDWARFEncodingAndBitSize(llvm::StringRef type_name,uint32_t dw_ate,uint32_t bit_size)950 CompilerType TypeSystemClang::GetBuiltinTypeForDWARFEncodingAndBitSize(
951 llvm::StringRef type_name, uint32_t dw_ate, uint32_t bit_size) {
952 ASTContext &ast = getASTContext();
953
954 switch (dw_ate) {
955 default:
956 break;
957
958 case DW_ATE_address:
959 if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy))
960 return GetType(ast.VoidPtrTy);
961 break;
962
963 case DW_ATE_boolean:
964 if (QualTypeMatchesBitSize(bit_size, ast, ast.BoolTy))
965 return GetType(ast.BoolTy);
966 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
967 return GetType(ast.UnsignedCharTy);
968 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
969 return GetType(ast.UnsignedShortTy);
970 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
971 return GetType(ast.UnsignedIntTy);
972 break;
973
974 case DW_ATE_lo_user:
975 // This has been seen to mean DW_AT_complex_integer
976 if (type_name.contains("complex")) {
977 CompilerType complex_int_clang_type =
978 GetBuiltinTypeForDWARFEncodingAndBitSize("int", DW_ATE_signed,
979 bit_size / 2);
980 return GetType(
981 ast.getComplexType(ClangUtil::GetQualType(complex_int_clang_type)));
982 }
983 break;
984
985 case DW_ATE_complex_float:
986 if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatComplexTy))
987 return GetType(ast.FloatComplexTy);
988 else if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleComplexTy))
989 return GetType(ast.DoubleComplexTy);
990 else if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleComplexTy))
991 return GetType(ast.LongDoubleComplexTy);
992 else {
993 CompilerType complex_float_clang_type =
994 GetBuiltinTypeForDWARFEncodingAndBitSize("float", DW_ATE_float,
995 bit_size / 2);
996 return GetType(
997 ast.getComplexType(ClangUtil::GetQualType(complex_float_clang_type)));
998 }
999 break;
1000
1001 case DW_ATE_float:
1002 if (type_name == "float" &&
1003 QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
1004 return GetType(ast.FloatTy);
1005 if (type_name == "double" &&
1006 QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
1007 return GetType(ast.DoubleTy);
1008 if (type_name == "long double" &&
1009 QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
1010 return GetType(ast.LongDoubleTy);
1011 // Fall back to not requiring a name match
1012 if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
1013 return GetType(ast.FloatTy);
1014 if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
1015 return GetType(ast.DoubleTy);
1016 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
1017 return GetType(ast.LongDoubleTy);
1018 if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy))
1019 return GetType(ast.HalfTy);
1020 break;
1021
1022 case DW_ATE_signed:
1023 if (!type_name.empty()) {
1024 if (type_name == "wchar_t" &&
1025 QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy) &&
1026 (getTargetInfo() &&
1027 TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1028 return GetType(ast.WCharTy);
1029 if (type_name == "void" &&
1030 QualTypeMatchesBitSize(bit_size, ast, ast.VoidTy))
1031 return GetType(ast.VoidTy);
1032 if (type_name.contains("long long") &&
1033 QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
1034 return GetType(ast.LongLongTy);
1035 if (type_name.contains("long") &&
1036 QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
1037 return GetType(ast.LongTy);
1038 if (type_name.contains("short") &&
1039 QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
1040 return GetType(ast.ShortTy);
1041 if (type_name.contains("char")) {
1042 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1043 return GetType(ast.CharTy);
1044 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
1045 return GetType(ast.SignedCharTy);
1046 }
1047 if (type_name.contains("int")) {
1048 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
1049 return GetType(ast.IntTy);
1050 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
1051 return GetType(ast.Int128Ty);
1052 }
1053 }
1054 // We weren't able to match up a type name, just search by size
1055 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1056 return GetType(ast.CharTy);
1057 if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
1058 return GetType(ast.ShortTy);
1059 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
1060 return GetType(ast.IntTy);
1061 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
1062 return GetType(ast.LongTy);
1063 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
1064 return GetType(ast.LongLongTy);
1065 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
1066 return GetType(ast.Int128Ty);
1067 break;
1068
1069 case DW_ATE_signed_char:
1070 if (ast.getLangOpts().CharIsSigned && type_name == "char") {
1071 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1072 return GetType(ast.CharTy);
1073 }
1074 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
1075 return GetType(ast.SignedCharTy);
1076 break;
1077
1078 case DW_ATE_unsigned:
1079 if (!type_name.empty()) {
1080 if (type_name == "wchar_t") {
1081 if (QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy)) {
1082 if (!(getTargetInfo() &&
1083 TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1084 return GetType(ast.WCharTy);
1085 }
1086 }
1087 if (type_name.contains("long long")) {
1088 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
1089 return GetType(ast.UnsignedLongLongTy);
1090 } else if (type_name.contains("long")) {
1091 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
1092 return GetType(ast.UnsignedLongTy);
1093 } else if (type_name.contains("short")) {
1094 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1095 return GetType(ast.UnsignedShortTy);
1096 } else if (type_name.contains("char")) {
1097 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1098 return GetType(ast.UnsignedCharTy);
1099 } else if (type_name.contains("int")) {
1100 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
1101 return GetType(ast.UnsignedIntTy);
1102 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
1103 return GetType(ast.UnsignedInt128Ty);
1104 }
1105 }
1106 // We weren't able to match up a type name, just search by size
1107 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1108 return GetType(ast.UnsignedCharTy);
1109 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1110 return GetType(ast.UnsignedShortTy);
1111 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
1112 return GetType(ast.UnsignedIntTy);
1113 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
1114 return GetType(ast.UnsignedLongTy);
1115 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
1116 return GetType(ast.UnsignedLongLongTy);
1117 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
1118 return GetType(ast.UnsignedInt128Ty);
1119 break;
1120
1121 case DW_ATE_unsigned_char:
1122 if (!ast.getLangOpts().CharIsSigned && type_name == "char") {
1123 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1124 return GetType(ast.CharTy);
1125 }
1126 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1127 return GetType(ast.UnsignedCharTy);
1128 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1129 return GetType(ast.UnsignedShortTy);
1130 break;
1131
1132 case DW_ATE_imaginary_float:
1133 break;
1134
1135 case DW_ATE_UTF:
1136 switch (bit_size) {
1137 case 8:
1138 return GetType(ast.Char8Ty);
1139 case 16:
1140 return GetType(ast.Char16Ty);
1141 case 32:
1142 return GetType(ast.Char32Ty);
1143 default:
1144 if (!type_name.empty()) {
1145 if (type_name == "char16_t")
1146 return GetType(ast.Char16Ty);
1147 if (type_name == "char32_t")
1148 return GetType(ast.Char32Ty);
1149 if (type_name == "char8_t")
1150 return GetType(ast.Char8Ty);
1151 }
1152 }
1153 break;
1154 }
1155 // This assert should fire for anything that we don't catch above so we know
1156 // to fix any issues we run into.
1157 if (!type_name.empty()) {
1158 std::string type_name_str = type_name.str();
1159 Host::SystemLog(Host::eSystemLogError,
1160 "error: need to add support for DW_TAG_base_type '%s' "
1161 "encoded with DW_ATE = 0x%x, bit_size = %u\n",
1162 type_name_str.c_str(), dw_ate, bit_size);
1163 } else {
1164 Host::SystemLog(Host::eSystemLogError, "error: need to add support for "
1165 "DW_TAG_base_type encoded with "
1166 "DW_ATE = 0x%x, bit_size = %u\n",
1167 dw_ate, bit_size);
1168 }
1169 return CompilerType();
1170 }
1171
GetCStringType(bool is_const)1172 CompilerType TypeSystemClang::GetCStringType(bool is_const) {
1173 ASTContext &ast = getASTContext();
1174 QualType char_type(ast.CharTy);
1175
1176 if (is_const)
1177 char_type.addConst();
1178
1179 return GetType(ast.getPointerType(char_type));
1180 }
1181
AreTypesSame(CompilerType type1,CompilerType type2,bool ignore_qualifiers)1182 bool TypeSystemClang::AreTypesSame(CompilerType type1, CompilerType type2,
1183 bool ignore_qualifiers) {
1184 TypeSystemClang *ast =
1185 llvm::dyn_cast_or_null<TypeSystemClang>(type1.GetTypeSystem());
1186 if (!ast || ast != type2.GetTypeSystem())
1187 return false;
1188
1189 if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType())
1190 return true;
1191
1192 QualType type1_qual = ClangUtil::GetQualType(type1);
1193 QualType type2_qual = ClangUtil::GetQualType(type2);
1194
1195 if (ignore_qualifiers) {
1196 type1_qual = type1_qual.getUnqualifiedType();
1197 type2_qual = type2_qual.getUnqualifiedType();
1198 }
1199
1200 return ast->getASTContext().hasSameType(type1_qual, type2_qual);
1201 }
1202
GetTypeForDecl(void * opaque_decl)1203 CompilerType TypeSystemClang::GetTypeForDecl(void *opaque_decl) {
1204 if (!opaque_decl)
1205 return CompilerType();
1206
1207 clang::Decl *decl = static_cast<clang::Decl *>(opaque_decl);
1208 if (auto *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl))
1209 return GetTypeForDecl(named_decl);
1210 return CompilerType();
1211 }
1212
CreateDeclContext(DeclContext * ctx)1213 CompilerDeclContext TypeSystemClang::CreateDeclContext(DeclContext *ctx) {
1214 // Check that the DeclContext actually belongs to this ASTContext.
1215 assert(&ctx->getParentASTContext() == &getASTContext());
1216 return CompilerDeclContext(this, ctx);
1217 }
1218
GetTypeForDecl(clang::NamedDecl * decl)1219 CompilerType TypeSystemClang::GetTypeForDecl(clang::NamedDecl *decl) {
1220 if (clang::ObjCInterfaceDecl *interface_decl =
1221 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
1222 return GetTypeForDecl(interface_decl);
1223 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
1224 return GetTypeForDecl(tag_decl);
1225 return CompilerType();
1226 }
1227
GetTypeForDecl(TagDecl * decl)1228 CompilerType TypeSystemClang::GetTypeForDecl(TagDecl *decl) {
1229 return GetType(getASTContext().getTagDeclType(decl));
1230 }
1231
GetTypeForDecl(ObjCInterfaceDecl * decl)1232 CompilerType TypeSystemClang::GetTypeForDecl(ObjCInterfaceDecl *decl) {
1233 return GetType(getASTContext().getObjCInterfaceType(decl));
1234 }
1235
1236 #pragma mark Structure, Unions, Classes
1237
SetOwningModule(clang::Decl * decl,OptionalClangModuleID owning_module)1238 void TypeSystemClang::SetOwningModule(clang::Decl *decl,
1239 OptionalClangModuleID owning_module) {
1240 if (!decl || !owning_module.HasValue())
1241 return;
1242
1243 decl->setFromASTFile();
1244 decl->setOwningModuleID(owning_module.GetValue());
1245 decl->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible);
1246 }
1247
1248 OptionalClangModuleID
GetOrCreateClangModule(llvm::StringRef name,OptionalClangModuleID parent,bool is_framework,bool is_explicit)1249 TypeSystemClang::GetOrCreateClangModule(llvm::StringRef name,
1250 OptionalClangModuleID parent,
1251 bool is_framework, bool is_explicit) {
1252 // Get the external AST source which holds the modules.
1253 auto *ast_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1254 getASTContext().getExternalSource());
1255 assert(ast_source && "external ast source was lost");
1256 if (!ast_source)
1257 return {};
1258
1259 // Lazily initialize the module map.
1260 if (!m_header_search_up) {
1261 auto HSOpts = std::make_shared<clang::HeaderSearchOptions>();
1262 m_header_search_up = std::make_unique<clang::HeaderSearch>(
1263 HSOpts, *m_source_manager_up, *m_diagnostics_engine_up,
1264 *m_language_options_up, m_target_info_up.get());
1265 m_module_map_up = std::make_unique<clang::ModuleMap>(
1266 *m_source_manager_up, *m_diagnostics_engine_up, *m_language_options_up,
1267 m_target_info_up.get(), *m_header_search_up);
1268 }
1269
1270 // Get or create the module context.
1271 bool created;
1272 clang::Module *module;
1273 auto parent_desc = ast_source->getSourceDescriptor(parent.GetValue());
1274 std::tie(module, created) = m_module_map_up->findOrCreateModule(
1275 name, parent_desc ? parent_desc->getModuleOrNull() : nullptr,
1276 is_framework, is_explicit);
1277 if (!created)
1278 return ast_source->GetIDForModule(module);
1279
1280 return ast_source->RegisterModule(module);
1281 }
1282
CreateRecordType(clang::DeclContext * decl_ctx,OptionalClangModuleID owning_module,AccessType access_type,llvm::StringRef name,int kind,LanguageType language,ClangASTMetadata * metadata,bool exports_symbols)1283 CompilerType TypeSystemClang::CreateRecordType(
1284 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1285 AccessType access_type, llvm::StringRef name, int kind,
1286 LanguageType language, ClangASTMetadata *metadata, bool exports_symbols) {
1287 ASTContext &ast = getASTContext();
1288
1289 if (decl_ctx == nullptr)
1290 decl_ctx = ast.getTranslationUnitDecl();
1291
1292 if (language == eLanguageTypeObjC ||
1293 language == eLanguageTypeObjC_plus_plus) {
1294 bool isForwardDecl = true;
1295 bool isInternal = false;
1296 return CreateObjCClass(name, decl_ctx, owning_module, isForwardDecl,
1297 isInternal, metadata);
1298 }
1299
1300 // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1301 // we will need to update this code. I was told to currently always use the
1302 // CXXRecordDecl class since we often don't know from debug information if
1303 // something is struct or a class, so we default to always use the more
1304 // complete definition just in case.
1305
1306 bool has_name = !name.empty();
1307 CXXRecordDecl *decl = CXXRecordDecl::CreateDeserialized(ast, 0);
1308 decl->setTagKind(static_cast<TagDecl::TagKind>(kind));
1309 decl->setDeclContext(decl_ctx);
1310 if (has_name)
1311 decl->setDeclName(&ast.Idents.get(name));
1312 SetOwningModule(decl, owning_module);
1313
1314 if (!has_name) {
1315 // In C++ a lambda is also represented as an unnamed class. This is
1316 // different from an *anonymous class* that the user wrote:
1317 //
1318 // struct A {
1319 // // anonymous class (GNU/MSVC extension)
1320 // struct {
1321 // int x;
1322 // };
1323 // // unnamed class within a class
1324 // struct {
1325 // int y;
1326 // } B;
1327 // };
1328 //
1329 // void f() {
1330 // // unammed class outside of a class
1331 // struct {
1332 // int z;
1333 // } C;
1334 // }
1335 //
1336 // Anonymous classes is a GNU/MSVC extension that clang supports. It
1337 // requires the anonymous class be embedded within a class. So the new
1338 // heuristic verifies this condition.
1339 if (isa<CXXRecordDecl>(decl_ctx) && exports_symbols)
1340 decl->setAnonymousStructOrUnion(true);
1341 }
1342
1343 if (decl) {
1344 if (metadata)
1345 SetMetadata(decl, *metadata);
1346
1347 if (access_type != eAccessNone)
1348 decl->setAccess(ConvertAccessTypeToAccessSpecifier(access_type));
1349
1350 if (decl_ctx)
1351 decl_ctx->addDecl(decl);
1352
1353 return GetType(ast.getTagDeclType(decl));
1354 }
1355 return CompilerType();
1356 }
1357
1358 namespace {
IsValueParam(const clang::TemplateArgument & argument)1359 bool IsValueParam(const clang::TemplateArgument &argument) {
1360 return argument.getKind() == TemplateArgument::Integral;
1361 }
1362 }
1363
CreateTemplateParameterList(ASTContext & ast,const TypeSystemClang::TemplateParameterInfos & template_param_infos,llvm::SmallVector<NamedDecl *,8> & template_param_decls)1364 static TemplateParameterList *CreateTemplateParameterList(
1365 ASTContext &ast,
1366 const TypeSystemClang::TemplateParameterInfos &template_param_infos,
1367 llvm::SmallVector<NamedDecl *, 8> &template_param_decls) {
1368 const bool parameter_pack = false;
1369 const bool is_typename = false;
1370 const unsigned depth = 0;
1371 const size_t num_template_params = template_param_infos.args.size();
1372 DeclContext *const decl_context =
1373 ast.getTranslationUnitDecl(); // Is this the right decl context?,
1374 for (size_t i = 0; i < num_template_params; ++i) {
1375 const char *name = template_param_infos.names[i];
1376
1377 IdentifierInfo *identifier_info = nullptr;
1378 if (name && name[0])
1379 identifier_info = &ast.Idents.get(name);
1380 if (IsValueParam(template_param_infos.args[i])) {
1381 QualType template_param_type =
1382 template_param_infos.args[i].getIntegralType();
1383 template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1384 ast, decl_context, SourceLocation(), SourceLocation(), depth, i,
1385 identifier_info, template_param_type, parameter_pack,
1386 ast.getTrivialTypeSourceInfo(template_param_type)));
1387 } else {
1388 template_param_decls.push_back(TemplateTypeParmDecl::Create(
1389 ast, decl_context, SourceLocation(), SourceLocation(), depth, i,
1390 identifier_info, is_typename, parameter_pack));
1391 }
1392 }
1393
1394 if (template_param_infos.packed_args) {
1395 IdentifierInfo *identifier_info = nullptr;
1396 if (template_param_infos.pack_name && template_param_infos.pack_name[0])
1397 identifier_info = &ast.Idents.get(template_param_infos.pack_name);
1398 const bool parameter_pack_true = true;
1399
1400 if (!template_param_infos.packed_args->args.empty() &&
1401 IsValueParam(template_param_infos.packed_args->args[0])) {
1402 QualType template_param_type =
1403 template_param_infos.packed_args->args[0].getIntegralType();
1404 template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1405 ast, decl_context, SourceLocation(), SourceLocation(), depth,
1406 num_template_params, identifier_info, template_param_type,
1407 parameter_pack_true,
1408 ast.getTrivialTypeSourceInfo(template_param_type)));
1409 } else {
1410 template_param_decls.push_back(TemplateTypeParmDecl::Create(
1411 ast, decl_context, SourceLocation(), SourceLocation(), depth,
1412 num_template_params, identifier_info, is_typename,
1413 parameter_pack_true));
1414 }
1415 }
1416 clang::Expr *const requires_clause = nullptr; // TODO: Concepts
1417 TemplateParameterList *template_param_list = TemplateParameterList::Create(
1418 ast, SourceLocation(), SourceLocation(), template_param_decls,
1419 SourceLocation(), requires_clause);
1420 return template_param_list;
1421 }
1422
CreateFunctionTemplateDecl(clang::DeclContext * decl_ctx,OptionalClangModuleID owning_module,clang::FunctionDecl * func_decl,const TemplateParameterInfos & template_param_infos)1423 clang::FunctionTemplateDecl *TypeSystemClang::CreateFunctionTemplateDecl(
1424 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1425 clang::FunctionDecl *func_decl,
1426 const TemplateParameterInfos &template_param_infos) {
1427 // /// Create a function template node.
1428 ASTContext &ast = getASTContext();
1429
1430 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1431 TemplateParameterList *template_param_list = CreateTemplateParameterList(
1432 ast, template_param_infos, template_param_decls);
1433 FunctionTemplateDecl *func_tmpl_decl =
1434 FunctionTemplateDecl::CreateDeserialized(ast, 0);
1435 func_tmpl_decl->setDeclContext(decl_ctx);
1436 func_tmpl_decl->setLocation(func_decl->getLocation());
1437 func_tmpl_decl->setDeclName(func_decl->getDeclName());
1438 func_tmpl_decl->init(func_decl, template_param_list);
1439 SetOwningModule(func_tmpl_decl, owning_module);
1440
1441 for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1442 i < template_param_decl_count; ++i) {
1443 // TODO: verify which decl context we should put template_param_decls into..
1444 template_param_decls[i]->setDeclContext(func_decl);
1445 }
1446 // Function templates inside a record need to have an access specifier.
1447 // It doesn't matter what access specifier we give the template as LLDB
1448 // anyway allows accessing everything inside a record.
1449 if (decl_ctx->isRecord())
1450 func_tmpl_decl->setAccess(clang::AccessSpecifier::AS_public);
1451
1452 return func_tmpl_decl;
1453 }
1454
CreateFunctionTemplateSpecializationInfo(FunctionDecl * func_decl,clang::FunctionTemplateDecl * func_tmpl_decl,const TemplateParameterInfos & infos)1455 void TypeSystemClang::CreateFunctionTemplateSpecializationInfo(
1456 FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl,
1457 const TemplateParameterInfos &infos) {
1458 TemplateArgumentList *template_args_ptr =
1459 TemplateArgumentList::CreateCopy(func_decl->getASTContext(), infos.args);
1460
1461 func_decl->setFunctionTemplateSpecialization(func_tmpl_decl,
1462 template_args_ptr, nullptr);
1463 }
1464
CreateClassTemplateDecl(DeclContext * decl_ctx,OptionalClangModuleID owning_module,lldb::AccessType access_type,const char * class_name,int kind,const TemplateParameterInfos & template_param_infos)1465 ClassTemplateDecl *TypeSystemClang::CreateClassTemplateDecl(
1466 DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1467 lldb::AccessType access_type, const char *class_name, int kind,
1468 const TemplateParameterInfos &template_param_infos) {
1469 ASTContext &ast = getASTContext();
1470
1471 ClassTemplateDecl *class_template_decl = nullptr;
1472 if (decl_ctx == nullptr)
1473 decl_ctx = ast.getTranslationUnitDecl();
1474
1475 IdentifierInfo &identifier_info = ast.Idents.get(class_name);
1476 DeclarationName decl_name(&identifier_info);
1477
1478 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1479
1480 for (NamedDecl *decl : result) {
1481 class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1482 if (class_template_decl)
1483 return class_template_decl;
1484 }
1485
1486 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1487
1488 TemplateParameterList *template_param_list = CreateTemplateParameterList(
1489 ast, template_param_infos, template_param_decls);
1490
1491 CXXRecordDecl *template_cxx_decl = CXXRecordDecl::CreateDeserialized(ast, 0);
1492 template_cxx_decl->setTagKind(static_cast<TagDecl::TagKind>(kind));
1493 // What decl context do we use here? TU? The actual decl context?
1494 template_cxx_decl->setDeclContext(decl_ctx);
1495 template_cxx_decl->setDeclName(decl_name);
1496 SetOwningModule(template_cxx_decl, owning_module);
1497
1498 for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1499 i < template_param_decl_count; ++i) {
1500 template_param_decls[i]->setDeclContext(template_cxx_decl);
1501 }
1502
1503 // With templated classes, we say that a class is templated with
1504 // specializations, but that the bare class has no functions.
1505 // template_cxx_decl->startDefinition();
1506 // template_cxx_decl->completeDefinition();
1507
1508 class_template_decl = ClassTemplateDecl::CreateDeserialized(ast, 0);
1509 // What decl context do we use here? TU? The actual decl context?
1510 class_template_decl->setDeclContext(decl_ctx);
1511 class_template_decl->setDeclName(decl_name);
1512 class_template_decl->init(template_cxx_decl, template_param_list);
1513 template_cxx_decl->setDescribedClassTemplate(class_template_decl);
1514 SetOwningModule(class_template_decl, owning_module);
1515
1516 if (class_template_decl) {
1517 if (access_type != eAccessNone)
1518 class_template_decl->setAccess(
1519 ConvertAccessTypeToAccessSpecifier(access_type));
1520
1521 decl_ctx->addDecl(class_template_decl);
1522
1523 VerifyDecl(class_template_decl);
1524 }
1525
1526 return class_template_decl;
1527 }
1528
1529 TemplateTemplateParmDecl *
CreateTemplateTemplateParmDecl(const char * template_name)1530 TypeSystemClang::CreateTemplateTemplateParmDecl(const char *template_name) {
1531 ASTContext &ast = getASTContext();
1532
1533 auto *decl_ctx = ast.getTranslationUnitDecl();
1534
1535 IdentifierInfo &identifier_info = ast.Idents.get(template_name);
1536 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1537
1538 TypeSystemClang::TemplateParameterInfos template_param_infos;
1539 TemplateParameterList *template_param_list = CreateTemplateParameterList(
1540 ast, template_param_infos, template_param_decls);
1541
1542 // LLDB needs to create those decls only to be able to display a
1543 // type that includes a template template argument. Only the name matters for
1544 // this purpose, so we use dummy values for the other characteristics of the
1545 // type.
1546 return TemplateTemplateParmDecl::Create(
1547 ast, decl_ctx, SourceLocation(),
1548 /*Depth*/ 0, /*Position*/ 0,
1549 /*IsParameterPack*/ false, &identifier_info, template_param_list);
1550 }
1551
1552 ClassTemplateSpecializationDecl *
CreateClassTemplateSpecializationDecl(DeclContext * decl_ctx,OptionalClangModuleID owning_module,ClassTemplateDecl * class_template_decl,int kind,const TemplateParameterInfos & template_param_infos)1553 TypeSystemClang::CreateClassTemplateSpecializationDecl(
1554 DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1555 ClassTemplateDecl *class_template_decl, int kind,
1556 const TemplateParameterInfos &template_param_infos) {
1557 ASTContext &ast = getASTContext();
1558 llvm::SmallVector<clang::TemplateArgument, 2> args(
1559 template_param_infos.args.size() +
1560 (template_param_infos.packed_args ? 1 : 0));
1561 std::copy(template_param_infos.args.begin(), template_param_infos.args.end(),
1562 args.begin());
1563 if (template_param_infos.packed_args) {
1564 args[args.size() - 1] = TemplateArgument::CreatePackCopy(
1565 ast, template_param_infos.packed_args->args);
1566 }
1567 ClassTemplateSpecializationDecl *class_template_specialization_decl =
1568 ClassTemplateSpecializationDecl::CreateDeserialized(ast, 0);
1569 class_template_specialization_decl->setTagKind(
1570 static_cast<TagDecl::TagKind>(kind));
1571 class_template_specialization_decl->setDeclContext(decl_ctx);
1572 class_template_specialization_decl->setInstantiationOf(class_template_decl);
1573 class_template_specialization_decl->setTemplateArgs(
1574 TemplateArgumentList::CreateCopy(ast, args));
1575 ast.getTypeDeclType(class_template_specialization_decl, nullptr);
1576 class_template_specialization_decl->setDeclName(
1577 class_template_decl->getDeclName());
1578 SetOwningModule(class_template_specialization_decl, owning_module);
1579 decl_ctx->addDecl(class_template_specialization_decl);
1580
1581 class_template_specialization_decl->setSpecializationKind(
1582 TSK_ExplicitSpecialization);
1583
1584 return class_template_specialization_decl;
1585 }
1586
CreateClassTemplateSpecializationType(ClassTemplateSpecializationDecl * class_template_specialization_decl)1587 CompilerType TypeSystemClang::CreateClassTemplateSpecializationType(
1588 ClassTemplateSpecializationDecl *class_template_specialization_decl) {
1589 if (class_template_specialization_decl) {
1590 ASTContext &ast = getASTContext();
1591 return GetType(ast.getTagDeclType(class_template_specialization_decl));
1592 }
1593 return CompilerType();
1594 }
1595
check_op_param(bool is_method,clang::OverloadedOperatorKind op_kind,bool unary,bool binary,uint32_t num_params)1596 static inline bool check_op_param(bool is_method,
1597 clang::OverloadedOperatorKind op_kind,
1598 bool unary, bool binary,
1599 uint32_t num_params) {
1600 // Special-case call since it can take any number of operands
1601 if (op_kind == OO_Call)
1602 return true;
1603
1604 // The parameter count doesn't include "this"
1605 if (is_method)
1606 ++num_params;
1607 if (num_params == 1)
1608 return unary;
1609 if (num_params == 2)
1610 return binary;
1611 else
1612 return false;
1613 }
1614
CheckOverloadedOperatorKindParameterCount(bool is_method,clang::OverloadedOperatorKind op_kind,uint32_t num_params)1615 bool TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
1616 bool is_method, clang::OverloadedOperatorKind op_kind,
1617 uint32_t num_params) {
1618 switch (op_kind) {
1619 default:
1620 break;
1621 // C++ standard allows any number of arguments to new/delete
1622 case OO_New:
1623 case OO_Array_New:
1624 case OO_Delete:
1625 case OO_Array_Delete:
1626 return true;
1627 }
1628
1629 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
1630 case OO_##Name: \
1631 return check_op_param(is_method, op_kind, Unary, Binary, num_params);
1632 switch (op_kind) {
1633 #include "clang/Basic/OperatorKinds.def"
1634 default:
1635 break;
1636 }
1637 return false;
1638 }
1639
1640 clang::AccessSpecifier
UnifyAccessSpecifiers(clang::AccessSpecifier lhs,clang::AccessSpecifier rhs)1641 TypeSystemClang::UnifyAccessSpecifiers(clang::AccessSpecifier lhs,
1642 clang::AccessSpecifier rhs) {
1643 // Make the access equal to the stricter of the field and the nested field's
1644 // access
1645 if (lhs == AS_none || rhs == AS_none)
1646 return AS_none;
1647 if (lhs == AS_private || rhs == AS_private)
1648 return AS_private;
1649 if (lhs == AS_protected || rhs == AS_protected)
1650 return AS_protected;
1651 return AS_public;
1652 }
1653
FieldIsBitfield(FieldDecl * field,uint32_t & bitfield_bit_size)1654 bool TypeSystemClang::FieldIsBitfield(FieldDecl *field,
1655 uint32_t &bitfield_bit_size) {
1656 ASTContext &ast = getASTContext();
1657 if (field == nullptr)
1658 return false;
1659
1660 if (field->isBitField()) {
1661 Expr *bit_width_expr = field->getBitWidth();
1662 if (bit_width_expr) {
1663 if (Optional<llvm::APSInt> bit_width_apsint =
1664 bit_width_expr->getIntegerConstantExpr(ast)) {
1665 bitfield_bit_size = bit_width_apsint->getLimitedValue(UINT32_MAX);
1666 return true;
1667 }
1668 }
1669 }
1670 return false;
1671 }
1672
RecordHasFields(const RecordDecl * record_decl)1673 bool TypeSystemClang::RecordHasFields(const RecordDecl *record_decl) {
1674 if (record_decl == nullptr)
1675 return false;
1676
1677 if (!record_decl->field_empty())
1678 return true;
1679
1680 // No fields, lets check this is a CXX record and check the base classes
1681 const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1682 if (cxx_record_decl) {
1683 CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1684 for (base_class = cxx_record_decl->bases_begin(),
1685 base_class_end = cxx_record_decl->bases_end();
1686 base_class != base_class_end; ++base_class) {
1687 const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(
1688 base_class->getType()->getAs<RecordType>()->getDecl());
1689 if (RecordHasFields(base_class_decl))
1690 return true;
1691 }
1692 }
1693 return false;
1694 }
1695
1696 #pragma mark Objective-C Classes
1697
CreateObjCClass(llvm::StringRef name,clang::DeclContext * decl_ctx,OptionalClangModuleID owning_module,bool isForwardDecl,bool isInternal,ClangASTMetadata * metadata)1698 CompilerType TypeSystemClang::CreateObjCClass(
1699 llvm::StringRef name, clang::DeclContext *decl_ctx,
1700 OptionalClangModuleID owning_module, bool isForwardDecl, bool isInternal,
1701 ClangASTMetadata *metadata) {
1702 ASTContext &ast = getASTContext();
1703 assert(!name.empty());
1704 if (!decl_ctx)
1705 decl_ctx = ast.getTranslationUnitDecl();
1706
1707 ObjCInterfaceDecl *decl = ObjCInterfaceDecl::CreateDeserialized(ast, 0);
1708 decl->setDeclContext(decl_ctx);
1709 decl->setDeclName(&ast.Idents.get(name));
1710 /*isForwardDecl,*/
1711 decl->setImplicit(isInternal);
1712 SetOwningModule(decl, owning_module);
1713
1714 if (decl && metadata)
1715 SetMetadata(decl, *metadata);
1716
1717 return GetType(ast.getObjCInterfaceType(decl));
1718 }
1719
BaseSpecifierIsEmpty(const CXXBaseSpecifier * b)1720 static inline bool BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) {
1721 return !TypeSystemClang::RecordHasFields(b->getType()->getAsCXXRecordDecl());
1722 }
1723
1724 uint32_t
GetNumBaseClasses(const CXXRecordDecl * cxx_record_decl,bool omit_empty_base_classes)1725 TypeSystemClang::GetNumBaseClasses(const CXXRecordDecl *cxx_record_decl,
1726 bool omit_empty_base_classes) {
1727 uint32_t num_bases = 0;
1728 if (cxx_record_decl) {
1729 if (omit_empty_base_classes) {
1730 CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1731 for (base_class = cxx_record_decl->bases_begin(),
1732 base_class_end = cxx_record_decl->bases_end();
1733 base_class != base_class_end; ++base_class) {
1734 // Skip empty base classes
1735 if (BaseSpecifierIsEmpty(base_class))
1736 continue;
1737 ++num_bases;
1738 }
1739 } else
1740 num_bases = cxx_record_decl->getNumBases();
1741 }
1742 return num_bases;
1743 }
1744
1745 #pragma mark Namespace Declarations
1746
GetUniqueNamespaceDeclaration(const char * name,clang::DeclContext * decl_ctx,OptionalClangModuleID owning_module,bool is_inline)1747 NamespaceDecl *TypeSystemClang::GetUniqueNamespaceDeclaration(
1748 const char *name, clang::DeclContext *decl_ctx,
1749 OptionalClangModuleID owning_module, bool is_inline) {
1750 NamespaceDecl *namespace_decl = nullptr;
1751 ASTContext &ast = getASTContext();
1752 TranslationUnitDecl *translation_unit_decl = ast.getTranslationUnitDecl();
1753 if (!decl_ctx)
1754 decl_ctx = translation_unit_decl;
1755
1756 if (name) {
1757 IdentifierInfo &identifier_info = ast.Idents.get(name);
1758 DeclarationName decl_name(&identifier_info);
1759 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1760 for (NamedDecl *decl : result) {
1761 namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
1762 if (namespace_decl)
1763 return namespace_decl;
1764 }
1765
1766 namespace_decl =
1767 NamespaceDecl::Create(ast, decl_ctx, is_inline, SourceLocation(),
1768 SourceLocation(), &identifier_info, nullptr);
1769
1770 decl_ctx->addDecl(namespace_decl);
1771 } else {
1772 if (decl_ctx == translation_unit_decl) {
1773 namespace_decl = translation_unit_decl->getAnonymousNamespace();
1774 if (namespace_decl)
1775 return namespace_decl;
1776
1777 namespace_decl =
1778 NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(),
1779 SourceLocation(), nullptr, nullptr);
1780 translation_unit_decl->setAnonymousNamespace(namespace_decl);
1781 translation_unit_decl->addDecl(namespace_decl);
1782 assert(namespace_decl == translation_unit_decl->getAnonymousNamespace());
1783 } else {
1784 NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
1785 if (parent_namespace_decl) {
1786 namespace_decl = parent_namespace_decl->getAnonymousNamespace();
1787 if (namespace_decl)
1788 return namespace_decl;
1789 namespace_decl =
1790 NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(),
1791 SourceLocation(), nullptr, nullptr);
1792 parent_namespace_decl->setAnonymousNamespace(namespace_decl);
1793 parent_namespace_decl->addDecl(namespace_decl);
1794 assert(namespace_decl ==
1795 parent_namespace_decl->getAnonymousNamespace());
1796 } else {
1797 assert(false && "GetUniqueNamespaceDeclaration called with no name and "
1798 "no namespace as decl_ctx");
1799 }
1800 }
1801 }
1802 // Note: namespaces can span multiple modules, so perhaps this isn't a good
1803 // idea.
1804 SetOwningModule(namespace_decl, owning_module);
1805
1806 VerifyDecl(namespace_decl);
1807 return namespace_decl;
1808 }
1809
1810 clang::BlockDecl *
CreateBlockDeclaration(clang::DeclContext * ctx,OptionalClangModuleID owning_module)1811 TypeSystemClang::CreateBlockDeclaration(clang::DeclContext *ctx,
1812 OptionalClangModuleID owning_module) {
1813 if (ctx) {
1814 clang::BlockDecl *decl =
1815 clang::BlockDecl::CreateDeserialized(getASTContext(), 0);
1816 decl->setDeclContext(ctx);
1817 ctx->addDecl(decl);
1818 SetOwningModule(decl, owning_module);
1819 return decl;
1820 }
1821 return nullptr;
1822 }
1823
FindLCABetweenDecls(clang::DeclContext * left,clang::DeclContext * right,clang::DeclContext * root)1824 clang::DeclContext *FindLCABetweenDecls(clang::DeclContext *left,
1825 clang::DeclContext *right,
1826 clang::DeclContext *root) {
1827 if (root == nullptr)
1828 return nullptr;
1829
1830 std::set<clang::DeclContext *> path_left;
1831 for (clang::DeclContext *d = left; d != nullptr; d = d->getParent())
1832 path_left.insert(d);
1833
1834 for (clang::DeclContext *d = right; d != nullptr; d = d->getParent())
1835 if (path_left.find(d) != path_left.end())
1836 return d;
1837
1838 return nullptr;
1839 }
1840
CreateUsingDirectiveDeclaration(clang::DeclContext * decl_ctx,OptionalClangModuleID owning_module,clang::NamespaceDecl * ns_decl)1841 clang::UsingDirectiveDecl *TypeSystemClang::CreateUsingDirectiveDeclaration(
1842 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1843 clang::NamespaceDecl *ns_decl) {
1844 if (decl_ctx && ns_decl) {
1845 auto *translation_unit = getASTContext().getTranslationUnitDecl();
1846 clang::UsingDirectiveDecl *using_decl = clang::UsingDirectiveDecl::Create(
1847 getASTContext(), decl_ctx, clang::SourceLocation(),
1848 clang::SourceLocation(), clang::NestedNameSpecifierLoc(),
1849 clang::SourceLocation(), ns_decl,
1850 FindLCABetweenDecls(decl_ctx, ns_decl,
1851 translation_unit));
1852 decl_ctx->addDecl(using_decl);
1853 SetOwningModule(using_decl, owning_module);
1854 return using_decl;
1855 }
1856 return nullptr;
1857 }
1858
1859 clang::UsingDecl *
CreateUsingDeclaration(clang::DeclContext * current_decl_ctx,OptionalClangModuleID owning_module,clang::NamedDecl * target)1860 TypeSystemClang::CreateUsingDeclaration(clang::DeclContext *current_decl_ctx,
1861 OptionalClangModuleID owning_module,
1862 clang::NamedDecl *target) {
1863 if (current_decl_ctx && target) {
1864 clang::UsingDecl *using_decl = clang::UsingDecl::Create(
1865 getASTContext(), current_decl_ctx, clang::SourceLocation(),
1866 clang::NestedNameSpecifierLoc(), clang::DeclarationNameInfo(), false);
1867 SetOwningModule(using_decl, owning_module);
1868 clang::UsingShadowDecl *shadow_decl = clang::UsingShadowDecl::Create(
1869 getASTContext(), current_decl_ctx, clang::SourceLocation(), using_decl,
1870 target);
1871 SetOwningModule(shadow_decl, owning_module);
1872 using_decl->addShadowDecl(shadow_decl);
1873 current_decl_ctx->addDecl(using_decl);
1874 return using_decl;
1875 }
1876 return nullptr;
1877 }
1878
CreateVariableDeclaration(clang::DeclContext * decl_context,OptionalClangModuleID owning_module,const char * name,clang::QualType type)1879 clang::VarDecl *TypeSystemClang::CreateVariableDeclaration(
1880 clang::DeclContext *decl_context, OptionalClangModuleID owning_module,
1881 const char *name, clang::QualType type) {
1882 if (decl_context) {
1883 clang::VarDecl *var_decl =
1884 clang::VarDecl::CreateDeserialized(getASTContext(), 0);
1885 var_decl->setDeclContext(decl_context);
1886 if (name && name[0])
1887 var_decl->setDeclName(&getASTContext().Idents.getOwn(name));
1888 var_decl->setType(type);
1889 SetOwningModule(var_decl, owning_module);
1890 var_decl->setAccess(clang::AS_public);
1891 decl_context->addDecl(var_decl);
1892 return var_decl;
1893 }
1894 return nullptr;
1895 }
1896
1897 lldb::opaque_compiler_type_t
GetOpaqueCompilerType(clang::ASTContext * ast,lldb::BasicType basic_type)1898 TypeSystemClang::GetOpaqueCompilerType(clang::ASTContext *ast,
1899 lldb::BasicType basic_type) {
1900 switch (basic_type) {
1901 case eBasicTypeVoid:
1902 return ast->VoidTy.getAsOpaquePtr();
1903 case eBasicTypeChar:
1904 return ast->CharTy.getAsOpaquePtr();
1905 case eBasicTypeSignedChar:
1906 return ast->SignedCharTy.getAsOpaquePtr();
1907 case eBasicTypeUnsignedChar:
1908 return ast->UnsignedCharTy.getAsOpaquePtr();
1909 case eBasicTypeWChar:
1910 return ast->getWCharType().getAsOpaquePtr();
1911 case eBasicTypeSignedWChar:
1912 return ast->getSignedWCharType().getAsOpaquePtr();
1913 case eBasicTypeUnsignedWChar:
1914 return ast->getUnsignedWCharType().getAsOpaquePtr();
1915 case eBasicTypeChar16:
1916 return ast->Char16Ty.getAsOpaquePtr();
1917 case eBasicTypeChar32:
1918 return ast->Char32Ty.getAsOpaquePtr();
1919 case eBasicTypeShort:
1920 return ast->ShortTy.getAsOpaquePtr();
1921 case eBasicTypeUnsignedShort:
1922 return ast->UnsignedShortTy.getAsOpaquePtr();
1923 case eBasicTypeInt:
1924 return ast->IntTy.getAsOpaquePtr();
1925 case eBasicTypeUnsignedInt:
1926 return ast->UnsignedIntTy.getAsOpaquePtr();
1927 case eBasicTypeLong:
1928 return ast->LongTy.getAsOpaquePtr();
1929 case eBasicTypeUnsignedLong:
1930 return ast->UnsignedLongTy.getAsOpaquePtr();
1931 case eBasicTypeLongLong:
1932 return ast->LongLongTy.getAsOpaquePtr();
1933 case eBasicTypeUnsignedLongLong:
1934 return ast->UnsignedLongLongTy.getAsOpaquePtr();
1935 case eBasicTypeInt128:
1936 return ast->Int128Ty.getAsOpaquePtr();
1937 case eBasicTypeUnsignedInt128:
1938 return ast->UnsignedInt128Ty.getAsOpaquePtr();
1939 case eBasicTypeBool:
1940 return ast->BoolTy.getAsOpaquePtr();
1941 case eBasicTypeHalf:
1942 return ast->HalfTy.getAsOpaquePtr();
1943 case eBasicTypeFloat:
1944 return ast->FloatTy.getAsOpaquePtr();
1945 case eBasicTypeDouble:
1946 return ast->DoubleTy.getAsOpaquePtr();
1947 case eBasicTypeLongDouble:
1948 return ast->LongDoubleTy.getAsOpaquePtr();
1949 case eBasicTypeFloatComplex:
1950 return ast->FloatComplexTy.getAsOpaquePtr();
1951 case eBasicTypeDoubleComplex:
1952 return ast->DoubleComplexTy.getAsOpaquePtr();
1953 case eBasicTypeLongDoubleComplex:
1954 return ast->LongDoubleComplexTy.getAsOpaquePtr();
1955 case eBasicTypeObjCID:
1956 return ast->getObjCIdType().getAsOpaquePtr();
1957 case eBasicTypeObjCClass:
1958 return ast->getObjCClassType().getAsOpaquePtr();
1959 case eBasicTypeObjCSel:
1960 return ast->getObjCSelType().getAsOpaquePtr();
1961 case eBasicTypeNullPtr:
1962 return ast->NullPtrTy.getAsOpaquePtr();
1963 default:
1964 return nullptr;
1965 }
1966 }
1967
1968 #pragma mark Function Types
1969
1970 clang::DeclarationName
GetDeclarationName(llvm::StringRef name,const CompilerType & function_clang_type)1971 TypeSystemClang::GetDeclarationName(llvm::StringRef name,
1972 const CompilerType &function_clang_type) {
1973 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
1974 if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS)
1975 return DeclarationName(&getASTContext().Idents.get(
1976 name)); // Not operator, but a regular function.
1977
1978 // Check the number of operator parameters. Sometimes we have seen bad DWARF
1979 // that doesn't correctly describe operators and if we try to create a method
1980 // and add it to the class, clang will assert and crash, so we need to make
1981 // sure things are acceptable.
1982 clang::QualType method_qual_type(ClangUtil::GetQualType(function_clang_type));
1983 const clang::FunctionProtoType *function_type =
1984 llvm::dyn_cast<clang::FunctionProtoType>(method_qual_type.getTypePtr());
1985 if (function_type == nullptr)
1986 return clang::DeclarationName();
1987
1988 const bool is_method = false;
1989 const unsigned int num_params = function_type->getNumParams();
1990 if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
1991 is_method, op_kind, num_params))
1992 return clang::DeclarationName();
1993
1994 return getASTContext().DeclarationNames.getCXXOperatorName(op_kind);
1995 }
1996
GetTypePrintingPolicy()1997 PrintingPolicy TypeSystemClang::GetTypePrintingPolicy() {
1998 clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy());
1999 printing_policy.SuppressTagKeyword = true;
2000 // Inline namespaces are important for some type formatters (e.g., libc++
2001 // and libstdc++ are differentiated by their inline namespaces).
2002 printing_policy.SuppressInlineNamespace = false;
2003 printing_policy.SuppressUnwrittenScope = false;
2004 // Default arguments are also always important for type formatters. Otherwise
2005 // we would need to always specify two type names for the setups where we do
2006 // know the default arguments and where we don't know default arguments.
2007 //
2008 // For example, without this we would need to have formatters for both:
2009 // std::basic_string<char>
2010 // and
2011 // std::basic_string<char, std::char_traits<char>, std::allocator<char> >
2012 // to support setups where LLDB was able to reconstruct default arguments
2013 // (and we then would have suppressed them from the type name) and also setups
2014 // where LLDB wasn't able to reconstruct the default arguments.
2015 printing_policy.SuppressDefaultTemplateArgs = false;
2016 return printing_policy;
2017 }
2018
GetTypeNameForDecl(const NamedDecl * named_decl)2019 std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl) {
2020 clang::PrintingPolicy printing_policy = GetTypePrintingPolicy();
2021 std::string result;
2022 llvm::raw_string_ostream os(result);
2023 named_decl->printQualifiedName(os, printing_policy);
2024 return result;
2025 }
2026
CreateFunctionDeclaration(clang::DeclContext * decl_ctx,OptionalClangModuleID owning_module,llvm::StringRef name,const CompilerType & function_clang_type,clang::StorageClass storage,bool is_inline)2027 FunctionDecl *TypeSystemClang::CreateFunctionDeclaration(
2028 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2029 llvm::StringRef name, const CompilerType &function_clang_type,
2030 clang::StorageClass storage, bool is_inline) {
2031 FunctionDecl *func_decl = nullptr;
2032 ASTContext &ast = getASTContext();
2033 if (!decl_ctx)
2034 decl_ctx = ast.getTranslationUnitDecl();
2035
2036 const bool hasWrittenPrototype = true;
2037 const bool isConstexprSpecified = false;
2038
2039 clang::DeclarationName declarationName =
2040 GetDeclarationName(name, function_clang_type);
2041 func_decl = FunctionDecl::CreateDeserialized(ast, 0);
2042 func_decl->setDeclContext(decl_ctx);
2043 func_decl->setDeclName(declarationName);
2044 func_decl->setType(ClangUtil::GetQualType(function_clang_type));
2045 func_decl->setStorageClass(storage);
2046 func_decl->setInlineSpecified(is_inline);
2047 func_decl->setHasWrittenPrototype(hasWrittenPrototype);
2048 func_decl->setConstexprKind(isConstexprSpecified
2049 ? ConstexprSpecKind::Constexpr
2050 : ConstexprSpecKind::Unspecified);
2051 SetOwningModule(func_decl, owning_module);
2052 if (func_decl)
2053 decl_ctx->addDecl(func_decl);
2054
2055 VerifyDecl(func_decl);
2056
2057 return func_decl;
2058 }
2059
2060 CompilerType
CreateFunctionType(const CompilerType & result_type,const CompilerType * args,unsigned num_args,bool is_variadic,unsigned type_quals,clang::CallingConv cc)2061 TypeSystemClang::CreateFunctionType(const CompilerType &result_type,
2062 const CompilerType *args, unsigned num_args,
2063 bool is_variadic, unsigned type_quals,
2064 clang::CallingConv cc) {
2065 if (!result_type || !ClangUtil::IsClangType(result_type))
2066 return CompilerType(); // invalid return type
2067
2068 std::vector<QualType> qual_type_args;
2069 if (num_args > 0 && args == nullptr)
2070 return CompilerType(); // invalid argument array passed in
2071
2072 // Verify that all arguments are valid and the right type
2073 for (unsigned i = 0; i < num_args; ++i) {
2074 if (args[i]) {
2075 // Make sure we have a clang type in args[i] and not a type from another
2076 // language whose name might match
2077 const bool is_clang_type = ClangUtil::IsClangType(args[i]);
2078 lldbassert(is_clang_type);
2079 if (is_clang_type)
2080 qual_type_args.push_back(ClangUtil::GetQualType(args[i]));
2081 else
2082 return CompilerType(); // invalid argument type (must be a clang type)
2083 } else
2084 return CompilerType(); // invalid argument type (empty)
2085 }
2086
2087 // TODO: Detect calling convention in DWARF?
2088 FunctionProtoType::ExtProtoInfo proto_info;
2089 proto_info.ExtInfo = cc;
2090 proto_info.Variadic = is_variadic;
2091 proto_info.ExceptionSpec = EST_None;
2092 proto_info.TypeQuals = clang::Qualifiers::fromFastMask(type_quals);
2093 proto_info.RefQualifier = RQ_None;
2094
2095 return GetType(getASTContext().getFunctionType(
2096 ClangUtil::GetQualType(result_type), qual_type_args, proto_info));
2097 }
2098
CreateParameterDeclaration(clang::DeclContext * decl_ctx,OptionalClangModuleID owning_module,const char * name,const CompilerType & param_type,int storage,bool add_decl)2099 ParmVarDecl *TypeSystemClang::CreateParameterDeclaration(
2100 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2101 const char *name, const CompilerType ¶m_type, int storage,
2102 bool add_decl) {
2103 ASTContext &ast = getASTContext();
2104 auto *decl = ParmVarDecl::CreateDeserialized(ast, 0);
2105 decl->setDeclContext(decl_ctx);
2106 if (name && name[0])
2107 decl->setDeclName(&ast.Idents.get(name));
2108 decl->setType(ClangUtil::GetQualType(param_type));
2109 decl->setStorageClass(static_cast<clang::StorageClass>(storage));
2110 SetOwningModule(decl, owning_module);
2111 if (add_decl)
2112 decl_ctx->addDecl(decl);
2113
2114 return decl;
2115 }
2116
SetFunctionParameters(FunctionDecl * function_decl,ParmVarDecl ** params,unsigned num_params)2117 void TypeSystemClang::SetFunctionParameters(FunctionDecl *function_decl,
2118 ParmVarDecl **params,
2119 unsigned num_params) {
2120 if (function_decl)
2121 function_decl->setParams(ArrayRef<ParmVarDecl *>(params, num_params));
2122 }
2123
2124 CompilerType
CreateBlockPointerType(const CompilerType & function_type)2125 TypeSystemClang::CreateBlockPointerType(const CompilerType &function_type) {
2126 QualType block_type = m_ast_up->getBlockPointerType(
2127 clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType()));
2128
2129 return GetType(block_type);
2130 }
2131
2132 #pragma mark Array Types
2133
CreateArrayType(const CompilerType & element_type,size_t element_count,bool is_vector)2134 CompilerType TypeSystemClang::CreateArrayType(const CompilerType &element_type,
2135 size_t element_count,
2136 bool is_vector) {
2137 if (element_type.IsValid()) {
2138 ASTContext &ast = getASTContext();
2139
2140 if (is_vector) {
2141 return GetType(ast.getExtVectorType(ClangUtil::GetQualType(element_type),
2142 element_count));
2143 } else {
2144
2145 llvm::APInt ap_element_count(64, element_count);
2146 if (element_count == 0) {
2147 return GetType(ast.getIncompleteArrayType(
2148 ClangUtil::GetQualType(element_type), clang::ArrayType::Normal, 0));
2149 } else {
2150 return GetType(ast.getConstantArrayType(
2151 ClangUtil::GetQualType(element_type), ap_element_count, nullptr,
2152 clang::ArrayType::Normal, 0));
2153 }
2154 }
2155 }
2156 return CompilerType();
2157 }
2158
CreateStructForIdentifier(ConstString type_name,const std::initializer_list<std::pair<const char *,CompilerType>> & type_fields,bool packed)2159 CompilerType TypeSystemClang::CreateStructForIdentifier(
2160 ConstString type_name,
2161 const std::initializer_list<std::pair<const char *, CompilerType>>
2162 &type_fields,
2163 bool packed) {
2164 CompilerType type;
2165 if (!type_name.IsEmpty() &&
2166 (type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name))
2167 .IsValid()) {
2168 lldbassert(0 && "Trying to create a type for an existing name");
2169 return type;
2170 }
2171
2172 type = CreateRecordType(nullptr, OptionalClangModuleID(), lldb::eAccessPublic,
2173 type_name.GetCString(), clang::TTK_Struct,
2174 lldb::eLanguageTypeC);
2175 StartTagDeclarationDefinition(type);
2176 for (const auto &field : type_fields)
2177 AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic,
2178 0);
2179 if (packed)
2180 SetIsPacked(type);
2181 CompleteTagDeclarationDefinition(type);
2182 return type;
2183 }
2184
GetOrCreateStructForIdentifier(ConstString type_name,const std::initializer_list<std::pair<const char *,CompilerType>> & type_fields,bool packed)2185 CompilerType TypeSystemClang::GetOrCreateStructForIdentifier(
2186 ConstString type_name,
2187 const std::initializer_list<std::pair<const char *, CompilerType>>
2188 &type_fields,
2189 bool packed) {
2190 CompilerType type;
2191 if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid())
2192 return type;
2193
2194 return CreateStructForIdentifier(type_name, type_fields, packed);
2195 }
2196
2197 #pragma mark Enumeration Types
2198
CreateEnumerationType(const char * name,clang::DeclContext * decl_ctx,OptionalClangModuleID owning_module,const Declaration & decl,const CompilerType & integer_clang_type,bool is_scoped)2199 CompilerType TypeSystemClang::CreateEnumerationType(
2200 const char *name, clang::DeclContext *decl_ctx,
2201 OptionalClangModuleID owning_module, const Declaration &decl,
2202 const CompilerType &integer_clang_type, bool is_scoped) {
2203 // TODO: Do something intelligent with the Declaration object passed in
2204 // like maybe filling in the SourceLocation with it...
2205 ASTContext &ast = getASTContext();
2206
2207 // TODO: ask about these...
2208 // const bool IsFixed = false;
2209 EnumDecl *enum_decl = EnumDecl::CreateDeserialized(ast, 0);
2210 enum_decl->setDeclContext(decl_ctx);
2211 if (name && name[0])
2212 enum_decl->setDeclName(&ast.Idents.get(name));
2213 enum_decl->setScoped(is_scoped);
2214 enum_decl->setScopedUsingClassTag(is_scoped);
2215 enum_decl->setFixed(false);
2216 SetOwningModule(enum_decl, owning_module);
2217 if (enum_decl) {
2218 if (decl_ctx)
2219 decl_ctx->addDecl(enum_decl);
2220
2221 // TODO: check if we should be setting the promotion type too?
2222 enum_decl->setIntegerType(ClangUtil::GetQualType(integer_clang_type));
2223
2224 enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
2225
2226 return GetType(ast.getTagDeclType(enum_decl));
2227 }
2228 return CompilerType();
2229 }
2230
GetIntTypeFromBitSize(size_t bit_size,bool is_signed)2231 CompilerType TypeSystemClang::GetIntTypeFromBitSize(size_t bit_size,
2232 bool is_signed) {
2233 clang::ASTContext &ast = getASTContext();
2234
2235 if (is_signed) {
2236 if (bit_size == ast.getTypeSize(ast.SignedCharTy))
2237 return GetType(ast.SignedCharTy);
2238
2239 if (bit_size == ast.getTypeSize(ast.ShortTy))
2240 return GetType(ast.ShortTy);
2241
2242 if (bit_size == ast.getTypeSize(ast.IntTy))
2243 return GetType(ast.IntTy);
2244
2245 if (bit_size == ast.getTypeSize(ast.LongTy))
2246 return GetType(ast.LongTy);
2247
2248 if (bit_size == ast.getTypeSize(ast.LongLongTy))
2249 return GetType(ast.LongLongTy);
2250
2251 if (bit_size == ast.getTypeSize(ast.Int128Ty))
2252 return GetType(ast.Int128Ty);
2253 } else {
2254 if (bit_size == ast.getTypeSize(ast.UnsignedCharTy))
2255 return GetType(ast.UnsignedCharTy);
2256
2257 if (bit_size == ast.getTypeSize(ast.UnsignedShortTy))
2258 return GetType(ast.UnsignedShortTy);
2259
2260 if (bit_size == ast.getTypeSize(ast.UnsignedIntTy))
2261 return GetType(ast.UnsignedIntTy);
2262
2263 if (bit_size == ast.getTypeSize(ast.UnsignedLongTy))
2264 return GetType(ast.UnsignedLongTy);
2265
2266 if (bit_size == ast.getTypeSize(ast.UnsignedLongLongTy))
2267 return GetType(ast.UnsignedLongLongTy);
2268
2269 if (bit_size == ast.getTypeSize(ast.UnsignedInt128Ty))
2270 return GetType(ast.UnsignedInt128Ty);
2271 }
2272 return CompilerType();
2273 }
2274
GetPointerSizedIntType(bool is_signed)2275 CompilerType TypeSystemClang::GetPointerSizedIntType(bool is_signed) {
2276 return GetIntTypeFromBitSize(
2277 getASTContext().getTypeSize(getASTContext().VoidPtrTy), is_signed);
2278 }
2279
DumpDeclContextHiearchy(clang::DeclContext * decl_ctx)2280 void TypeSystemClang::DumpDeclContextHiearchy(clang::DeclContext *decl_ctx) {
2281 if (decl_ctx) {
2282 DumpDeclContextHiearchy(decl_ctx->getParent());
2283
2284 clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl_ctx);
2285 if (named_decl) {
2286 printf("%20s: %s\n", decl_ctx->getDeclKindName(),
2287 named_decl->getDeclName().getAsString().c_str());
2288 } else {
2289 printf("%20s\n", decl_ctx->getDeclKindName());
2290 }
2291 }
2292 }
2293
DumpDeclHiearchy(clang::Decl * decl)2294 void TypeSystemClang::DumpDeclHiearchy(clang::Decl *decl) {
2295 if (decl == nullptr)
2296 return;
2297 DumpDeclContextHiearchy(decl->getDeclContext());
2298
2299 clang::RecordDecl *record_decl = llvm::dyn_cast<clang::RecordDecl>(decl);
2300 if (record_decl) {
2301 printf("%20s: %s%s\n", decl->getDeclKindName(),
2302 record_decl->getDeclName().getAsString().c_str(),
2303 record_decl->isInjectedClassName() ? " (injected class name)" : "");
2304
2305 } else {
2306 clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl);
2307 if (named_decl) {
2308 printf("%20s: %s\n", decl->getDeclKindName(),
2309 named_decl->getDeclName().getAsString().c_str());
2310 } else {
2311 printf("%20s\n", decl->getDeclKindName());
2312 }
2313 }
2314 }
2315
DeclsAreEquivalent(clang::Decl * lhs_decl,clang::Decl * rhs_decl)2316 bool TypeSystemClang::DeclsAreEquivalent(clang::Decl *lhs_decl,
2317 clang::Decl *rhs_decl) {
2318 if (lhs_decl && rhs_decl) {
2319 // Make sure the decl kinds match first
2320 const clang::Decl::Kind lhs_decl_kind = lhs_decl->getKind();
2321 const clang::Decl::Kind rhs_decl_kind = rhs_decl->getKind();
2322
2323 if (lhs_decl_kind == rhs_decl_kind) {
2324 // Now check that the decl contexts kinds are all equivalent before we
2325 // have to check any names of the decl contexts...
2326 clang::DeclContext *lhs_decl_ctx = lhs_decl->getDeclContext();
2327 clang::DeclContext *rhs_decl_ctx = rhs_decl->getDeclContext();
2328 if (lhs_decl_ctx && rhs_decl_ctx) {
2329 while (true) {
2330 if (lhs_decl_ctx && rhs_decl_ctx) {
2331 const clang::Decl::Kind lhs_decl_ctx_kind =
2332 lhs_decl_ctx->getDeclKind();
2333 const clang::Decl::Kind rhs_decl_ctx_kind =
2334 rhs_decl_ctx->getDeclKind();
2335 if (lhs_decl_ctx_kind == rhs_decl_ctx_kind) {
2336 lhs_decl_ctx = lhs_decl_ctx->getParent();
2337 rhs_decl_ctx = rhs_decl_ctx->getParent();
2338
2339 if (lhs_decl_ctx == nullptr && rhs_decl_ctx == nullptr)
2340 break;
2341 } else
2342 return false;
2343 } else
2344 return false;
2345 }
2346
2347 // Now make sure the name of the decls match
2348 clang::NamedDecl *lhs_named_decl =
2349 llvm::dyn_cast<clang::NamedDecl>(lhs_decl);
2350 clang::NamedDecl *rhs_named_decl =
2351 llvm::dyn_cast<clang::NamedDecl>(rhs_decl);
2352 if (lhs_named_decl && rhs_named_decl) {
2353 clang::DeclarationName lhs_decl_name = lhs_named_decl->getDeclName();
2354 clang::DeclarationName rhs_decl_name = rhs_named_decl->getDeclName();
2355 if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2356 if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2357 return false;
2358 } else
2359 return false;
2360 } else
2361 return false;
2362
2363 // We know that the decl context kinds all match, so now we need to
2364 // make sure the names match as well
2365 lhs_decl_ctx = lhs_decl->getDeclContext();
2366 rhs_decl_ctx = rhs_decl->getDeclContext();
2367 while (true) {
2368 switch (lhs_decl_ctx->getDeclKind()) {
2369 case clang::Decl::TranslationUnit:
2370 // We don't care about the translation unit names
2371 return true;
2372 default: {
2373 clang::NamedDecl *lhs_named_decl =
2374 llvm::dyn_cast<clang::NamedDecl>(lhs_decl_ctx);
2375 clang::NamedDecl *rhs_named_decl =
2376 llvm::dyn_cast<clang::NamedDecl>(rhs_decl_ctx);
2377 if (lhs_named_decl && rhs_named_decl) {
2378 clang::DeclarationName lhs_decl_name =
2379 lhs_named_decl->getDeclName();
2380 clang::DeclarationName rhs_decl_name =
2381 rhs_named_decl->getDeclName();
2382 if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2383 if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2384 return false;
2385 } else
2386 return false;
2387 } else
2388 return false;
2389 } break;
2390 }
2391 lhs_decl_ctx = lhs_decl_ctx->getParent();
2392 rhs_decl_ctx = rhs_decl_ctx->getParent();
2393 }
2394 }
2395 }
2396 }
2397 return false;
2398 }
GetCompleteDecl(clang::ASTContext * ast,clang::Decl * decl)2399 bool TypeSystemClang::GetCompleteDecl(clang::ASTContext *ast,
2400 clang::Decl *decl) {
2401 if (!decl)
2402 return false;
2403
2404 ExternalASTSource *ast_source = ast->getExternalSource();
2405
2406 if (!ast_source)
2407 return false;
2408
2409 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) {
2410 if (tag_decl->isCompleteDefinition())
2411 return true;
2412
2413 if (!tag_decl->hasExternalLexicalStorage())
2414 return false;
2415
2416 ast_source->CompleteType(tag_decl);
2417
2418 return !tag_decl->getTypeForDecl()->isIncompleteType();
2419 } else if (clang::ObjCInterfaceDecl *objc_interface_decl =
2420 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) {
2421 if (objc_interface_decl->getDefinition())
2422 return true;
2423
2424 if (!objc_interface_decl->hasExternalLexicalStorage())
2425 return false;
2426
2427 ast_source->CompleteType(objc_interface_decl);
2428
2429 return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
2430 } else {
2431 return false;
2432 }
2433 }
2434
SetMetadataAsUserID(const clang::Decl * decl,user_id_t user_id)2435 void TypeSystemClang::SetMetadataAsUserID(const clang::Decl *decl,
2436 user_id_t user_id) {
2437 ClangASTMetadata meta_data;
2438 meta_data.SetUserID(user_id);
2439 SetMetadata(decl, meta_data);
2440 }
2441
SetMetadataAsUserID(const clang::Type * type,user_id_t user_id)2442 void TypeSystemClang::SetMetadataAsUserID(const clang::Type *type,
2443 user_id_t user_id) {
2444 ClangASTMetadata meta_data;
2445 meta_data.SetUserID(user_id);
2446 SetMetadata(type, meta_data);
2447 }
2448
SetMetadata(const clang::Decl * object,ClangASTMetadata & metadata)2449 void TypeSystemClang::SetMetadata(const clang::Decl *object,
2450 ClangASTMetadata &metadata) {
2451 m_decl_metadata[object] = metadata;
2452 }
2453
SetMetadata(const clang::Type * object,ClangASTMetadata & metadata)2454 void TypeSystemClang::SetMetadata(const clang::Type *object,
2455 ClangASTMetadata &metadata) {
2456 m_type_metadata[object] = metadata;
2457 }
2458
GetMetadata(const clang::Decl * object)2459 ClangASTMetadata *TypeSystemClang::GetMetadata(const clang::Decl *object) {
2460 auto It = m_decl_metadata.find(object);
2461 if (It != m_decl_metadata.end())
2462 return &It->second;
2463 return nullptr;
2464 }
2465
GetMetadata(const clang::Type * object)2466 ClangASTMetadata *TypeSystemClang::GetMetadata(const clang::Type *object) {
2467 auto It = m_type_metadata.find(object);
2468 if (It != m_type_metadata.end())
2469 return &It->second;
2470 return nullptr;
2471 }
2472
SetTagTypeKind(clang::QualType tag_qual_type,int kind) const2473 bool TypeSystemClang::SetTagTypeKind(clang::QualType tag_qual_type,
2474 int kind) const {
2475 const clang::Type *clang_type = tag_qual_type.getTypePtr();
2476 if (clang_type) {
2477 const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(clang_type);
2478 if (tag_type) {
2479 clang::TagDecl *tag_decl =
2480 llvm::dyn_cast<clang::TagDecl>(tag_type->getDecl());
2481 if (tag_decl) {
2482 tag_decl->setTagKind((clang::TagDecl::TagKind)kind);
2483 return true;
2484 }
2485 }
2486 }
2487 return false;
2488 }
2489
SetDefaultAccessForRecordFields(clang::RecordDecl * record_decl,int default_accessibility,int * assigned_accessibilities,size_t num_assigned_accessibilities)2490 bool TypeSystemClang::SetDefaultAccessForRecordFields(
2491 clang::RecordDecl *record_decl, int default_accessibility,
2492 int *assigned_accessibilities, size_t num_assigned_accessibilities) {
2493 if (record_decl) {
2494 uint32_t field_idx;
2495 clang::RecordDecl::field_iterator field, field_end;
2496 for (field = record_decl->field_begin(),
2497 field_end = record_decl->field_end(), field_idx = 0;
2498 field != field_end; ++field, ++field_idx) {
2499 // If no accessibility was assigned, assign the correct one
2500 if (field_idx < num_assigned_accessibilities &&
2501 assigned_accessibilities[field_idx] == clang::AS_none)
2502 field->setAccess((clang::AccessSpecifier)default_accessibility);
2503 }
2504 return true;
2505 }
2506 return false;
2507 }
2508
2509 clang::DeclContext *
GetDeclContextForType(const CompilerType & type)2510 TypeSystemClang::GetDeclContextForType(const CompilerType &type) {
2511 return GetDeclContextForType(ClangUtil::GetQualType(type));
2512 }
2513
2514 /// Aggressively desugar the provided type, skipping past various kinds of
2515 /// syntactic sugar and other constructs one typically wants to ignore.
2516 /// The \p mask argument allows one to skip certain kinds of simplifications,
2517 /// when one wishes to handle a certain kind of type directly.
2518 static QualType
RemoveWrappingTypes(QualType type,ArrayRef<clang::Type::TypeClass> mask={})2519 RemoveWrappingTypes(QualType type, ArrayRef<clang::Type::TypeClass> mask = {}) {
2520 while (true) {
2521 if (find(mask, type->getTypeClass()) != mask.end())
2522 return type;
2523 switch (type->getTypeClass()) {
2524 // This is not fully correct as _Atomic is more than sugar, but it is
2525 // sufficient for the purposes we care about.
2526 case clang::Type::Atomic:
2527 type = cast<clang::AtomicType>(type)->getValueType();
2528 break;
2529 case clang::Type::Auto:
2530 case clang::Type::Decltype:
2531 case clang::Type::Elaborated:
2532 case clang::Type::Paren:
2533 case clang::Type::SubstTemplateTypeParm:
2534 case clang::Type::TemplateSpecialization:
2535 case clang::Type::Typedef:
2536 case clang::Type::TypeOf:
2537 case clang::Type::TypeOfExpr:
2538 type = type->getLocallyUnqualifiedSingleStepDesugaredType();
2539 break;
2540 default:
2541 return type;
2542 }
2543 }
2544 }
2545
2546 clang::DeclContext *
GetDeclContextForType(clang::QualType type)2547 TypeSystemClang::GetDeclContextForType(clang::QualType type) {
2548 if (type.isNull())
2549 return nullptr;
2550
2551 clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType());
2552 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2553 switch (type_class) {
2554 case clang::Type::ObjCInterface:
2555 return llvm::cast<clang::ObjCObjectType>(qual_type.getTypePtr())
2556 ->getInterface();
2557 case clang::Type::ObjCObjectPointer:
2558 return GetDeclContextForType(
2559 llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
2560 ->getPointeeType());
2561 case clang::Type::Record:
2562 return llvm::cast<clang::RecordType>(qual_type)->getDecl();
2563 case clang::Type::Enum:
2564 return llvm::cast<clang::EnumType>(qual_type)->getDecl();
2565 default:
2566 break;
2567 }
2568 // No DeclContext in this type...
2569 return nullptr;
2570 }
2571
GetCompleteQualType(clang::ASTContext * ast,clang::QualType qual_type,bool allow_completion=true)2572 static bool GetCompleteQualType(clang::ASTContext *ast,
2573 clang::QualType qual_type,
2574 bool allow_completion = true) {
2575 qual_type = RemoveWrappingTypes(qual_type);
2576 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2577 switch (type_class) {
2578 case clang::Type::ConstantArray:
2579 case clang::Type::IncompleteArray:
2580 case clang::Type::VariableArray: {
2581 const clang::ArrayType *array_type =
2582 llvm::dyn_cast<clang::ArrayType>(qual_type.getTypePtr());
2583
2584 if (array_type)
2585 return GetCompleteQualType(ast, array_type->getElementType(),
2586 allow_completion);
2587 } break;
2588 case clang::Type::Record: {
2589 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2590 if (cxx_record_decl) {
2591 if (cxx_record_decl->hasExternalLexicalStorage()) {
2592 const bool is_complete = cxx_record_decl->isCompleteDefinition();
2593 const bool fields_loaded =
2594 cxx_record_decl->hasLoadedFieldsFromExternalStorage();
2595 if (is_complete && fields_loaded)
2596 return true;
2597
2598 if (!allow_completion)
2599 return false;
2600
2601 // Call the field_begin() accessor to for it to use the external source
2602 // to load the fields...
2603 clang::ExternalASTSource *external_ast_source =
2604 ast->getExternalSource();
2605 if (external_ast_source) {
2606 external_ast_source->CompleteType(cxx_record_decl);
2607 if (cxx_record_decl->isCompleteDefinition()) {
2608 cxx_record_decl->field_begin();
2609 cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
2610 }
2611 }
2612 }
2613 }
2614 const clang::TagType *tag_type =
2615 llvm::cast<clang::TagType>(qual_type.getTypePtr());
2616 return !tag_type->isIncompleteType();
2617 } break;
2618
2619 case clang::Type::Enum: {
2620 const clang::TagType *tag_type =
2621 llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
2622 if (tag_type) {
2623 clang::TagDecl *tag_decl = tag_type->getDecl();
2624 if (tag_decl) {
2625 if (tag_decl->getDefinition())
2626 return true;
2627
2628 if (!allow_completion)
2629 return false;
2630
2631 if (tag_decl->hasExternalLexicalStorage()) {
2632 if (ast) {
2633 clang::ExternalASTSource *external_ast_source =
2634 ast->getExternalSource();
2635 if (external_ast_source) {
2636 external_ast_source->CompleteType(tag_decl);
2637 return !tag_type->isIncompleteType();
2638 }
2639 }
2640 }
2641 return false;
2642 }
2643 }
2644
2645 } break;
2646 case clang::Type::ObjCObject:
2647 case clang::Type::ObjCInterface: {
2648 const clang::ObjCObjectType *objc_class_type =
2649 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
2650 if (objc_class_type) {
2651 clang::ObjCInterfaceDecl *class_interface_decl =
2652 objc_class_type->getInterface();
2653 // We currently can't complete objective C types through the newly added
2654 // ASTContext because it only supports TagDecl objects right now...
2655 if (class_interface_decl) {
2656 if (class_interface_decl->getDefinition())
2657 return true;
2658
2659 if (!allow_completion)
2660 return false;
2661
2662 if (class_interface_decl->hasExternalLexicalStorage()) {
2663 if (ast) {
2664 clang::ExternalASTSource *external_ast_source =
2665 ast->getExternalSource();
2666 if (external_ast_source) {
2667 external_ast_source->CompleteType(class_interface_decl);
2668 return !objc_class_type->isIncompleteType();
2669 }
2670 }
2671 }
2672 return false;
2673 }
2674 }
2675 } break;
2676
2677 case clang::Type::Attributed:
2678 return GetCompleteQualType(
2679 ast, llvm::cast<clang::AttributedType>(qual_type)->getModifiedType(),
2680 allow_completion);
2681
2682 default:
2683 break;
2684 }
2685
2686 return true;
2687 }
2688
2689 static clang::ObjCIvarDecl::AccessControl
ConvertAccessTypeToObjCIvarAccessControl(AccessType access)2690 ConvertAccessTypeToObjCIvarAccessControl(AccessType access) {
2691 switch (access) {
2692 case eAccessNone:
2693 return clang::ObjCIvarDecl::None;
2694 case eAccessPublic:
2695 return clang::ObjCIvarDecl::Public;
2696 case eAccessPrivate:
2697 return clang::ObjCIvarDecl::Private;
2698 case eAccessProtected:
2699 return clang::ObjCIvarDecl::Protected;
2700 case eAccessPackage:
2701 return clang::ObjCIvarDecl::Package;
2702 }
2703 return clang::ObjCIvarDecl::None;
2704 }
2705
2706 // Tests
2707
2708 #ifndef NDEBUG
Verify(lldb::opaque_compiler_type_t type)2709 bool TypeSystemClang::Verify(lldb::opaque_compiler_type_t type) {
2710 return !type || llvm::isa<clang::Type>(GetQualType(type).getTypePtr());
2711 }
2712 #endif
2713
IsAggregateType(lldb::opaque_compiler_type_t type)2714 bool TypeSystemClang::IsAggregateType(lldb::opaque_compiler_type_t type) {
2715 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2716
2717 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2718 switch (type_class) {
2719 case clang::Type::IncompleteArray:
2720 case clang::Type::VariableArray:
2721 case clang::Type::ConstantArray:
2722 case clang::Type::ExtVector:
2723 case clang::Type::Vector:
2724 case clang::Type::Record:
2725 case clang::Type::ObjCObject:
2726 case clang::Type::ObjCInterface:
2727 return true;
2728 default:
2729 break;
2730 }
2731 // The clang type does have a value
2732 return false;
2733 }
2734
IsAnonymousType(lldb::opaque_compiler_type_t type)2735 bool TypeSystemClang::IsAnonymousType(lldb::opaque_compiler_type_t type) {
2736 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2737
2738 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2739 switch (type_class) {
2740 case clang::Type::Record: {
2741 if (const clang::RecordType *record_type =
2742 llvm::dyn_cast_or_null<clang::RecordType>(
2743 qual_type.getTypePtrOrNull())) {
2744 if (const clang::RecordDecl *record_decl = record_type->getDecl()) {
2745 return record_decl->isAnonymousStructOrUnion();
2746 }
2747 }
2748 break;
2749 }
2750 default:
2751 break;
2752 }
2753 // The clang type does have a value
2754 return false;
2755 }
2756
IsArrayType(lldb::opaque_compiler_type_t type,CompilerType * element_type_ptr,uint64_t * size,bool * is_incomplete)2757 bool TypeSystemClang::IsArrayType(lldb::opaque_compiler_type_t type,
2758 CompilerType *element_type_ptr,
2759 uint64_t *size, bool *is_incomplete) {
2760 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2761
2762 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2763 switch (type_class) {
2764 default:
2765 break;
2766
2767 case clang::Type::ConstantArray:
2768 if (element_type_ptr)
2769 element_type_ptr->SetCompilerType(
2770 this, llvm::cast<clang::ConstantArrayType>(qual_type)
2771 ->getElementType()
2772 .getAsOpaquePtr());
2773 if (size)
2774 *size = llvm::cast<clang::ConstantArrayType>(qual_type)
2775 ->getSize()
2776 .getLimitedValue(ULLONG_MAX);
2777 if (is_incomplete)
2778 *is_incomplete = false;
2779 return true;
2780
2781 case clang::Type::IncompleteArray:
2782 if (element_type_ptr)
2783 element_type_ptr->SetCompilerType(
2784 this, llvm::cast<clang::IncompleteArrayType>(qual_type)
2785 ->getElementType()
2786 .getAsOpaquePtr());
2787 if (size)
2788 *size = 0;
2789 if (is_incomplete)
2790 *is_incomplete = true;
2791 return true;
2792
2793 case clang::Type::VariableArray:
2794 if (element_type_ptr)
2795 element_type_ptr->SetCompilerType(
2796 this, llvm::cast<clang::VariableArrayType>(qual_type)
2797 ->getElementType()
2798 .getAsOpaquePtr());
2799 if (size)
2800 *size = 0;
2801 if (is_incomplete)
2802 *is_incomplete = false;
2803 return true;
2804
2805 case clang::Type::DependentSizedArray:
2806 if (element_type_ptr)
2807 element_type_ptr->SetCompilerType(
2808 this, llvm::cast<clang::DependentSizedArrayType>(qual_type)
2809 ->getElementType()
2810 .getAsOpaquePtr());
2811 if (size)
2812 *size = 0;
2813 if (is_incomplete)
2814 *is_incomplete = false;
2815 return true;
2816 }
2817 if (element_type_ptr)
2818 element_type_ptr->Clear();
2819 if (size)
2820 *size = 0;
2821 if (is_incomplete)
2822 *is_incomplete = false;
2823 return false;
2824 }
2825
IsVectorType(lldb::opaque_compiler_type_t type,CompilerType * element_type,uint64_t * size)2826 bool TypeSystemClang::IsVectorType(lldb::opaque_compiler_type_t type,
2827 CompilerType *element_type, uint64_t *size) {
2828 clang::QualType qual_type(GetCanonicalQualType(type));
2829
2830 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2831 switch (type_class) {
2832 case clang::Type::Vector: {
2833 const clang::VectorType *vector_type =
2834 qual_type->getAs<clang::VectorType>();
2835 if (vector_type) {
2836 if (size)
2837 *size = vector_type->getNumElements();
2838 if (element_type)
2839 *element_type = GetType(vector_type->getElementType());
2840 }
2841 return true;
2842 } break;
2843 case clang::Type::ExtVector: {
2844 const clang::ExtVectorType *ext_vector_type =
2845 qual_type->getAs<clang::ExtVectorType>();
2846 if (ext_vector_type) {
2847 if (size)
2848 *size = ext_vector_type->getNumElements();
2849 if (element_type)
2850 *element_type =
2851 CompilerType(this, ext_vector_type->getElementType().getAsOpaquePtr());
2852 }
2853 return true;
2854 }
2855 default:
2856 break;
2857 }
2858 return false;
2859 }
2860
IsRuntimeGeneratedType(lldb::opaque_compiler_type_t type)2861 bool TypeSystemClang::IsRuntimeGeneratedType(
2862 lldb::opaque_compiler_type_t type) {
2863 clang::DeclContext *decl_ctx = GetDeclContextForType(GetQualType(type));
2864 if (!decl_ctx)
2865 return false;
2866
2867 if (!llvm::isa<clang::ObjCInterfaceDecl>(decl_ctx))
2868 return false;
2869
2870 clang::ObjCInterfaceDecl *result_iface_decl =
2871 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl_ctx);
2872
2873 ClangASTMetadata *ast_metadata = GetMetadata(result_iface_decl);
2874 if (!ast_metadata)
2875 return false;
2876 return (ast_metadata->GetISAPtr() != 0);
2877 }
2878
IsCharType(lldb::opaque_compiler_type_t type)2879 bool TypeSystemClang::IsCharType(lldb::opaque_compiler_type_t type) {
2880 return GetQualType(type).getUnqualifiedType()->isCharType();
2881 }
2882
IsCompleteType(lldb::opaque_compiler_type_t type)2883 bool TypeSystemClang::IsCompleteType(lldb::opaque_compiler_type_t type) {
2884 const bool allow_completion = false;
2885 return GetCompleteQualType(&getASTContext(), GetQualType(type),
2886 allow_completion);
2887 }
2888
IsConst(lldb::opaque_compiler_type_t type)2889 bool TypeSystemClang::IsConst(lldb::opaque_compiler_type_t type) {
2890 return GetQualType(type).isConstQualified();
2891 }
2892
IsCStringType(lldb::opaque_compiler_type_t type,uint32_t & length)2893 bool TypeSystemClang::IsCStringType(lldb::opaque_compiler_type_t type,
2894 uint32_t &length) {
2895 CompilerType pointee_or_element_clang_type;
2896 length = 0;
2897 Flags type_flags(GetTypeInfo(type, &pointee_or_element_clang_type));
2898
2899 if (!pointee_or_element_clang_type.IsValid())
2900 return false;
2901
2902 if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer)) {
2903 if (pointee_or_element_clang_type.IsCharType()) {
2904 if (type_flags.Test(eTypeIsArray)) {
2905 // We know the size of the array and it could be a C string since it is
2906 // an array of characters
2907 length = llvm::cast<clang::ConstantArrayType>(
2908 GetCanonicalQualType(type).getTypePtr())
2909 ->getSize()
2910 .getLimitedValue();
2911 }
2912 return true;
2913 }
2914 }
2915 return false;
2916 }
2917
IsFunctionType(lldb::opaque_compiler_type_t type)2918 bool TypeSystemClang::IsFunctionType(lldb::opaque_compiler_type_t type) {
2919 if (type) {
2920 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
2921
2922 if (qual_type->isFunctionType()) {
2923 return true;
2924 }
2925
2926 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2927 switch (type_class) {
2928 default:
2929 break;
2930 case clang::Type::LValueReference:
2931 case clang::Type::RValueReference: {
2932 const clang::ReferenceType *reference_type =
2933 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
2934 if (reference_type)
2935 return IsFunctionType(
2936 reference_type->getPointeeType().getAsOpaquePtr());
2937 } break;
2938 }
2939 }
2940 return false;
2941 }
2942
2943 // Used to detect "Homogeneous Floating-point Aggregates"
2944 uint32_t
IsHomogeneousAggregate(lldb::opaque_compiler_type_t type,CompilerType * base_type_ptr)2945 TypeSystemClang::IsHomogeneousAggregate(lldb::opaque_compiler_type_t type,
2946 CompilerType *base_type_ptr) {
2947 if (!type)
2948 return 0;
2949
2950 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2951 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2952 switch (type_class) {
2953 case clang::Type::Record:
2954 if (GetCompleteType(type)) {
2955 const clang::CXXRecordDecl *cxx_record_decl =
2956 qual_type->getAsCXXRecordDecl();
2957 if (cxx_record_decl) {
2958 if (cxx_record_decl->getNumBases() || cxx_record_decl->isDynamicClass())
2959 return 0;
2960 }
2961 const clang::RecordType *record_type =
2962 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
2963 if (record_type) {
2964 const clang::RecordDecl *record_decl = record_type->getDecl();
2965 if (record_decl) {
2966 // We are looking for a structure that contains only floating point
2967 // types
2968 clang::RecordDecl::field_iterator field_pos,
2969 field_end = record_decl->field_end();
2970 uint32_t num_fields = 0;
2971 bool is_hva = false;
2972 bool is_hfa = false;
2973 clang::QualType base_qual_type;
2974 uint64_t base_bitwidth = 0;
2975 for (field_pos = record_decl->field_begin(); field_pos != field_end;
2976 ++field_pos) {
2977 clang::QualType field_qual_type = field_pos->getType();
2978 uint64_t field_bitwidth = getASTContext().getTypeSize(qual_type);
2979 if (field_qual_type->isFloatingType()) {
2980 if (field_qual_type->isComplexType())
2981 return 0;
2982 else {
2983 if (num_fields == 0)
2984 base_qual_type = field_qual_type;
2985 else {
2986 if (is_hva)
2987 return 0;
2988 is_hfa = true;
2989 if (field_qual_type.getTypePtr() !=
2990 base_qual_type.getTypePtr())
2991 return 0;
2992 }
2993 }
2994 } else if (field_qual_type->isVectorType() ||
2995 field_qual_type->isExtVectorType()) {
2996 if (num_fields == 0) {
2997 base_qual_type = field_qual_type;
2998 base_bitwidth = field_bitwidth;
2999 } else {
3000 if (is_hfa)
3001 return 0;
3002 is_hva = true;
3003 if (base_bitwidth != field_bitwidth)
3004 return 0;
3005 if (field_qual_type.getTypePtr() != base_qual_type.getTypePtr())
3006 return 0;
3007 }
3008 } else
3009 return 0;
3010 ++num_fields;
3011 }
3012 if (base_type_ptr)
3013 *base_type_ptr = CompilerType(this, base_qual_type.getAsOpaquePtr());
3014 return num_fields;
3015 }
3016 }
3017 }
3018 break;
3019
3020 default:
3021 break;
3022 }
3023 return 0;
3024 }
3025
GetNumberOfFunctionArguments(lldb::opaque_compiler_type_t type)3026 size_t TypeSystemClang::GetNumberOfFunctionArguments(
3027 lldb::opaque_compiler_type_t type) {
3028 if (type) {
3029 clang::QualType qual_type(GetCanonicalQualType(type));
3030 const clang::FunctionProtoType *func =
3031 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3032 if (func)
3033 return func->getNumParams();
3034 }
3035 return 0;
3036 }
3037
3038 CompilerType
GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type,const size_t index)3039 TypeSystemClang::GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type,
3040 const size_t index) {
3041 if (type) {
3042 clang::QualType qual_type(GetQualType(type));
3043 const clang::FunctionProtoType *func =
3044 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3045 if (func) {
3046 if (index < func->getNumParams())
3047 return CompilerType(this, func->getParamType(index).getAsOpaquePtr());
3048 }
3049 }
3050 return CompilerType();
3051 }
3052
IsFunctionPointerType(lldb::opaque_compiler_type_t type)3053 bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
3054 if (type) {
3055 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3056
3057 if (qual_type->isFunctionPointerType())
3058 return true;
3059
3060 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3061 switch (type_class) {
3062 default:
3063 break;
3064
3065 case clang::Type::LValueReference:
3066 case clang::Type::RValueReference: {
3067 const clang::ReferenceType *reference_type =
3068 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3069 if (reference_type)
3070 return IsFunctionPointerType(
3071 reference_type->getPointeeType().getAsOpaquePtr());
3072 } break;
3073 }
3074 }
3075 return false;
3076 }
3077
IsBlockPointerType(lldb::opaque_compiler_type_t type,CompilerType * function_pointer_type_ptr)3078 bool TypeSystemClang::IsBlockPointerType(
3079 lldb::opaque_compiler_type_t type,
3080 CompilerType *function_pointer_type_ptr) {
3081 if (type) {
3082 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3083
3084 if (qual_type->isBlockPointerType()) {
3085 if (function_pointer_type_ptr) {
3086 const clang::BlockPointerType *block_pointer_type =
3087 qual_type->getAs<clang::BlockPointerType>();
3088 QualType pointee_type = block_pointer_type->getPointeeType();
3089 QualType function_pointer_type = m_ast_up->getPointerType(pointee_type);
3090 *function_pointer_type_ptr =
3091 CompilerType(this, function_pointer_type.getAsOpaquePtr());
3092 }
3093 return true;
3094 }
3095
3096 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3097 switch (type_class) {
3098 default:
3099 break;
3100
3101 case clang::Type::LValueReference:
3102 case clang::Type::RValueReference: {
3103 const clang::ReferenceType *reference_type =
3104 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3105 if (reference_type)
3106 return IsBlockPointerType(
3107 reference_type->getPointeeType().getAsOpaquePtr(),
3108 function_pointer_type_ptr);
3109 } break;
3110 }
3111 }
3112 return false;
3113 }
3114
IsIntegerType(lldb::opaque_compiler_type_t type,bool & is_signed)3115 bool TypeSystemClang::IsIntegerType(lldb::opaque_compiler_type_t type,
3116 bool &is_signed) {
3117 if (!type)
3118 return false;
3119
3120 clang::QualType qual_type(GetCanonicalQualType(type));
3121 const clang::BuiltinType *builtin_type =
3122 llvm::dyn_cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal());
3123
3124 if (builtin_type) {
3125 if (builtin_type->isInteger()) {
3126 is_signed = builtin_type->isSignedInteger();
3127 return true;
3128 }
3129 }
3130
3131 return false;
3132 }
3133
IsEnumerationType(lldb::opaque_compiler_type_t type,bool & is_signed)3134 bool TypeSystemClang::IsEnumerationType(lldb::opaque_compiler_type_t type,
3135 bool &is_signed) {
3136 if (type) {
3137 const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3138 GetCanonicalQualType(type)->getCanonicalTypeInternal());
3139
3140 if (enum_type) {
3141 IsIntegerType(enum_type->getDecl()->getIntegerType().getAsOpaquePtr(),
3142 is_signed);
3143 return true;
3144 }
3145 }
3146
3147 return false;
3148 }
3149
IsPointerType(lldb::opaque_compiler_type_t type,CompilerType * pointee_type)3150 bool TypeSystemClang::IsPointerType(lldb::opaque_compiler_type_t type,
3151 CompilerType *pointee_type) {
3152 if (type) {
3153 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3154 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3155 switch (type_class) {
3156 case clang::Type::Builtin:
3157 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3158 default:
3159 break;
3160 case clang::BuiltinType::ObjCId:
3161 case clang::BuiltinType::ObjCClass:
3162 return true;
3163 }
3164 return false;
3165 case clang::Type::ObjCObjectPointer:
3166 if (pointee_type)
3167 pointee_type->SetCompilerType(
3168 this, llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3169 ->getPointeeType()
3170 .getAsOpaquePtr());
3171 return true;
3172 case clang::Type::BlockPointer:
3173 if (pointee_type)
3174 pointee_type->SetCompilerType(
3175 this, llvm::cast<clang::BlockPointerType>(qual_type)
3176 ->getPointeeType()
3177 .getAsOpaquePtr());
3178 return true;
3179 case clang::Type::Pointer:
3180 if (pointee_type)
3181 pointee_type->SetCompilerType(this,
3182 llvm::cast<clang::PointerType>(qual_type)
3183 ->getPointeeType()
3184 .getAsOpaquePtr());
3185 return true;
3186 case clang::Type::MemberPointer:
3187 if (pointee_type)
3188 pointee_type->SetCompilerType(
3189 this, llvm::cast<clang::MemberPointerType>(qual_type)
3190 ->getPointeeType()
3191 .getAsOpaquePtr());
3192 return true;
3193 default:
3194 break;
3195 }
3196 }
3197 if (pointee_type)
3198 pointee_type->Clear();
3199 return false;
3200 }
3201
IsPointerOrReferenceType(lldb::opaque_compiler_type_t type,CompilerType * pointee_type)3202 bool TypeSystemClang::IsPointerOrReferenceType(
3203 lldb::opaque_compiler_type_t type, CompilerType *pointee_type) {
3204 if (type) {
3205 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3206 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3207 switch (type_class) {
3208 case clang::Type::Builtin:
3209 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3210 default:
3211 break;
3212 case clang::BuiltinType::ObjCId:
3213 case clang::BuiltinType::ObjCClass:
3214 return true;
3215 }
3216 return false;
3217 case clang::Type::ObjCObjectPointer:
3218 if (pointee_type)
3219 pointee_type->SetCompilerType(
3220 this, llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3221 ->getPointeeType().getAsOpaquePtr());
3222 return true;
3223 case clang::Type::BlockPointer:
3224 if (pointee_type)
3225 pointee_type->SetCompilerType(
3226 this, llvm::cast<clang::BlockPointerType>(qual_type)
3227 ->getPointeeType()
3228 .getAsOpaquePtr());
3229 return true;
3230 case clang::Type::Pointer:
3231 if (pointee_type)
3232 pointee_type->SetCompilerType(this,
3233 llvm::cast<clang::PointerType>(qual_type)
3234 ->getPointeeType()
3235 .getAsOpaquePtr());
3236 return true;
3237 case clang::Type::MemberPointer:
3238 if (pointee_type)
3239 pointee_type->SetCompilerType(
3240 this, llvm::cast<clang::MemberPointerType>(qual_type)
3241 ->getPointeeType()
3242 .getAsOpaquePtr());
3243 return true;
3244 case clang::Type::LValueReference:
3245 if (pointee_type)
3246 pointee_type->SetCompilerType(
3247 this, llvm::cast<clang::LValueReferenceType>(qual_type)
3248 ->desugar()
3249 .getAsOpaquePtr());
3250 return true;
3251 case clang::Type::RValueReference:
3252 if (pointee_type)
3253 pointee_type->SetCompilerType(
3254 this, llvm::cast<clang::RValueReferenceType>(qual_type)
3255 ->desugar()
3256 .getAsOpaquePtr());
3257 return true;
3258 default:
3259 break;
3260 }
3261 }
3262 if (pointee_type)
3263 pointee_type->Clear();
3264 return false;
3265 }
3266
IsReferenceType(lldb::opaque_compiler_type_t type,CompilerType * pointee_type,bool * is_rvalue)3267 bool TypeSystemClang::IsReferenceType(lldb::opaque_compiler_type_t type,
3268 CompilerType *pointee_type,
3269 bool *is_rvalue) {
3270 if (type) {
3271 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3272 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3273
3274 switch (type_class) {
3275 case clang::Type::LValueReference:
3276 if (pointee_type)
3277 pointee_type->SetCompilerType(
3278 this, llvm::cast<clang::LValueReferenceType>(qual_type)
3279 ->desugar()
3280 .getAsOpaquePtr());
3281 if (is_rvalue)
3282 *is_rvalue = false;
3283 return true;
3284 case clang::Type::RValueReference:
3285 if (pointee_type)
3286 pointee_type->SetCompilerType(
3287 this, llvm::cast<clang::RValueReferenceType>(qual_type)
3288 ->desugar()
3289 .getAsOpaquePtr());
3290 if (is_rvalue)
3291 *is_rvalue = true;
3292 return true;
3293
3294 default:
3295 break;
3296 }
3297 }
3298 if (pointee_type)
3299 pointee_type->Clear();
3300 return false;
3301 }
3302
IsFloatingPointType(lldb::opaque_compiler_type_t type,uint32_t & count,bool & is_complex)3303 bool TypeSystemClang::IsFloatingPointType(lldb::opaque_compiler_type_t type,
3304 uint32_t &count, bool &is_complex) {
3305 if (type) {
3306 clang::QualType qual_type(GetCanonicalQualType(type));
3307
3308 if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>(
3309 qual_type->getCanonicalTypeInternal())) {
3310 clang::BuiltinType::Kind kind = BT->getKind();
3311 if (kind >= clang::BuiltinType::Float &&
3312 kind <= clang::BuiltinType::LongDouble) {
3313 count = 1;
3314 is_complex = false;
3315 return true;
3316 }
3317 } else if (const clang::ComplexType *CT =
3318 llvm::dyn_cast<clang::ComplexType>(
3319 qual_type->getCanonicalTypeInternal())) {
3320 if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count,
3321 is_complex)) {
3322 count = 2;
3323 is_complex = true;
3324 return true;
3325 }
3326 } else if (const clang::VectorType *VT = llvm::dyn_cast<clang::VectorType>(
3327 qual_type->getCanonicalTypeInternal())) {
3328 if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count,
3329 is_complex)) {
3330 count = VT->getNumElements();
3331 is_complex = false;
3332 return true;
3333 }
3334 }
3335 }
3336 count = 0;
3337 is_complex = false;
3338 return false;
3339 }
3340
IsDefined(lldb::opaque_compiler_type_t type)3341 bool TypeSystemClang::IsDefined(lldb::opaque_compiler_type_t type) {
3342 if (!type)
3343 return false;
3344
3345 clang::QualType qual_type(GetQualType(type));
3346 const clang::TagType *tag_type =
3347 llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
3348 if (tag_type) {
3349 clang::TagDecl *tag_decl = tag_type->getDecl();
3350 if (tag_decl)
3351 return tag_decl->isCompleteDefinition();
3352 return false;
3353 } else {
3354 const clang::ObjCObjectType *objc_class_type =
3355 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
3356 if (objc_class_type) {
3357 clang::ObjCInterfaceDecl *class_interface_decl =
3358 objc_class_type->getInterface();
3359 if (class_interface_decl)
3360 return class_interface_decl->getDefinition() != nullptr;
3361 return false;
3362 }
3363 }
3364 return true;
3365 }
3366
IsObjCClassType(const CompilerType & type)3367 bool TypeSystemClang::IsObjCClassType(const CompilerType &type) {
3368 if (ClangUtil::IsClangType(type)) {
3369 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3370
3371 const clang::ObjCObjectPointerType *obj_pointer_type =
3372 llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3373
3374 if (obj_pointer_type)
3375 return obj_pointer_type->isObjCClassType();
3376 }
3377 return false;
3378 }
3379
IsObjCObjectOrInterfaceType(const CompilerType & type)3380 bool TypeSystemClang::IsObjCObjectOrInterfaceType(const CompilerType &type) {
3381 if (ClangUtil::IsClangType(type))
3382 return ClangUtil::GetCanonicalQualType(type)->isObjCObjectOrInterfaceType();
3383 return false;
3384 }
3385
IsClassType(lldb::opaque_compiler_type_t type)3386 bool TypeSystemClang::IsClassType(lldb::opaque_compiler_type_t type) {
3387 if (!type)
3388 return false;
3389 clang::QualType qual_type(GetCanonicalQualType(type));
3390 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3391 return (type_class == clang::Type::Record);
3392 }
3393
IsEnumType(lldb::opaque_compiler_type_t type)3394 bool TypeSystemClang::IsEnumType(lldb::opaque_compiler_type_t type) {
3395 if (!type)
3396 return false;
3397 clang::QualType qual_type(GetCanonicalQualType(type));
3398 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3399 return (type_class == clang::Type::Enum);
3400 }
3401
IsPolymorphicClass(lldb::opaque_compiler_type_t type)3402 bool TypeSystemClang::IsPolymorphicClass(lldb::opaque_compiler_type_t type) {
3403 if (type) {
3404 clang::QualType qual_type(GetCanonicalQualType(type));
3405 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3406 switch (type_class) {
3407 case clang::Type::Record:
3408 if (GetCompleteType(type)) {
3409 const clang::RecordType *record_type =
3410 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3411 const clang::RecordDecl *record_decl = record_type->getDecl();
3412 if (record_decl) {
3413 const clang::CXXRecordDecl *cxx_record_decl =
3414 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
3415 if (cxx_record_decl)
3416 return cxx_record_decl->isPolymorphic();
3417 }
3418 }
3419 break;
3420
3421 default:
3422 break;
3423 }
3424 }
3425 return false;
3426 }
3427
IsPossibleDynamicType(lldb::opaque_compiler_type_t type,CompilerType * dynamic_pointee_type,bool check_cplusplus,bool check_objc)3428 bool TypeSystemClang::IsPossibleDynamicType(lldb::opaque_compiler_type_t type,
3429 CompilerType *dynamic_pointee_type,
3430 bool check_cplusplus,
3431 bool check_objc) {
3432 clang::QualType pointee_qual_type;
3433 if (type) {
3434 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3435 bool success = false;
3436 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3437 switch (type_class) {
3438 case clang::Type::Builtin:
3439 if (check_objc &&
3440 llvm::cast<clang::BuiltinType>(qual_type)->getKind() ==
3441 clang::BuiltinType::ObjCId) {
3442 if (dynamic_pointee_type)
3443 dynamic_pointee_type->SetCompilerType(this, type);
3444 return true;
3445 }
3446 break;
3447
3448 case clang::Type::ObjCObjectPointer:
3449 if (check_objc) {
3450 if (const auto *objc_pointee_type =
3451 qual_type->getPointeeType().getTypePtrOrNull()) {
3452 if (const auto *objc_object_type =
3453 llvm::dyn_cast_or_null<clang::ObjCObjectType>(
3454 objc_pointee_type)) {
3455 if (objc_object_type->isObjCClass())
3456 return false;
3457 }
3458 }
3459 if (dynamic_pointee_type)
3460 dynamic_pointee_type->SetCompilerType(
3461 this, llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3462 ->getPointeeType()
3463 .getAsOpaquePtr());
3464 return true;
3465 }
3466 break;
3467
3468 case clang::Type::Pointer:
3469 pointee_qual_type =
3470 llvm::cast<clang::PointerType>(qual_type)->getPointeeType();
3471 success = true;
3472 break;
3473
3474 case clang::Type::LValueReference:
3475 case clang::Type::RValueReference:
3476 pointee_qual_type =
3477 llvm::cast<clang::ReferenceType>(qual_type)->getPointeeType();
3478 success = true;
3479 break;
3480
3481 default:
3482 break;
3483 }
3484
3485 if (success) {
3486 // Check to make sure what we are pointing too is a possible dynamic C++
3487 // type We currently accept any "void *" (in case we have a class that
3488 // has been watered down to an opaque pointer) and virtual C++ classes.
3489 const clang::Type::TypeClass pointee_type_class =
3490 pointee_qual_type.getCanonicalType()->getTypeClass();
3491 switch (pointee_type_class) {
3492 case clang::Type::Builtin:
3493 switch (llvm::cast<clang::BuiltinType>(pointee_qual_type)->getKind()) {
3494 case clang::BuiltinType::UnknownAny:
3495 case clang::BuiltinType::Void:
3496 if (dynamic_pointee_type)
3497 dynamic_pointee_type->SetCompilerType(
3498 this, pointee_qual_type.getAsOpaquePtr());
3499 return true;
3500 default:
3501 break;
3502 }
3503 break;
3504
3505 case clang::Type::Record:
3506 if (check_cplusplus) {
3507 clang::CXXRecordDecl *cxx_record_decl =
3508 pointee_qual_type->getAsCXXRecordDecl();
3509 if (cxx_record_decl) {
3510 bool is_complete = cxx_record_decl->isCompleteDefinition();
3511
3512 if (is_complete)
3513 success = cxx_record_decl->isDynamicClass();
3514 else {
3515 ClangASTMetadata *metadata = GetMetadata(cxx_record_decl);
3516 if (metadata)
3517 success = metadata->GetIsDynamicCXXType();
3518 else {
3519 is_complete = GetType(pointee_qual_type).GetCompleteType();
3520 if (is_complete)
3521 success = cxx_record_decl->isDynamicClass();
3522 else
3523 success = false;
3524 }
3525 }
3526
3527 if (success) {
3528 if (dynamic_pointee_type)
3529 dynamic_pointee_type->SetCompilerType(
3530 this, pointee_qual_type.getAsOpaquePtr());
3531 return true;
3532 }
3533 }
3534 }
3535 break;
3536
3537 case clang::Type::ObjCObject:
3538 case clang::Type::ObjCInterface:
3539 if (check_objc) {
3540 if (dynamic_pointee_type)
3541 dynamic_pointee_type->SetCompilerType(
3542 this, pointee_qual_type.getAsOpaquePtr());
3543 return true;
3544 }
3545 break;
3546
3547 default:
3548 break;
3549 }
3550 }
3551 }
3552 if (dynamic_pointee_type)
3553 dynamic_pointee_type->Clear();
3554 return false;
3555 }
3556
IsScalarType(lldb::opaque_compiler_type_t type)3557 bool TypeSystemClang::IsScalarType(lldb::opaque_compiler_type_t type) {
3558 if (!type)
3559 return false;
3560
3561 return (GetTypeInfo(type, nullptr) & eTypeIsScalar) != 0;
3562 }
3563
IsTypedefType(lldb::opaque_compiler_type_t type)3564 bool TypeSystemClang::IsTypedefType(lldb::opaque_compiler_type_t type) {
3565 if (!type)
3566 return false;
3567 return RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef})
3568 ->getTypeClass() == clang::Type::Typedef;
3569 }
3570
IsVoidType(lldb::opaque_compiler_type_t type)3571 bool TypeSystemClang::IsVoidType(lldb::opaque_compiler_type_t type) {
3572 if (!type)
3573 return false;
3574 return GetCanonicalQualType(type)->isVoidType();
3575 }
3576
CanPassInRegisters(const CompilerType & type)3577 bool TypeSystemClang::CanPassInRegisters(const CompilerType &type) {
3578 if (auto *record_decl =
3579 TypeSystemClang::GetAsRecordDecl(type)) {
3580 return record_decl->canPassInRegisters();
3581 }
3582 return false;
3583 }
3584
SupportsLanguage(lldb::LanguageType language)3585 bool TypeSystemClang::SupportsLanguage(lldb::LanguageType language) {
3586 return TypeSystemClangSupportsLanguage(language);
3587 }
3588
3589 Optional<std::string>
GetCXXClassName(const CompilerType & type)3590 TypeSystemClang::GetCXXClassName(const CompilerType &type) {
3591 if (!type)
3592 return llvm::None;
3593
3594 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3595 if (qual_type.isNull())
3596 return llvm::None;
3597
3598 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3599 if (!cxx_record_decl)
3600 return llvm::None;
3601
3602 return std::string(cxx_record_decl->getIdentifier()->getNameStart());
3603 }
3604
IsCXXClassType(const CompilerType & type)3605 bool TypeSystemClang::IsCXXClassType(const CompilerType &type) {
3606 if (!type)
3607 return false;
3608
3609 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3610 return !qual_type.isNull() && qual_type->getAsCXXRecordDecl() != nullptr;
3611 }
3612
IsBeingDefined(lldb::opaque_compiler_type_t type)3613 bool TypeSystemClang::IsBeingDefined(lldb::opaque_compiler_type_t type) {
3614 if (!type)
3615 return false;
3616 clang::QualType qual_type(GetCanonicalQualType(type));
3617 const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type);
3618 if (tag_type)
3619 return tag_type->isBeingDefined();
3620 return false;
3621 }
3622
IsObjCObjectPointerType(const CompilerType & type,CompilerType * class_type_ptr)3623 bool TypeSystemClang::IsObjCObjectPointerType(const CompilerType &type,
3624 CompilerType *class_type_ptr) {
3625 if (!ClangUtil::IsClangType(type))
3626 return false;
3627
3628 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3629
3630 if (!qual_type.isNull() && qual_type->isObjCObjectPointerType()) {
3631 if (class_type_ptr) {
3632 if (!qual_type->isObjCClassType() && !qual_type->isObjCIdType()) {
3633 const clang::ObjCObjectPointerType *obj_pointer_type =
3634 llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3635 if (obj_pointer_type == nullptr)
3636 class_type_ptr->Clear();
3637 else
3638 class_type_ptr->SetCompilerType(
3639 type.GetTypeSystem(),
3640 clang::QualType(obj_pointer_type->getInterfaceType(), 0)
3641 .getAsOpaquePtr());
3642 }
3643 }
3644 return true;
3645 }
3646 if (class_type_ptr)
3647 class_type_ptr->Clear();
3648 return false;
3649 }
3650
3651 // Type Completion
3652
GetCompleteType(lldb::opaque_compiler_type_t type)3653 bool TypeSystemClang::GetCompleteType(lldb::opaque_compiler_type_t type) {
3654 if (!type)
3655 return false;
3656 const bool allow_completion = true;
3657 return GetCompleteQualType(&getASTContext(), GetQualType(type),
3658 allow_completion);
3659 }
3660
GetTypeName(lldb::opaque_compiler_type_t type)3661 ConstString TypeSystemClang::GetTypeName(lldb::opaque_compiler_type_t type) {
3662 if (!type)
3663 return ConstString();
3664
3665 clang::QualType qual_type(GetQualType(type));
3666
3667 // Remove certain type sugar from the name. Sugar such as elaborated types
3668 // or template types which only serve to improve diagnostics shouldn't
3669 // act as their own types from the user's perspective (e.g., formatter
3670 // shouldn't format a variable differently depending on how the ser has
3671 // specified the type. '::Type' and 'Type' should behave the same).
3672 // Typedefs and atomic derived types are not removed as they are actually
3673 // useful for identifiying specific types.
3674 qual_type = RemoveWrappingTypes(qual_type,
3675 {clang::Type::Typedef, clang::Type::Atomic});
3676
3677 // For a typedef just return the qualified name.
3678 if (const auto *typedef_type = qual_type->getAs<clang::TypedefType>()) {
3679 const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
3680 return ConstString(GetTypeNameForDecl(typedef_decl));
3681 }
3682
3683 return ConstString(qual_type.getAsString(GetTypePrintingPolicy()));
3684 }
3685
3686 ConstString
GetDisplayTypeName(lldb::opaque_compiler_type_t type)3687 TypeSystemClang::GetDisplayTypeName(lldb::opaque_compiler_type_t type) {
3688 if (!type)
3689 return ConstString();
3690
3691 clang::QualType qual_type(GetQualType(type));
3692 clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy());
3693 printing_policy.SuppressTagKeyword = true;
3694 printing_policy.SuppressScope = false;
3695 printing_policy.SuppressUnwrittenScope = true;
3696 printing_policy.SuppressInlineNamespace = true;
3697 return ConstString(qual_type.getAsString(printing_policy));
3698 }
3699
3700 uint32_t
GetTypeInfo(lldb::opaque_compiler_type_t type,CompilerType * pointee_or_element_clang_type)3701 TypeSystemClang::GetTypeInfo(lldb::opaque_compiler_type_t type,
3702 CompilerType *pointee_or_element_clang_type) {
3703 if (!type)
3704 return 0;
3705
3706 if (pointee_or_element_clang_type)
3707 pointee_or_element_clang_type->Clear();
3708
3709 clang::QualType qual_type =
3710 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
3711
3712 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3713 switch (type_class) {
3714 case clang::Type::Attributed:
3715 return GetTypeInfo(
3716 qual_type->getAs<clang::AttributedType>()
3717 ->getModifiedType().getAsOpaquePtr(),
3718 pointee_or_element_clang_type);
3719 case clang::Type::Builtin: {
3720 const clang::BuiltinType *builtin_type = llvm::dyn_cast<clang::BuiltinType>(
3721 qual_type->getCanonicalTypeInternal());
3722
3723 uint32_t builtin_type_flags = eTypeIsBuiltIn | eTypeHasValue;
3724 switch (builtin_type->getKind()) {
3725 case clang::BuiltinType::ObjCId:
3726 case clang::BuiltinType::ObjCClass:
3727 if (pointee_or_element_clang_type)
3728 pointee_or_element_clang_type->SetCompilerType(
3729 this, getASTContext().ObjCBuiltinClassTy.getAsOpaquePtr());
3730 builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3731 break;
3732
3733 case clang::BuiltinType::ObjCSel:
3734 if (pointee_or_element_clang_type)
3735 pointee_or_element_clang_type->SetCompilerType(
3736 this, getASTContext().CharTy.getAsOpaquePtr());
3737 builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3738 break;
3739
3740 case clang::BuiltinType::Bool:
3741 case clang::BuiltinType::Char_U:
3742 case clang::BuiltinType::UChar:
3743 case clang::BuiltinType::WChar_U:
3744 case clang::BuiltinType::Char16:
3745 case clang::BuiltinType::Char32:
3746 case clang::BuiltinType::UShort:
3747 case clang::BuiltinType::UInt:
3748 case clang::BuiltinType::ULong:
3749 case clang::BuiltinType::ULongLong:
3750 case clang::BuiltinType::UInt128:
3751 case clang::BuiltinType::Char_S:
3752 case clang::BuiltinType::SChar:
3753 case clang::BuiltinType::WChar_S:
3754 case clang::BuiltinType::Short:
3755 case clang::BuiltinType::Int:
3756 case clang::BuiltinType::Long:
3757 case clang::BuiltinType::LongLong:
3758 case clang::BuiltinType::Int128:
3759 case clang::BuiltinType::Float:
3760 case clang::BuiltinType::Double:
3761 case clang::BuiltinType::LongDouble:
3762 builtin_type_flags |= eTypeIsScalar;
3763 if (builtin_type->isInteger()) {
3764 builtin_type_flags |= eTypeIsInteger;
3765 if (builtin_type->isSignedInteger())
3766 builtin_type_flags |= eTypeIsSigned;
3767 } else if (builtin_type->isFloatingPoint())
3768 builtin_type_flags |= eTypeIsFloat;
3769 break;
3770 default:
3771 break;
3772 }
3773 return builtin_type_flags;
3774 }
3775
3776 case clang::Type::BlockPointer:
3777 if (pointee_or_element_clang_type)
3778 pointee_or_element_clang_type->SetCompilerType(
3779 this, qual_type->getPointeeType().getAsOpaquePtr());
3780 return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
3781
3782 case clang::Type::Complex: {
3783 uint32_t complex_type_flags =
3784 eTypeIsBuiltIn | eTypeHasValue | eTypeIsComplex;
3785 const clang::ComplexType *complex_type = llvm::dyn_cast<clang::ComplexType>(
3786 qual_type->getCanonicalTypeInternal());
3787 if (complex_type) {
3788 clang::QualType complex_element_type(complex_type->getElementType());
3789 if (complex_element_type->isIntegerType())
3790 complex_type_flags |= eTypeIsFloat;
3791 else if (complex_element_type->isFloatingType())
3792 complex_type_flags |= eTypeIsInteger;
3793 }
3794 return complex_type_flags;
3795 } break;
3796
3797 case clang::Type::ConstantArray:
3798 case clang::Type::DependentSizedArray:
3799 case clang::Type::IncompleteArray:
3800 case clang::Type::VariableArray:
3801 if (pointee_or_element_clang_type)
3802 pointee_or_element_clang_type->SetCompilerType(
3803 this, llvm::cast<clang::ArrayType>(qual_type.getTypePtr())
3804 ->getElementType()
3805 .getAsOpaquePtr());
3806 return eTypeHasChildren | eTypeIsArray;
3807
3808 case clang::Type::DependentName:
3809 return 0;
3810 case clang::Type::DependentSizedExtVector:
3811 return eTypeHasChildren | eTypeIsVector;
3812 case clang::Type::DependentTemplateSpecialization:
3813 return eTypeIsTemplate;
3814
3815 case clang::Type::Enum:
3816 if (pointee_or_element_clang_type)
3817 pointee_or_element_clang_type->SetCompilerType(
3818 this, llvm::cast<clang::EnumType>(qual_type)
3819 ->getDecl()
3820 ->getIntegerType()
3821 .getAsOpaquePtr());
3822 return eTypeIsEnumeration | eTypeHasValue;
3823
3824 case clang::Type::FunctionProto:
3825 return eTypeIsFuncPrototype | eTypeHasValue;
3826 case clang::Type::FunctionNoProto:
3827 return eTypeIsFuncPrototype | eTypeHasValue;
3828 case clang::Type::InjectedClassName:
3829 return 0;
3830
3831 case clang::Type::LValueReference:
3832 case clang::Type::RValueReference:
3833 if (pointee_or_element_clang_type)
3834 pointee_or_element_clang_type->SetCompilerType(
3835 this, llvm::cast<clang::ReferenceType>(qual_type.getTypePtr())
3836 ->getPointeeType()
3837 .getAsOpaquePtr());
3838 return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
3839
3840 case clang::Type::MemberPointer:
3841 return eTypeIsPointer | eTypeIsMember | eTypeHasValue;
3842
3843 case clang::Type::ObjCObjectPointer:
3844 if (pointee_or_element_clang_type)
3845 pointee_or_element_clang_type->SetCompilerType(
3846 this, qual_type->getPointeeType().getAsOpaquePtr());
3847 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer |
3848 eTypeHasValue;
3849
3850 case clang::Type::ObjCObject:
3851 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3852 case clang::Type::ObjCInterface:
3853 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3854
3855 case clang::Type::Pointer:
3856 if (pointee_or_element_clang_type)
3857 pointee_or_element_clang_type->SetCompilerType(
3858 this, qual_type->getPointeeType().getAsOpaquePtr());
3859 return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
3860
3861 case clang::Type::Record:
3862 if (qual_type->getAsCXXRecordDecl())
3863 return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
3864 else
3865 return eTypeHasChildren | eTypeIsStructUnion;
3866 break;
3867 case clang::Type::SubstTemplateTypeParm:
3868 return eTypeIsTemplate;
3869 case clang::Type::TemplateTypeParm:
3870 return eTypeIsTemplate;
3871 case clang::Type::TemplateSpecialization:
3872 return eTypeIsTemplate;
3873
3874 case clang::Type::Typedef:
3875 return eTypeIsTypedef | GetType(llvm::cast<clang::TypedefType>(qual_type)
3876 ->getDecl()
3877 ->getUnderlyingType())
3878 .GetTypeInfo(pointee_or_element_clang_type);
3879 case clang::Type::UnresolvedUsing:
3880 return 0;
3881
3882 case clang::Type::ExtVector:
3883 case clang::Type::Vector: {
3884 uint32_t vector_type_flags = eTypeHasChildren | eTypeIsVector;
3885 const clang::VectorType *vector_type = llvm::dyn_cast<clang::VectorType>(
3886 qual_type->getCanonicalTypeInternal());
3887 if (vector_type) {
3888 if (vector_type->isIntegerType())
3889 vector_type_flags |= eTypeIsFloat;
3890 else if (vector_type->isFloatingType())
3891 vector_type_flags |= eTypeIsInteger;
3892 }
3893 return vector_type_flags;
3894 }
3895 default:
3896 return 0;
3897 }
3898 return 0;
3899 }
3900
3901 lldb::LanguageType
GetMinimumLanguage(lldb::opaque_compiler_type_t type)3902 TypeSystemClang::GetMinimumLanguage(lldb::opaque_compiler_type_t type) {
3903 if (!type)
3904 return lldb::eLanguageTypeC;
3905
3906 // If the type is a reference, then resolve it to what it refers to first:
3907 clang::QualType qual_type(GetCanonicalQualType(type).getNonReferenceType());
3908 if (qual_type->isAnyPointerType()) {
3909 if (qual_type->isObjCObjectPointerType())
3910 return lldb::eLanguageTypeObjC;
3911 if (qual_type->getPointeeCXXRecordDecl())
3912 return lldb::eLanguageTypeC_plus_plus;
3913
3914 clang::QualType pointee_type(qual_type->getPointeeType());
3915 if (pointee_type->getPointeeCXXRecordDecl())
3916 return lldb::eLanguageTypeC_plus_plus;
3917 if (pointee_type->isObjCObjectOrInterfaceType())
3918 return lldb::eLanguageTypeObjC;
3919 if (pointee_type->isObjCClassType())
3920 return lldb::eLanguageTypeObjC;
3921 if (pointee_type.getTypePtr() ==
3922 getASTContext().ObjCBuiltinIdTy.getTypePtr())
3923 return lldb::eLanguageTypeObjC;
3924 } else {
3925 if (qual_type->isObjCObjectOrInterfaceType())
3926 return lldb::eLanguageTypeObjC;
3927 if (qual_type->getAsCXXRecordDecl())
3928 return lldb::eLanguageTypeC_plus_plus;
3929 switch (qual_type->getTypeClass()) {
3930 default:
3931 break;
3932 case clang::Type::Builtin:
3933 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3934 default:
3935 case clang::BuiltinType::Void:
3936 case clang::BuiltinType::Bool:
3937 case clang::BuiltinType::Char_U:
3938 case clang::BuiltinType::UChar:
3939 case clang::BuiltinType::WChar_U:
3940 case clang::BuiltinType::Char16:
3941 case clang::BuiltinType::Char32:
3942 case clang::BuiltinType::UShort:
3943 case clang::BuiltinType::UInt:
3944 case clang::BuiltinType::ULong:
3945 case clang::BuiltinType::ULongLong:
3946 case clang::BuiltinType::UInt128:
3947 case clang::BuiltinType::Char_S:
3948 case clang::BuiltinType::SChar:
3949 case clang::BuiltinType::WChar_S:
3950 case clang::BuiltinType::Short:
3951 case clang::BuiltinType::Int:
3952 case clang::BuiltinType::Long:
3953 case clang::BuiltinType::LongLong:
3954 case clang::BuiltinType::Int128:
3955 case clang::BuiltinType::Float:
3956 case clang::BuiltinType::Double:
3957 case clang::BuiltinType::LongDouble:
3958 break;
3959
3960 case clang::BuiltinType::NullPtr:
3961 return eLanguageTypeC_plus_plus;
3962
3963 case clang::BuiltinType::ObjCId:
3964 case clang::BuiltinType::ObjCClass:
3965 case clang::BuiltinType::ObjCSel:
3966 return eLanguageTypeObjC;
3967
3968 case clang::BuiltinType::Dependent:
3969 case clang::BuiltinType::Overload:
3970 case clang::BuiltinType::BoundMember:
3971 case clang::BuiltinType::UnknownAny:
3972 break;
3973 }
3974 break;
3975 case clang::Type::Typedef:
3976 return GetType(llvm::cast<clang::TypedefType>(qual_type)
3977 ->getDecl()
3978 ->getUnderlyingType())
3979 .GetMinimumLanguage();
3980 }
3981 }
3982 return lldb::eLanguageTypeC;
3983 }
3984
3985 lldb::TypeClass
GetTypeClass(lldb::opaque_compiler_type_t type)3986 TypeSystemClang::GetTypeClass(lldb::opaque_compiler_type_t type) {
3987 if (!type)
3988 return lldb::eTypeClassInvalid;
3989
3990 clang::QualType qual_type =
3991 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
3992
3993 switch (qual_type->getTypeClass()) {
3994 case clang::Type::Atomic:
3995 case clang::Type::Auto:
3996 case clang::Type::Decltype:
3997 case clang::Type::Elaborated:
3998 case clang::Type::Paren:
3999 case clang::Type::TypeOf:
4000 case clang::Type::TypeOfExpr:
4001 llvm_unreachable("Handled in RemoveWrappingTypes!");
4002 case clang::Type::UnaryTransform:
4003 break;
4004 case clang::Type::FunctionNoProto:
4005 return lldb::eTypeClassFunction;
4006 case clang::Type::FunctionProto:
4007 return lldb::eTypeClassFunction;
4008 case clang::Type::IncompleteArray:
4009 return lldb::eTypeClassArray;
4010 case clang::Type::VariableArray:
4011 return lldb::eTypeClassArray;
4012 case clang::Type::ConstantArray:
4013 return lldb::eTypeClassArray;
4014 case clang::Type::DependentSizedArray:
4015 return lldb::eTypeClassArray;
4016 case clang::Type::DependentSizedExtVector:
4017 return lldb::eTypeClassVector;
4018 case clang::Type::DependentVector:
4019 return lldb::eTypeClassVector;
4020 case clang::Type::ExtVector:
4021 return lldb::eTypeClassVector;
4022 case clang::Type::Vector:
4023 return lldb::eTypeClassVector;
4024 case clang::Type::Builtin:
4025 // Ext-Int is just an integer type.
4026 case clang::Type::ExtInt:
4027 case clang::Type::DependentExtInt:
4028 return lldb::eTypeClassBuiltin;
4029 case clang::Type::ObjCObjectPointer:
4030 return lldb::eTypeClassObjCObjectPointer;
4031 case clang::Type::BlockPointer:
4032 return lldb::eTypeClassBlockPointer;
4033 case clang::Type::Pointer:
4034 return lldb::eTypeClassPointer;
4035 case clang::Type::LValueReference:
4036 return lldb::eTypeClassReference;
4037 case clang::Type::RValueReference:
4038 return lldb::eTypeClassReference;
4039 case clang::Type::MemberPointer:
4040 return lldb::eTypeClassMemberPointer;
4041 case clang::Type::Complex:
4042 if (qual_type->isComplexType())
4043 return lldb::eTypeClassComplexFloat;
4044 else
4045 return lldb::eTypeClassComplexInteger;
4046 case clang::Type::ObjCObject:
4047 return lldb::eTypeClassObjCObject;
4048 case clang::Type::ObjCInterface:
4049 return lldb::eTypeClassObjCInterface;
4050 case clang::Type::Record: {
4051 const clang::RecordType *record_type =
4052 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4053 const clang::RecordDecl *record_decl = record_type->getDecl();
4054 if (record_decl->isUnion())
4055 return lldb::eTypeClassUnion;
4056 else if (record_decl->isStruct())
4057 return lldb::eTypeClassStruct;
4058 else
4059 return lldb::eTypeClassClass;
4060 } break;
4061 case clang::Type::Enum:
4062 return lldb::eTypeClassEnumeration;
4063 case clang::Type::Typedef:
4064 return lldb::eTypeClassTypedef;
4065 case clang::Type::UnresolvedUsing:
4066 break;
4067
4068 case clang::Type::Attributed:
4069 break;
4070 case clang::Type::TemplateTypeParm:
4071 break;
4072 case clang::Type::SubstTemplateTypeParm:
4073 break;
4074 case clang::Type::SubstTemplateTypeParmPack:
4075 break;
4076 case clang::Type::InjectedClassName:
4077 break;
4078 case clang::Type::DependentName:
4079 break;
4080 case clang::Type::DependentTemplateSpecialization:
4081 break;
4082 case clang::Type::PackExpansion:
4083 break;
4084
4085 case clang::Type::TemplateSpecialization:
4086 break;
4087 case clang::Type::DeducedTemplateSpecialization:
4088 break;
4089 case clang::Type::Pipe:
4090 break;
4091
4092 // pointer type decayed from an array or function type.
4093 case clang::Type::Decayed:
4094 break;
4095 case clang::Type::Adjusted:
4096 break;
4097 case clang::Type::ObjCTypeParam:
4098 break;
4099
4100 case clang::Type::DependentAddressSpace:
4101 break;
4102 case clang::Type::MacroQualified:
4103 break;
4104
4105 // Matrix types that we're not sure how to display at the moment.
4106 case clang::Type::ConstantMatrix:
4107 case clang::Type::DependentSizedMatrix:
4108 break;
4109 }
4110 // We don't know hot to display this type...
4111 return lldb::eTypeClassOther;
4112 }
4113
GetTypeQualifiers(lldb::opaque_compiler_type_t type)4114 unsigned TypeSystemClang::GetTypeQualifiers(lldb::opaque_compiler_type_t type) {
4115 if (type)
4116 return GetQualType(type).getQualifiers().getCVRQualifiers();
4117 return 0;
4118 }
4119
4120 // Creating related types
4121
4122 CompilerType
GetArrayElementType(lldb::opaque_compiler_type_t type,ExecutionContextScope * exe_scope)4123 TypeSystemClang::GetArrayElementType(lldb::opaque_compiler_type_t type,
4124 ExecutionContextScope *exe_scope) {
4125 if (type) {
4126 clang::QualType qual_type(GetQualType(type));
4127
4128 const clang::Type *array_eletype =
4129 qual_type.getTypePtr()->getArrayElementTypeNoTypeQual();
4130
4131 if (!array_eletype)
4132 return CompilerType();
4133
4134 return GetType(clang::QualType(array_eletype, 0));
4135 }
4136 return CompilerType();
4137 }
4138
GetArrayType(lldb::opaque_compiler_type_t type,uint64_t size)4139 CompilerType TypeSystemClang::GetArrayType(lldb::opaque_compiler_type_t type,
4140 uint64_t size) {
4141 if (type) {
4142 clang::QualType qual_type(GetCanonicalQualType(type));
4143 clang::ASTContext &ast_ctx = getASTContext();
4144 if (size != 0)
4145 return GetType(ast_ctx.getConstantArrayType(
4146 qual_type, llvm::APInt(64, size), nullptr,
4147 clang::ArrayType::ArraySizeModifier::Normal, 0));
4148 else
4149 return GetType(ast_ctx.getIncompleteArrayType(
4150 qual_type, clang::ArrayType::ArraySizeModifier::Normal, 0));
4151 }
4152
4153 return CompilerType();
4154 }
4155
4156 CompilerType
GetCanonicalType(lldb::opaque_compiler_type_t type)4157 TypeSystemClang::GetCanonicalType(lldb::opaque_compiler_type_t type) {
4158 if (type)
4159 return GetType(GetCanonicalQualType(type));
4160 return CompilerType();
4161 }
4162
GetFullyUnqualifiedType_Impl(clang::ASTContext * ast,clang::QualType qual_type)4163 static clang::QualType GetFullyUnqualifiedType_Impl(clang::ASTContext *ast,
4164 clang::QualType qual_type) {
4165 if (qual_type->isPointerType())
4166 qual_type = ast->getPointerType(
4167 GetFullyUnqualifiedType_Impl(ast, qual_type->getPointeeType()));
4168 else
4169 qual_type = qual_type.getUnqualifiedType();
4170 qual_type.removeLocalConst();
4171 qual_type.removeLocalRestrict();
4172 qual_type.removeLocalVolatile();
4173 return qual_type;
4174 }
4175
4176 CompilerType
GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type)4177 TypeSystemClang::GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) {
4178 if (type)
4179 return GetType(
4180 GetFullyUnqualifiedType_Impl(&getASTContext(), GetQualType(type)));
4181 return CompilerType();
4182 }
4183
GetFunctionArgumentCount(lldb::opaque_compiler_type_t type)4184 int TypeSystemClang::GetFunctionArgumentCount(
4185 lldb::opaque_compiler_type_t type) {
4186 if (type) {
4187 const clang::FunctionProtoType *func =
4188 llvm::dyn_cast<clang::FunctionProtoType>(GetCanonicalQualType(type));
4189 if (func)
4190 return func->getNumParams();
4191 }
4192 return -1;
4193 }
4194
GetFunctionArgumentTypeAtIndex(lldb::opaque_compiler_type_t type,size_t idx)4195 CompilerType TypeSystemClang::GetFunctionArgumentTypeAtIndex(
4196 lldb::opaque_compiler_type_t type, size_t idx) {
4197 if (type) {
4198 const clang::FunctionProtoType *func =
4199 llvm::dyn_cast<clang::FunctionProtoType>(GetQualType(type));
4200 if (func) {
4201 const uint32_t num_args = func->getNumParams();
4202 if (idx < num_args)
4203 return GetType(func->getParamType(idx));
4204 }
4205 }
4206 return CompilerType();
4207 }
4208
4209 CompilerType
GetFunctionReturnType(lldb::opaque_compiler_type_t type)4210 TypeSystemClang::GetFunctionReturnType(lldb::opaque_compiler_type_t type) {
4211 if (type) {
4212 clang::QualType qual_type(GetQualType(type));
4213 const clang::FunctionProtoType *func =
4214 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
4215 if (func)
4216 return GetType(func->getReturnType());
4217 }
4218 return CompilerType();
4219 }
4220
4221 size_t
GetNumMemberFunctions(lldb::opaque_compiler_type_t type)4222 TypeSystemClang::GetNumMemberFunctions(lldb::opaque_compiler_type_t type) {
4223 size_t num_functions = 0;
4224 if (type) {
4225 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4226 switch (qual_type->getTypeClass()) {
4227 case clang::Type::Record:
4228 if (GetCompleteQualType(&getASTContext(), qual_type)) {
4229 const clang::RecordType *record_type =
4230 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4231 const clang::RecordDecl *record_decl = record_type->getDecl();
4232 assert(record_decl);
4233 const clang::CXXRecordDecl *cxx_record_decl =
4234 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4235 if (cxx_record_decl)
4236 num_functions = std::distance(cxx_record_decl->method_begin(),
4237 cxx_record_decl->method_end());
4238 }
4239 break;
4240
4241 case clang::Type::ObjCObjectPointer: {
4242 const clang::ObjCObjectPointerType *objc_class_type =
4243 qual_type->getAs<clang::ObjCObjectPointerType>();
4244 const clang::ObjCInterfaceType *objc_interface_type =
4245 objc_class_type->getInterfaceType();
4246 if (objc_interface_type &&
4247 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4248 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4249 clang::ObjCInterfaceDecl *class_interface_decl =
4250 objc_interface_type->getDecl();
4251 if (class_interface_decl) {
4252 num_functions = std::distance(class_interface_decl->meth_begin(),
4253 class_interface_decl->meth_end());
4254 }
4255 }
4256 break;
4257 }
4258
4259 case clang::Type::ObjCObject:
4260 case clang::Type::ObjCInterface:
4261 if (GetCompleteType(type)) {
4262 const clang::ObjCObjectType *objc_class_type =
4263 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4264 if (objc_class_type) {
4265 clang::ObjCInterfaceDecl *class_interface_decl =
4266 objc_class_type->getInterface();
4267 if (class_interface_decl)
4268 num_functions = std::distance(class_interface_decl->meth_begin(),
4269 class_interface_decl->meth_end());
4270 }
4271 }
4272 break;
4273
4274 default:
4275 break;
4276 }
4277 }
4278 return num_functions;
4279 }
4280
4281 TypeMemberFunctionImpl
GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type,size_t idx)4282 TypeSystemClang::GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type,
4283 size_t idx) {
4284 std::string name;
4285 MemberFunctionKind kind(MemberFunctionKind::eMemberFunctionKindUnknown);
4286 CompilerType clang_type;
4287 CompilerDecl clang_decl;
4288 if (type) {
4289 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4290 switch (qual_type->getTypeClass()) {
4291 case clang::Type::Record:
4292 if (GetCompleteQualType(&getASTContext(), qual_type)) {
4293 const clang::RecordType *record_type =
4294 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4295 const clang::RecordDecl *record_decl = record_type->getDecl();
4296 assert(record_decl);
4297 const clang::CXXRecordDecl *cxx_record_decl =
4298 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4299 if (cxx_record_decl) {
4300 auto method_iter = cxx_record_decl->method_begin();
4301 auto method_end = cxx_record_decl->method_end();
4302 if (idx <
4303 static_cast<size_t>(std::distance(method_iter, method_end))) {
4304 std::advance(method_iter, idx);
4305 clang::CXXMethodDecl *cxx_method_decl =
4306 method_iter->getCanonicalDecl();
4307 if (cxx_method_decl) {
4308 name = cxx_method_decl->getDeclName().getAsString();
4309 if (cxx_method_decl->isStatic())
4310 kind = lldb::eMemberFunctionKindStaticMethod;
4311 else if (llvm::isa<clang::CXXConstructorDecl>(cxx_method_decl))
4312 kind = lldb::eMemberFunctionKindConstructor;
4313 else if (llvm::isa<clang::CXXDestructorDecl>(cxx_method_decl))
4314 kind = lldb::eMemberFunctionKindDestructor;
4315 else
4316 kind = lldb::eMemberFunctionKindInstanceMethod;
4317 clang_type = GetType(cxx_method_decl->getType());
4318 clang_decl = GetCompilerDecl(cxx_method_decl);
4319 }
4320 }
4321 }
4322 }
4323 break;
4324
4325 case clang::Type::ObjCObjectPointer: {
4326 const clang::ObjCObjectPointerType *objc_class_type =
4327 qual_type->getAs<clang::ObjCObjectPointerType>();
4328 const clang::ObjCInterfaceType *objc_interface_type =
4329 objc_class_type->getInterfaceType();
4330 if (objc_interface_type &&
4331 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4332 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4333 clang::ObjCInterfaceDecl *class_interface_decl =
4334 objc_interface_type->getDecl();
4335 if (class_interface_decl) {
4336 auto method_iter = class_interface_decl->meth_begin();
4337 auto method_end = class_interface_decl->meth_end();
4338 if (idx <
4339 static_cast<size_t>(std::distance(method_iter, method_end))) {
4340 std::advance(method_iter, idx);
4341 clang::ObjCMethodDecl *objc_method_decl =
4342 method_iter->getCanonicalDecl();
4343 if (objc_method_decl) {
4344 clang_decl = GetCompilerDecl(objc_method_decl);
4345 name = objc_method_decl->getSelector().getAsString();
4346 if (objc_method_decl->isClassMethod())
4347 kind = lldb::eMemberFunctionKindStaticMethod;
4348 else
4349 kind = lldb::eMemberFunctionKindInstanceMethod;
4350 }
4351 }
4352 }
4353 }
4354 break;
4355 }
4356
4357 case clang::Type::ObjCObject:
4358 case clang::Type::ObjCInterface:
4359 if (GetCompleteType(type)) {
4360 const clang::ObjCObjectType *objc_class_type =
4361 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4362 if (objc_class_type) {
4363 clang::ObjCInterfaceDecl *class_interface_decl =
4364 objc_class_type->getInterface();
4365 if (class_interface_decl) {
4366 auto method_iter = class_interface_decl->meth_begin();
4367 auto method_end = class_interface_decl->meth_end();
4368 if (idx <
4369 static_cast<size_t>(std::distance(method_iter, method_end))) {
4370 std::advance(method_iter, idx);
4371 clang::ObjCMethodDecl *objc_method_decl =
4372 method_iter->getCanonicalDecl();
4373 if (objc_method_decl) {
4374 clang_decl = GetCompilerDecl(objc_method_decl);
4375 name = objc_method_decl->getSelector().getAsString();
4376 if (objc_method_decl->isClassMethod())
4377 kind = lldb::eMemberFunctionKindStaticMethod;
4378 else
4379 kind = lldb::eMemberFunctionKindInstanceMethod;
4380 }
4381 }
4382 }
4383 }
4384 }
4385 break;
4386
4387 default:
4388 break;
4389 }
4390 }
4391
4392 if (kind == eMemberFunctionKindUnknown)
4393 return TypeMemberFunctionImpl();
4394 else
4395 return TypeMemberFunctionImpl(clang_type, clang_decl, name, kind);
4396 }
4397
4398 CompilerType
GetNonReferenceType(lldb::opaque_compiler_type_t type)4399 TypeSystemClang::GetNonReferenceType(lldb::opaque_compiler_type_t type) {
4400 if (type)
4401 return GetType(GetQualType(type).getNonReferenceType());
4402 return CompilerType();
4403 }
4404
CreateTypedefType(const CompilerType & type,const char * typedef_name,const CompilerDeclContext & compiler_decl_ctx,uint32_t payload)4405 CompilerType TypeSystemClang::CreateTypedefType(
4406 const CompilerType &type, const char *typedef_name,
4407 const CompilerDeclContext &compiler_decl_ctx, uint32_t payload) {
4408 if (type && typedef_name && typedef_name[0]) {
4409 TypeSystemClang *ast =
4410 llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
4411 if (!ast)
4412 return CompilerType();
4413 clang::ASTContext &clang_ast = ast->getASTContext();
4414 clang::QualType qual_type(ClangUtil::GetQualType(type));
4415
4416 clang::DeclContext *decl_ctx =
4417 TypeSystemClang::DeclContextGetAsDeclContext(compiler_decl_ctx);
4418 if (!decl_ctx)
4419 decl_ctx = ast->getASTContext().getTranslationUnitDecl();
4420
4421 clang::TypedefDecl *decl =
4422 clang::TypedefDecl::CreateDeserialized(clang_ast, 0);
4423 decl->setDeclContext(decl_ctx);
4424 decl->setDeclName(&clang_ast.Idents.get(typedef_name));
4425 decl->setTypeSourceInfo(clang_ast.getTrivialTypeSourceInfo(qual_type));
4426
4427 SetOwningModule(decl, TypePayloadClang(payload).GetOwningModule());
4428 decl->setAccess(clang::AS_public); // TODO respect proper access specifier
4429
4430 decl_ctx->addDecl(decl);
4431
4432 // Get a uniqued clang::QualType for the typedef decl type
4433 return ast->GetType(clang_ast.getTypedefType(decl));
4434 }
4435 return CompilerType();
4436 }
4437
4438 CompilerType
GetPointeeType(lldb::opaque_compiler_type_t type)4439 TypeSystemClang::GetPointeeType(lldb::opaque_compiler_type_t type) {
4440 if (type) {
4441 clang::QualType qual_type(GetQualType(type));
4442 return GetType(qual_type.getTypePtr()->getPointeeType());
4443 }
4444 return CompilerType();
4445 }
4446
4447 CompilerType
GetPointerType(lldb::opaque_compiler_type_t type)4448 TypeSystemClang::GetPointerType(lldb::opaque_compiler_type_t type) {
4449 if (type) {
4450 clang::QualType qual_type(GetQualType(type));
4451
4452 switch (qual_type.getDesugaredType(getASTContext())->getTypeClass()) {
4453 case clang::Type::ObjCObject:
4454 case clang::Type::ObjCInterface:
4455 return GetType(getASTContext().getObjCObjectPointerType(qual_type));
4456
4457 default:
4458 return GetType(getASTContext().getPointerType(qual_type));
4459 }
4460 }
4461 return CompilerType();
4462 }
4463
4464 CompilerType
GetLValueReferenceType(lldb::opaque_compiler_type_t type)4465 TypeSystemClang::GetLValueReferenceType(lldb::opaque_compiler_type_t type) {
4466 if (type)
4467 return GetType(getASTContext().getLValueReferenceType(GetQualType(type)));
4468 else
4469 return CompilerType();
4470 }
4471
4472 CompilerType
GetRValueReferenceType(lldb::opaque_compiler_type_t type)4473 TypeSystemClang::GetRValueReferenceType(lldb::opaque_compiler_type_t type) {
4474 if (type)
4475 return GetType(getASTContext().getRValueReferenceType(GetQualType(type)));
4476 else
4477 return CompilerType();
4478 }
4479
GetAtomicType(lldb::opaque_compiler_type_t type)4480 CompilerType TypeSystemClang::GetAtomicType(lldb::opaque_compiler_type_t type) {
4481 if (!type)
4482 return CompilerType();
4483 return GetType(getASTContext().getAtomicType(GetQualType(type)));
4484 }
4485
4486 CompilerType
AddConstModifier(lldb::opaque_compiler_type_t type)4487 TypeSystemClang::AddConstModifier(lldb::opaque_compiler_type_t type) {
4488 if (type) {
4489 clang::QualType result(GetQualType(type));
4490 result.addConst();
4491 return GetType(result);
4492 }
4493 return CompilerType();
4494 }
4495
4496 CompilerType
AddVolatileModifier(lldb::opaque_compiler_type_t type)4497 TypeSystemClang::AddVolatileModifier(lldb::opaque_compiler_type_t type) {
4498 if (type) {
4499 clang::QualType result(GetQualType(type));
4500 result.addVolatile();
4501 return GetType(result);
4502 }
4503 return CompilerType();
4504 }
4505
4506 CompilerType
AddRestrictModifier(lldb::opaque_compiler_type_t type)4507 TypeSystemClang::AddRestrictModifier(lldb::opaque_compiler_type_t type) {
4508 if (type) {
4509 clang::QualType result(GetQualType(type));
4510 result.addRestrict();
4511 return GetType(result);
4512 }
4513 return CompilerType();
4514 }
4515
CreateTypedef(lldb::opaque_compiler_type_t type,const char * typedef_name,const CompilerDeclContext & compiler_decl_ctx,uint32_t payload)4516 CompilerType TypeSystemClang::CreateTypedef(
4517 lldb::opaque_compiler_type_t type, const char *typedef_name,
4518 const CompilerDeclContext &compiler_decl_ctx, uint32_t payload) {
4519 if (type) {
4520 clang::ASTContext &clang_ast = getASTContext();
4521 clang::QualType qual_type(GetQualType(type));
4522
4523 clang::DeclContext *decl_ctx =
4524 TypeSystemClang::DeclContextGetAsDeclContext(compiler_decl_ctx);
4525 if (!decl_ctx)
4526 decl_ctx = getASTContext().getTranslationUnitDecl();
4527
4528 clang::TypedefDecl *decl = clang::TypedefDecl::Create(
4529 clang_ast, decl_ctx, clang::SourceLocation(), clang::SourceLocation(),
4530 &clang_ast.Idents.get(typedef_name),
4531 clang_ast.getTrivialTypeSourceInfo(qual_type));
4532 decl_ctx->addDecl(decl);
4533 SetOwningModule(decl, TypePayloadClang(payload).GetOwningModule());
4534
4535 clang::TagDecl *tdecl = nullptr;
4536 if (!qual_type.isNull()) {
4537 if (const clang::RecordType *rt = qual_type->getAs<clang::RecordType>())
4538 tdecl = rt->getDecl();
4539 if (const clang::EnumType *et = qual_type->getAs<clang::EnumType>())
4540 tdecl = et->getDecl();
4541 }
4542
4543 // Check whether this declaration is an anonymous struct, union, or enum,
4544 // hidden behind a typedef. If so, we try to check whether we have a
4545 // typedef tag to attach to the original record declaration
4546 if (tdecl && !tdecl->getIdentifier() && !tdecl->getTypedefNameForAnonDecl())
4547 tdecl->setTypedefNameForAnonDecl(decl);
4548
4549 decl->setAccess(clang::AS_public); // TODO respect proper access specifier
4550
4551 // Get a uniqued clang::QualType for the typedef decl type
4552 return GetType(clang_ast.getTypedefType(decl));
4553 }
4554 return CompilerType();
4555 }
4556
4557 CompilerType
GetTypedefedType(lldb::opaque_compiler_type_t type)4558 TypeSystemClang::GetTypedefedType(lldb::opaque_compiler_type_t type) {
4559 if (type) {
4560 const clang::TypedefType *typedef_type = llvm::dyn_cast<clang::TypedefType>(
4561 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}));
4562 if (typedef_type)
4563 return GetType(typedef_type->getDecl()->getUnderlyingType());
4564 }
4565 return CompilerType();
4566 }
4567
4568 // Create related types using the current type's AST
4569
GetBasicTypeFromAST(lldb::BasicType basic_type)4570 CompilerType TypeSystemClang::GetBasicTypeFromAST(lldb::BasicType basic_type) {
4571 return TypeSystemClang::GetBasicType(basic_type);
4572 }
4573 // Exploring the type
4574
4575 const llvm::fltSemantics &
GetFloatTypeSemantics(size_t byte_size)4576 TypeSystemClang::GetFloatTypeSemantics(size_t byte_size) {
4577 clang::ASTContext &ast = getASTContext();
4578 const size_t bit_size = byte_size * 8;
4579 if (bit_size == ast.getTypeSize(ast.FloatTy))
4580 return ast.getFloatTypeSemantics(ast.FloatTy);
4581 else if (bit_size == ast.getTypeSize(ast.DoubleTy))
4582 return ast.getFloatTypeSemantics(ast.DoubleTy);
4583 else if (bit_size == ast.getTypeSize(ast.LongDoubleTy))
4584 return ast.getFloatTypeSemantics(ast.LongDoubleTy);
4585 else if (bit_size == ast.getTypeSize(ast.HalfTy))
4586 return ast.getFloatTypeSemantics(ast.HalfTy);
4587 return llvm::APFloatBase::Bogus();
4588 }
4589
4590 Optional<uint64_t>
GetBitSize(lldb::opaque_compiler_type_t type,ExecutionContextScope * exe_scope)4591 TypeSystemClang::GetBitSize(lldb::opaque_compiler_type_t type,
4592 ExecutionContextScope *exe_scope) {
4593 if (GetCompleteType(type)) {
4594 clang::QualType qual_type(GetCanonicalQualType(type));
4595 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4596 switch (type_class) {
4597 case clang::Type::Record:
4598 if (GetCompleteType(type))
4599 return getASTContext().getTypeSize(qual_type);
4600 else
4601 return None;
4602 break;
4603
4604 case clang::Type::ObjCInterface:
4605 case clang::Type::ObjCObject: {
4606 ExecutionContext exe_ctx(exe_scope);
4607 Process *process = exe_ctx.GetProcessPtr();
4608 if (process) {
4609 ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process);
4610 if (objc_runtime) {
4611 uint64_t bit_size = 0;
4612 if (objc_runtime->GetTypeBitSize(GetType(qual_type), bit_size))
4613 return bit_size;
4614 }
4615 } else {
4616 static bool g_printed = false;
4617 if (!g_printed) {
4618 StreamString s;
4619 DumpTypeDescription(type, &s);
4620
4621 llvm::outs() << "warning: trying to determine the size of type ";
4622 llvm::outs() << s.GetString() << "\n";
4623 llvm::outs() << "without a valid ExecutionContext. this is not "
4624 "reliable. please file a bug against LLDB.\n";
4625 llvm::outs() << "backtrace:\n";
4626 llvm::sys::PrintStackTrace(llvm::outs());
4627 llvm::outs() << "\n";
4628 g_printed = true;
4629 }
4630 }
4631 }
4632 LLVM_FALLTHROUGH;
4633 default:
4634 const uint32_t bit_size = getASTContext().getTypeSize(qual_type);
4635 if (bit_size == 0) {
4636 if (qual_type->isIncompleteArrayType())
4637 return getASTContext().getTypeSize(
4638 qual_type->getArrayElementTypeNoTypeQual()
4639 ->getCanonicalTypeUnqualified());
4640 }
4641 if (qual_type->isObjCObjectOrInterfaceType())
4642 return bit_size +
4643 getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy);
4644 // Function types actually have a size of 0, that's not an error.
4645 if (qual_type->isFunctionProtoType())
4646 return bit_size;
4647 if (bit_size)
4648 return bit_size;
4649 }
4650 }
4651 return None;
4652 }
4653
4654 llvm::Optional<size_t>
GetTypeBitAlign(lldb::opaque_compiler_type_t type,ExecutionContextScope * exe_scope)4655 TypeSystemClang::GetTypeBitAlign(lldb::opaque_compiler_type_t type,
4656 ExecutionContextScope *exe_scope) {
4657 if (GetCompleteType(type))
4658 return getASTContext().getTypeAlign(GetQualType(type));
4659 return {};
4660 }
4661
GetEncoding(lldb::opaque_compiler_type_t type,uint64_t & count)4662 lldb::Encoding TypeSystemClang::GetEncoding(lldb::opaque_compiler_type_t type,
4663 uint64_t &count) {
4664 if (!type)
4665 return lldb::eEncodingInvalid;
4666
4667 count = 1;
4668 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4669
4670 switch (qual_type->getTypeClass()) {
4671 case clang::Type::Atomic:
4672 case clang::Type::Auto:
4673 case clang::Type::Decltype:
4674 case clang::Type::Elaborated:
4675 case clang::Type::Paren:
4676 case clang::Type::Typedef:
4677 case clang::Type::TypeOf:
4678 case clang::Type::TypeOfExpr:
4679 llvm_unreachable("Handled in RemoveWrappingTypes!");
4680
4681 case clang::Type::UnaryTransform:
4682 break;
4683
4684 case clang::Type::FunctionNoProto:
4685 case clang::Type::FunctionProto:
4686 break;
4687
4688 case clang::Type::IncompleteArray:
4689 case clang::Type::VariableArray:
4690 break;
4691
4692 case clang::Type::ConstantArray:
4693 break;
4694
4695 case clang::Type::DependentVector:
4696 case clang::Type::ExtVector:
4697 case clang::Type::Vector:
4698 // TODO: Set this to more than one???
4699 break;
4700
4701 case clang::Type::ExtInt:
4702 case clang::Type::DependentExtInt:
4703 return qual_type->isUnsignedIntegerType() ? lldb::eEncodingUint
4704 : lldb::eEncodingSint;
4705
4706 case clang::Type::Builtin:
4707 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
4708 case clang::BuiltinType::Void:
4709 break;
4710
4711 case clang::BuiltinType::Bool:
4712 case clang::BuiltinType::Char_S:
4713 case clang::BuiltinType::SChar:
4714 case clang::BuiltinType::WChar_S:
4715 case clang::BuiltinType::Short:
4716 case clang::BuiltinType::Int:
4717 case clang::BuiltinType::Long:
4718 case clang::BuiltinType::LongLong:
4719 case clang::BuiltinType::Int128:
4720 return lldb::eEncodingSint;
4721
4722 case clang::BuiltinType::Char_U:
4723 case clang::BuiltinType::UChar:
4724 case clang::BuiltinType::WChar_U:
4725 case clang::BuiltinType::Char8:
4726 case clang::BuiltinType::Char16:
4727 case clang::BuiltinType::Char32:
4728 case clang::BuiltinType::UShort:
4729 case clang::BuiltinType::UInt:
4730 case clang::BuiltinType::ULong:
4731 case clang::BuiltinType::ULongLong:
4732 case clang::BuiltinType::UInt128:
4733 return lldb::eEncodingUint;
4734
4735 // Fixed point types. Note that they are currently ignored.
4736 case clang::BuiltinType::ShortAccum:
4737 case clang::BuiltinType::Accum:
4738 case clang::BuiltinType::LongAccum:
4739 case clang::BuiltinType::UShortAccum:
4740 case clang::BuiltinType::UAccum:
4741 case clang::BuiltinType::ULongAccum:
4742 case clang::BuiltinType::ShortFract:
4743 case clang::BuiltinType::Fract:
4744 case clang::BuiltinType::LongFract:
4745 case clang::BuiltinType::UShortFract:
4746 case clang::BuiltinType::UFract:
4747 case clang::BuiltinType::ULongFract:
4748 case clang::BuiltinType::SatShortAccum:
4749 case clang::BuiltinType::SatAccum:
4750 case clang::BuiltinType::SatLongAccum:
4751 case clang::BuiltinType::SatUShortAccum:
4752 case clang::BuiltinType::SatUAccum:
4753 case clang::BuiltinType::SatULongAccum:
4754 case clang::BuiltinType::SatShortFract:
4755 case clang::BuiltinType::SatFract:
4756 case clang::BuiltinType::SatLongFract:
4757 case clang::BuiltinType::SatUShortFract:
4758 case clang::BuiltinType::SatUFract:
4759 case clang::BuiltinType::SatULongFract:
4760 break;
4761
4762 case clang::BuiltinType::Half:
4763 case clang::BuiltinType::Float:
4764 case clang::BuiltinType::Float16:
4765 case clang::BuiltinType::Float128:
4766 case clang::BuiltinType::Double:
4767 case clang::BuiltinType::LongDouble:
4768 case clang::BuiltinType::BFloat16:
4769 return lldb::eEncodingIEEE754;
4770
4771 case clang::BuiltinType::ObjCClass:
4772 case clang::BuiltinType::ObjCId:
4773 case clang::BuiltinType::ObjCSel:
4774 return lldb::eEncodingUint;
4775
4776 case clang::BuiltinType::NullPtr:
4777 return lldb::eEncodingUint;
4778
4779 case clang::BuiltinType::Kind::ARCUnbridgedCast:
4780 case clang::BuiltinType::Kind::BoundMember:
4781 case clang::BuiltinType::Kind::BuiltinFn:
4782 case clang::BuiltinType::Kind::Dependent:
4783 case clang::BuiltinType::Kind::OCLClkEvent:
4784 case clang::BuiltinType::Kind::OCLEvent:
4785 case clang::BuiltinType::Kind::OCLImage1dRO:
4786 case clang::BuiltinType::Kind::OCLImage1dWO:
4787 case clang::BuiltinType::Kind::OCLImage1dRW:
4788 case clang::BuiltinType::Kind::OCLImage1dArrayRO:
4789 case clang::BuiltinType::Kind::OCLImage1dArrayWO:
4790 case clang::BuiltinType::Kind::OCLImage1dArrayRW:
4791 case clang::BuiltinType::Kind::OCLImage1dBufferRO:
4792 case clang::BuiltinType::Kind::OCLImage1dBufferWO:
4793 case clang::BuiltinType::Kind::OCLImage1dBufferRW:
4794 case clang::BuiltinType::Kind::OCLImage2dRO:
4795 case clang::BuiltinType::Kind::OCLImage2dWO:
4796 case clang::BuiltinType::Kind::OCLImage2dRW:
4797 case clang::BuiltinType::Kind::OCLImage2dArrayRO:
4798 case clang::BuiltinType::Kind::OCLImage2dArrayWO:
4799 case clang::BuiltinType::Kind::OCLImage2dArrayRW:
4800 case clang::BuiltinType::Kind::OCLImage2dArrayDepthRO:
4801 case clang::BuiltinType::Kind::OCLImage2dArrayDepthWO:
4802 case clang::BuiltinType::Kind::OCLImage2dArrayDepthRW:
4803 case clang::BuiltinType::Kind::OCLImage2dArrayMSAARO:
4804 case clang::BuiltinType::Kind::OCLImage2dArrayMSAAWO:
4805 case clang::BuiltinType::Kind::OCLImage2dArrayMSAARW:
4806 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRO:
4807 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthWO:
4808 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRW:
4809 case clang::BuiltinType::Kind::OCLImage2dDepthRO:
4810 case clang::BuiltinType::Kind::OCLImage2dDepthWO:
4811 case clang::BuiltinType::Kind::OCLImage2dDepthRW:
4812 case clang::BuiltinType::Kind::OCLImage2dMSAARO:
4813 case clang::BuiltinType::Kind::OCLImage2dMSAAWO:
4814 case clang::BuiltinType::Kind::OCLImage2dMSAARW:
4815 case clang::BuiltinType::Kind::OCLImage2dMSAADepthRO:
4816 case clang::BuiltinType::Kind::OCLImage2dMSAADepthWO:
4817 case clang::BuiltinType::Kind::OCLImage2dMSAADepthRW:
4818 case clang::BuiltinType::Kind::OCLImage3dRO:
4819 case clang::BuiltinType::Kind::OCLImage3dWO:
4820 case clang::BuiltinType::Kind::OCLImage3dRW:
4821 case clang::BuiltinType::Kind::OCLQueue:
4822 case clang::BuiltinType::Kind::OCLReserveID:
4823 case clang::BuiltinType::Kind::OCLSampler:
4824 case clang::BuiltinType::Kind::OMPArraySection:
4825 case clang::BuiltinType::Kind::OMPArrayShaping:
4826 case clang::BuiltinType::Kind::OMPIterator:
4827 case clang::BuiltinType::Kind::Overload:
4828 case clang::BuiltinType::Kind::PseudoObject:
4829 case clang::BuiltinType::Kind::UnknownAny:
4830 break;
4831
4832 case clang::BuiltinType::OCLIntelSubgroupAVCMcePayload:
4833 case clang::BuiltinType::OCLIntelSubgroupAVCImePayload:
4834 case clang::BuiltinType::OCLIntelSubgroupAVCRefPayload:
4835 case clang::BuiltinType::OCLIntelSubgroupAVCSicPayload:
4836 case clang::BuiltinType::OCLIntelSubgroupAVCMceResult:
4837 case clang::BuiltinType::OCLIntelSubgroupAVCImeResult:
4838 case clang::BuiltinType::OCLIntelSubgroupAVCRefResult:
4839 case clang::BuiltinType::OCLIntelSubgroupAVCSicResult:
4840 case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleRefStreamout:
4841 case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualRefStreamout:
4842 case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleRefStreamin:
4843 case clang::BuiltinType::OCLIntelSubgroupAVCImeDualRefStreamin:
4844 break;
4845
4846 // PowerPC -- Matrix Multiply Assist
4847 case clang::BuiltinType::VectorPair:
4848 case clang::BuiltinType::VectorQuad:
4849 break;
4850
4851 // ARM -- Scalable Vector Extension
4852 case clang::BuiltinType::SveBool:
4853 case clang::BuiltinType::SveInt8:
4854 case clang::BuiltinType::SveInt8x2:
4855 case clang::BuiltinType::SveInt8x3:
4856 case clang::BuiltinType::SveInt8x4:
4857 case clang::BuiltinType::SveInt16:
4858 case clang::BuiltinType::SveInt16x2:
4859 case clang::BuiltinType::SveInt16x3:
4860 case clang::BuiltinType::SveInt16x4:
4861 case clang::BuiltinType::SveInt32:
4862 case clang::BuiltinType::SveInt32x2:
4863 case clang::BuiltinType::SveInt32x3:
4864 case clang::BuiltinType::SveInt32x4:
4865 case clang::BuiltinType::SveInt64:
4866 case clang::BuiltinType::SveInt64x2:
4867 case clang::BuiltinType::SveInt64x3:
4868 case clang::BuiltinType::SveInt64x4:
4869 case clang::BuiltinType::SveUint8:
4870 case clang::BuiltinType::SveUint8x2:
4871 case clang::BuiltinType::SveUint8x3:
4872 case clang::BuiltinType::SveUint8x4:
4873 case clang::BuiltinType::SveUint16:
4874 case clang::BuiltinType::SveUint16x2:
4875 case clang::BuiltinType::SveUint16x3:
4876 case clang::BuiltinType::SveUint16x4:
4877 case clang::BuiltinType::SveUint32:
4878 case clang::BuiltinType::SveUint32x2:
4879 case clang::BuiltinType::SveUint32x3:
4880 case clang::BuiltinType::SveUint32x4:
4881 case clang::BuiltinType::SveUint64:
4882 case clang::BuiltinType::SveUint64x2:
4883 case clang::BuiltinType::SveUint64x3:
4884 case clang::BuiltinType::SveUint64x4:
4885 case clang::BuiltinType::SveFloat16:
4886 case clang::BuiltinType::SveBFloat16:
4887 case clang::BuiltinType::SveBFloat16x2:
4888 case clang::BuiltinType::SveBFloat16x3:
4889 case clang::BuiltinType::SveBFloat16x4:
4890 case clang::BuiltinType::SveFloat16x2:
4891 case clang::BuiltinType::SveFloat16x3:
4892 case clang::BuiltinType::SveFloat16x4:
4893 case clang::BuiltinType::SveFloat32:
4894 case clang::BuiltinType::SveFloat32x2:
4895 case clang::BuiltinType::SveFloat32x3:
4896 case clang::BuiltinType::SveFloat32x4:
4897 case clang::BuiltinType::SveFloat64:
4898 case clang::BuiltinType::SveFloat64x2:
4899 case clang::BuiltinType::SveFloat64x3:
4900 case clang::BuiltinType::SveFloat64x4:
4901 break;
4902
4903 case clang::BuiltinType::IncompleteMatrixIdx:
4904 break;
4905 }
4906 break;
4907 // All pointer types are represented as unsigned integer encodings. We may
4908 // nee to add a eEncodingPointer if we ever need to know the difference
4909 case clang::Type::ObjCObjectPointer:
4910 case clang::Type::BlockPointer:
4911 case clang::Type::Pointer:
4912 case clang::Type::LValueReference:
4913 case clang::Type::RValueReference:
4914 case clang::Type::MemberPointer:
4915 return lldb::eEncodingUint;
4916 case clang::Type::Complex: {
4917 lldb::Encoding encoding = lldb::eEncodingIEEE754;
4918 if (qual_type->isComplexType())
4919 encoding = lldb::eEncodingIEEE754;
4920 else {
4921 const clang::ComplexType *complex_type =
4922 qual_type->getAsComplexIntegerType();
4923 if (complex_type)
4924 encoding = GetType(complex_type->getElementType()).GetEncoding(count);
4925 else
4926 encoding = lldb::eEncodingSint;
4927 }
4928 count = 2;
4929 return encoding;
4930 }
4931
4932 case clang::Type::ObjCInterface:
4933 break;
4934 case clang::Type::Record:
4935 break;
4936 case clang::Type::Enum:
4937 return lldb::eEncodingSint;
4938 case clang::Type::DependentSizedArray:
4939 case clang::Type::DependentSizedExtVector:
4940 case clang::Type::UnresolvedUsing:
4941 case clang::Type::Attributed:
4942 case clang::Type::TemplateTypeParm:
4943 case clang::Type::SubstTemplateTypeParm:
4944 case clang::Type::SubstTemplateTypeParmPack:
4945 case clang::Type::InjectedClassName:
4946 case clang::Type::DependentName:
4947 case clang::Type::DependentTemplateSpecialization:
4948 case clang::Type::PackExpansion:
4949 case clang::Type::ObjCObject:
4950
4951 case clang::Type::TemplateSpecialization:
4952 case clang::Type::DeducedTemplateSpecialization:
4953 case clang::Type::Adjusted:
4954 case clang::Type::Pipe:
4955 break;
4956
4957 // pointer type decayed from an array or function type.
4958 case clang::Type::Decayed:
4959 break;
4960 case clang::Type::ObjCTypeParam:
4961 break;
4962
4963 case clang::Type::DependentAddressSpace:
4964 break;
4965 case clang::Type::MacroQualified:
4966 break;
4967
4968 case clang::Type::ConstantMatrix:
4969 case clang::Type::DependentSizedMatrix:
4970 break;
4971 }
4972 count = 0;
4973 return lldb::eEncodingInvalid;
4974 }
4975
GetFormat(lldb::opaque_compiler_type_t type)4976 lldb::Format TypeSystemClang::GetFormat(lldb::opaque_compiler_type_t type) {
4977 if (!type)
4978 return lldb::eFormatDefault;
4979
4980 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4981
4982 switch (qual_type->getTypeClass()) {
4983 case clang::Type::Atomic:
4984 case clang::Type::Auto:
4985 case clang::Type::Decltype:
4986 case clang::Type::Elaborated:
4987 case clang::Type::Paren:
4988 case clang::Type::Typedef:
4989 case clang::Type::TypeOf:
4990 case clang::Type::TypeOfExpr:
4991 llvm_unreachable("Handled in RemoveWrappingTypes!");
4992 case clang::Type::UnaryTransform:
4993 break;
4994
4995 case clang::Type::FunctionNoProto:
4996 case clang::Type::FunctionProto:
4997 break;
4998
4999 case clang::Type::IncompleteArray:
5000 case clang::Type::VariableArray:
5001 break;
5002
5003 case clang::Type::ConstantArray:
5004 return lldb::eFormatVoid; // no value
5005
5006 case clang::Type::DependentVector:
5007 case clang::Type::ExtVector:
5008 case clang::Type::Vector:
5009 break;
5010
5011 case clang::Type::ExtInt:
5012 case clang::Type::DependentExtInt:
5013 return qual_type->isUnsignedIntegerType() ? lldb::eFormatUnsigned
5014 : lldb::eFormatDecimal;
5015
5016 case clang::Type::Builtin:
5017 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5018 case clang::BuiltinType::UnknownAny:
5019 case clang::BuiltinType::Void:
5020 case clang::BuiltinType::BoundMember:
5021 break;
5022
5023 case clang::BuiltinType::Bool:
5024 return lldb::eFormatBoolean;
5025 case clang::BuiltinType::Char_S:
5026 case clang::BuiltinType::SChar:
5027 case clang::BuiltinType::WChar_S:
5028 case clang::BuiltinType::Char_U:
5029 case clang::BuiltinType::UChar:
5030 case clang::BuiltinType::WChar_U:
5031 return lldb::eFormatChar;
5032 case clang::BuiltinType::Char16:
5033 return lldb::eFormatUnicode16;
5034 case clang::BuiltinType::Char32:
5035 return lldb::eFormatUnicode32;
5036 case clang::BuiltinType::UShort:
5037 return lldb::eFormatUnsigned;
5038 case clang::BuiltinType::Short:
5039 return lldb::eFormatDecimal;
5040 case clang::BuiltinType::UInt:
5041 return lldb::eFormatUnsigned;
5042 case clang::BuiltinType::Int:
5043 return lldb::eFormatDecimal;
5044 case clang::BuiltinType::ULong:
5045 return lldb::eFormatUnsigned;
5046 case clang::BuiltinType::Long:
5047 return lldb::eFormatDecimal;
5048 case clang::BuiltinType::ULongLong:
5049 return lldb::eFormatUnsigned;
5050 case clang::BuiltinType::LongLong:
5051 return lldb::eFormatDecimal;
5052 case clang::BuiltinType::UInt128:
5053 return lldb::eFormatUnsigned;
5054 case clang::BuiltinType::Int128:
5055 return lldb::eFormatDecimal;
5056 case clang::BuiltinType::Half:
5057 case clang::BuiltinType::Float:
5058 case clang::BuiltinType::Double:
5059 case clang::BuiltinType::LongDouble:
5060 return lldb::eFormatFloat;
5061 default:
5062 return lldb::eFormatHex;
5063 }
5064 break;
5065 case clang::Type::ObjCObjectPointer:
5066 return lldb::eFormatHex;
5067 case clang::Type::BlockPointer:
5068 return lldb::eFormatHex;
5069 case clang::Type::Pointer:
5070 return lldb::eFormatHex;
5071 case clang::Type::LValueReference:
5072 case clang::Type::RValueReference:
5073 return lldb::eFormatHex;
5074 case clang::Type::MemberPointer:
5075 break;
5076 case clang::Type::Complex: {
5077 if (qual_type->isComplexType())
5078 return lldb::eFormatComplex;
5079 else
5080 return lldb::eFormatComplexInteger;
5081 }
5082 case clang::Type::ObjCInterface:
5083 break;
5084 case clang::Type::Record:
5085 break;
5086 case clang::Type::Enum:
5087 return lldb::eFormatEnum;
5088 case clang::Type::DependentSizedArray:
5089 case clang::Type::DependentSizedExtVector:
5090 case clang::Type::UnresolvedUsing:
5091 case clang::Type::Attributed:
5092 case clang::Type::TemplateTypeParm:
5093 case clang::Type::SubstTemplateTypeParm:
5094 case clang::Type::SubstTemplateTypeParmPack:
5095 case clang::Type::InjectedClassName:
5096 case clang::Type::DependentName:
5097 case clang::Type::DependentTemplateSpecialization:
5098 case clang::Type::PackExpansion:
5099 case clang::Type::ObjCObject:
5100
5101 case clang::Type::TemplateSpecialization:
5102 case clang::Type::DeducedTemplateSpecialization:
5103 case clang::Type::Adjusted:
5104 case clang::Type::Pipe:
5105 break;
5106
5107 // pointer type decayed from an array or function type.
5108 case clang::Type::Decayed:
5109 break;
5110 case clang::Type::ObjCTypeParam:
5111 break;
5112
5113 case clang::Type::DependentAddressSpace:
5114 break;
5115 case clang::Type::MacroQualified:
5116 break;
5117
5118 // Matrix types we're not sure how to display yet.
5119 case clang::Type::ConstantMatrix:
5120 case clang::Type::DependentSizedMatrix:
5121 break;
5122 }
5123 // We don't know hot to display this type...
5124 return lldb::eFormatBytes;
5125 }
5126
ObjCDeclHasIVars(clang::ObjCInterfaceDecl * class_interface_decl,bool check_superclass)5127 static bool ObjCDeclHasIVars(clang::ObjCInterfaceDecl *class_interface_decl,
5128 bool check_superclass) {
5129 while (class_interface_decl) {
5130 if (class_interface_decl->ivar_size() > 0)
5131 return true;
5132
5133 if (check_superclass)
5134 class_interface_decl = class_interface_decl->getSuperClass();
5135 else
5136 break;
5137 }
5138 return false;
5139 }
5140
5141 static Optional<SymbolFile::ArrayInfo>
GetDynamicArrayInfo(TypeSystemClang & ast,SymbolFile * sym_file,clang::QualType qual_type,const ExecutionContext * exe_ctx)5142 GetDynamicArrayInfo(TypeSystemClang &ast, SymbolFile *sym_file,
5143 clang::QualType qual_type,
5144 const ExecutionContext *exe_ctx) {
5145 if (qual_type->isIncompleteArrayType())
5146 if (auto *metadata = ast.GetMetadata(qual_type.getTypePtr()))
5147 return sym_file->GetDynamicArrayInfoForUID(metadata->GetUserID(),
5148 exe_ctx);
5149 return llvm::None;
5150 }
5151
GetNumChildren(lldb::opaque_compiler_type_t type,bool omit_empty_base_classes,const ExecutionContext * exe_ctx)5152 uint32_t TypeSystemClang::GetNumChildren(lldb::opaque_compiler_type_t type,
5153 bool omit_empty_base_classes,
5154 const ExecutionContext *exe_ctx) {
5155 if (!type)
5156 return 0;
5157
5158 uint32_t num_children = 0;
5159 clang::QualType qual_type(RemoveWrappingTypes(GetQualType(type)));
5160 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5161 switch (type_class) {
5162 case clang::Type::Builtin:
5163 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5164 case clang::BuiltinType::ObjCId: // child is Class
5165 case clang::BuiltinType::ObjCClass: // child is Class
5166 num_children = 1;
5167 break;
5168
5169 default:
5170 break;
5171 }
5172 break;
5173
5174 case clang::Type::Complex:
5175 return 0;
5176 case clang::Type::Record:
5177 if (GetCompleteQualType(&getASTContext(), qual_type)) {
5178 const clang::RecordType *record_type =
5179 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5180 const clang::RecordDecl *record_decl = record_type->getDecl();
5181 assert(record_decl);
5182 const clang::CXXRecordDecl *cxx_record_decl =
5183 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
5184 if (cxx_record_decl) {
5185 if (omit_empty_base_classes) {
5186 // Check each base classes to see if it or any of its base classes
5187 // contain any fields. This can help limit the noise in variable
5188 // views by not having to show base classes that contain no members.
5189 clang::CXXRecordDecl::base_class_const_iterator base_class,
5190 base_class_end;
5191 for (base_class = cxx_record_decl->bases_begin(),
5192 base_class_end = cxx_record_decl->bases_end();
5193 base_class != base_class_end; ++base_class) {
5194 const clang::CXXRecordDecl *base_class_decl =
5195 llvm::cast<clang::CXXRecordDecl>(
5196 base_class->getType()
5197 ->getAs<clang::RecordType>()
5198 ->getDecl());
5199
5200 // Skip empty base classes
5201 if (!TypeSystemClang::RecordHasFields(base_class_decl))
5202 continue;
5203
5204 num_children++;
5205 }
5206 } else {
5207 // Include all base classes
5208 num_children += cxx_record_decl->getNumBases();
5209 }
5210 }
5211 clang::RecordDecl::field_iterator field, field_end;
5212 for (field = record_decl->field_begin(),
5213 field_end = record_decl->field_end();
5214 field != field_end; ++field)
5215 ++num_children;
5216 }
5217 break;
5218
5219 case clang::Type::ObjCObject:
5220 case clang::Type::ObjCInterface:
5221 if (GetCompleteQualType(&getASTContext(), qual_type)) {
5222 const clang::ObjCObjectType *objc_class_type =
5223 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5224 assert(objc_class_type);
5225 if (objc_class_type) {
5226 clang::ObjCInterfaceDecl *class_interface_decl =
5227 objc_class_type->getInterface();
5228
5229 if (class_interface_decl) {
5230
5231 clang::ObjCInterfaceDecl *superclass_interface_decl =
5232 class_interface_decl->getSuperClass();
5233 if (superclass_interface_decl) {
5234 if (omit_empty_base_classes) {
5235 if (ObjCDeclHasIVars(superclass_interface_decl, true))
5236 ++num_children;
5237 } else
5238 ++num_children;
5239 }
5240
5241 num_children += class_interface_decl->ivar_size();
5242 }
5243 }
5244 }
5245 break;
5246
5247 case clang::Type::LValueReference:
5248 case clang::Type::RValueReference:
5249 case clang::Type::ObjCObjectPointer: {
5250 CompilerType pointee_clang_type(GetPointeeType(type));
5251
5252 uint32_t num_pointee_children = 0;
5253 if (pointee_clang_type.IsAggregateType())
5254 num_pointee_children =
5255 pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx);
5256 // If this type points to a simple type, then it has 1 child
5257 if (num_pointee_children == 0)
5258 num_children = 1;
5259 else
5260 num_children = num_pointee_children;
5261 } break;
5262
5263 case clang::Type::Vector:
5264 case clang::Type::ExtVector:
5265 num_children =
5266 llvm::cast<clang::VectorType>(qual_type.getTypePtr())->getNumElements();
5267 break;
5268
5269 case clang::Type::ConstantArray:
5270 num_children = llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr())
5271 ->getSize()
5272 .getLimitedValue();
5273 break;
5274 case clang::Type::IncompleteArray:
5275 if (auto array_info =
5276 GetDynamicArrayInfo(*this, GetSymbolFile(), qual_type, exe_ctx))
5277 // Only 1-dimensional arrays are supported.
5278 num_children = array_info->element_orders.size()
5279 ? array_info->element_orders.back()
5280 : 0;
5281 break;
5282
5283 case clang::Type::Pointer: {
5284 const clang::PointerType *pointer_type =
5285 llvm::cast<clang::PointerType>(qual_type.getTypePtr());
5286 clang::QualType pointee_type(pointer_type->getPointeeType());
5287 CompilerType pointee_clang_type(GetType(pointee_type));
5288 uint32_t num_pointee_children = 0;
5289 if (pointee_clang_type.IsAggregateType())
5290 num_pointee_children =
5291 pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx);
5292 if (num_pointee_children == 0) {
5293 // We have a pointer to a pointee type that claims it has no children. We
5294 // will want to look at
5295 num_children = GetNumPointeeChildren(pointee_type);
5296 } else
5297 num_children = num_pointee_children;
5298 } break;
5299
5300 default:
5301 break;
5302 }
5303 return num_children;
5304 }
5305
GetBuiltinTypeByName(ConstString name)5306 CompilerType TypeSystemClang::GetBuiltinTypeByName(ConstString name) {
5307 return GetBasicType(GetBasicTypeEnumeration(name));
5308 }
5309
5310 lldb::BasicType
GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type)5311 TypeSystemClang::GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) {
5312 if (type) {
5313 clang::QualType qual_type(GetQualType(type));
5314 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5315 if (type_class == clang::Type::Builtin) {
5316 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5317 case clang::BuiltinType::Void:
5318 return eBasicTypeVoid;
5319 case clang::BuiltinType::Bool:
5320 return eBasicTypeBool;
5321 case clang::BuiltinType::Char_S:
5322 return eBasicTypeSignedChar;
5323 case clang::BuiltinType::Char_U:
5324 return eBasicTypeUnsignedChar;
5325 case clang::BuiltinType::Char16:
5326 return eBasicTypeChar16;
5327 case clang::BuiltinType::Char32:
5328 return eBasicTypeChar32;
5329 case clang::BuiltinType::UChar:
5330 return eBasicTypeUnsignedChar;
5331 case clang::BuiltinType::SChar:
5332 return eBasicTypeSignedChar;
5333 case clang::BuiltinType::WChar_S:
5334 return eBasicTypeSignedWChar;
5335 case clang::BuiltinType::WChar_U:
5336 return eBasicTypeUnsignedWChar;
5337 case clang::BuiltinType::Short:
5338 return eBasicTypeShort;
5339 case clang::BuiltinType::UShort:
5340 return eBasicTypeUnsignedShort;
5341 case clang::BuiltinType::Int:
5342 return eBasicTypeInt;
5343 case clang::BuiltinType::UInt:
5344 return eBasicTypeUnsignedInt;
5345 case clang::BuiltinType::Long:
5346 return eBasicTypeLong;
5347 case clang::BuiltinType::ULong:
5348 return eBasicTypeUnsignedLong;
5349 case clang::BuiltinType::LongLong:
5350 return eBasicTypeLongLong;
5351 case clang::BuiltinType::ULongLong:
5352 return eBasicTypeUnsignedLongLong;
5353 case clang::BuiltinType::Int128:
5354 return eBasicTypeInt128;
5355 case clang::BuiltinType::UInt128:
5356 return eBasicTypeUnsignedInt128;
5357
5358 case clang::BuiltinType::Half:
5359 return eBasicTypeHalf;
5360 case clang::BuiltinType::Float:
5361 return eBasicTypeFloat;
5362 case clang::BuiltinType::Double:
5363 return eBasicTypeDouble;
5364 case clang::BuiltinType::LongDouble:
5365 return eBasicTypeLongDouble;
5366
5367 case clang::BuiltinType::NullPtr:
5368 return eBasicTypeNullPtr;
5369 case clang::BuiltinType::ObjCId:
5370 return eBasicTypeObjCID;
5371 case clang::BuiltinType::ObjCClass:
5372 return eBasicTypeObjCClass;
5373 case clang::BuiltinType::ObjCSel:
5374 return eBasicTypeObjCSel;
5375 default:
5376 return eBasicTypeOther;
5377 }
5378 }
5379 }
5380 return eBasicTypeInvalid;
5381 }
5382
ForEachEnumerator(lldb::opaque_compiler_type_t type,std::function<bool (const CompilerType & integer_type,ConstString name,const llvm::APSInt & value)> const & callback)5383 void TypeSystemClang::ForEachEnumerator(
5384 lldb::opaque_compiler_type_t type,
5385 std::function<bool(const CompilerType &integer_type,
5386 ConstString name,
5387 const llvm::APSInt &value)> const &callback) {
5388 const clang::EnumType *enum_type =
5389 llvm::dyn_cast<clang::EnumType>(GetCanonicalQualType(type));
5390 if (enum_type) {
5391 const clang::EnumDecl *enum_decl = enum_type->getDecl();
5392 if (enum_decl) {
5393 CompilerType integer_type = GetType(enum_decl->getIntegerType());
5394
5395 clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
5396 for (enum_pos = enum_decl->enumerator_begin(),
5397 enum_end_pos = enum_decl->enumerator_end();
5398 enum_pos != enum_end_pos; ++enum_pos) {
5399 ConstString name(enum_pos->getNameAsString().c_str());
5400 if (!callback(integer_type, name, enum_pos->getInitVal()))
5401 break;
5402 }
5403 }
5404 }
5405 }
5406
5407 #pragma mark Aggregate Types
5408
GetNumFields(lldb::opaque_compiler_type_t type)5409 uint32_t TypeSystemClang::GetNumFields(lldb::opaque_compiler_type_t type) {
5410 if (!type)
5411 return 0;
5412
5413 uint32_t count = 0;
5414 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
5415 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5416 switch (type_class) {
5417 case clang::Type::Record:
5418 if (GetCompleteType(type)) {
5419 const clang::RecordType *record_type =
5420 llvm::dyn_cast<clang::RecordType>(qual_type.getTypePtr());
5421 if (record_type) {
5422 clang::RecordDecl *record_decl = record_type->getDecl();
5423 if (record_decl) {
5424 uint32_t field_idx = 0;
5425 clang::RecordDecl::field_iterator field, field_end;
5426 for (field = record_decl->field_begin(),
5427 field_end = record_decl->field_end();
5428 field != field_end; ++field)
5429 ++field_idx;
5430 count = field_idx;
5431 }
5432 }
5433 }
5434 break;
5435
5436 case clang::Type::ObjCObjectPointer: {
5437 const clang::ObjCObjectPointerType *objc_class_type =
5438 qual_type->getAs<clang::ObjCObjectPointerType>();
5439 const clang::ObjCInterfaceType *objc_interface_type =
5440 objc_class_type->getInterfaceType();
5441 if (objc_interface_type &&
5442 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
5443 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5444 clang::ObjCInterfaceDecl *class_interface_decl =
5445 objc_interface_type->getDecl();
5446 if (class_interface_decl) {
5447 count = class_interface_decl->ivar_size();
5448 }
5449 }
5450 break;
5451 }
5452
5453 case clang::Type::ObjCObject:
5454 case clang::Type::ObjCInterface:
5455 if (GetCompleteType(type)) {
5456 const clang::ObjCObjectType *objc_class_type =
5457 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5458 if (objc_class_type) {
5459 clang::ObjCInterfaceDecl *class_interface_decl =
5460 objc_class_type->getInterface();
5461
5462 if (class_interface_decl)
5463 count = class_interface_decl->ivar_size();
5464 }
5465 }
5466 break;
5467
5468 default:
5469 break;
5470 }
5471 return count;
5472 }
5473
5474 static lldb::opaque_compiler_type_t
GetObjCFieldAtIndex(clang::ASTContext * ast,clang::ObjCInterfaceDecl * class_interface_decl,size_t idx,std::string & name,uint64_t * bit_offset_ptr,uint32_t * bitfield_bit_size_ptr,bool * is_bitfield_ptr)5475 GetObjCFieldAtIndex(clang::ASTContext *ast,
5476 clang::ObjCInterfaceDecl *class_interface_decl, size_t idx,
5477 std::string &name, uint64_t *bit_offset_ptr,
5478 uint32_t *bitfield_bit_size_ptr, bool *is_bitfield_ptr) {
5479 if (class_interface_decl) {
5480 if (idx < (class_interface_decl->ivar_size())) {
5481 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
5482 ivar_end = class_interface_decl->ivar_end();
5483 uint32_t ivar_idx = 0;
5484
5485 for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end;
5486 ++ivar_pos, ++ivar_idx) {
5487 if (ivar_idx == idx) {
5488 const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
5489
5490 clang::QualType ivar_qual_type(ivar_decl->getType());
5491
5492 name.assign(ivar_decl->getNameAsString());
5493
5494 if (bit_offset_ptr) {
5495 const clang::ASTRecordLayout &interface_layout =
5496 ast->getASTObjCInterfaceLayout(class_interface_decl);
5497 *bit_offset_ptr = interface_layout.getFieldOffset(ivar_idx);
5498 }
5499
5500 const bool is_bitfield = ivar_pos->isBitField();
5501
5502 if (bitfield_bit_size_ptr) {
5503 *bitfield_bit_size_ptr = 0;
5504
5505 if (is_bitfield && ast) {
5506 clang::Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth();
5507 clang::Expr::EvalResult result;
5508 if (bitfield_bit_size_expr &&
5509 bitfield_bit_size_expr->EvaluateAsInt(result, *ast)) {
5510 llvm::APSInt bitfield_apsint = result.Val.getInt();
5511 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5512 }
5513 }
5514 }
5515 if (is_bitfield_ptr)
5516 *is_bitfield_ptr = is_bitfield;
5517
5518 return ivar_qual_type.getAsOpaquePtr();
5519 }
5520 }
5521 }
5522 }
5523 return nullptr;
5524 }
5525
GetFieldAtIndex(lldb::opaque_compiler_type_t type,size_t idx,std::string & name,uint64_t * bit_offset_ptr,uint32_t * bitfield_bit_size_ptr,bool * is_bitfield_ptr)5526 CompilerType TypeSystemClang::GetFieldAtIndex(lldb::opaque_compiler_type_t type,
5527 size_t idx, std::string &name,
5528 uint64_t *bit_offset_ptr,
5529 uint32_t *bitfield_bit_size_ptr,
5530 bool *is_bitfield_ptr) {
5531 if (!type)
5532 return CompilerType();
5533
5534 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
5535 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5536 switch (type_class) {
5537 case clang::Type::Record:
5538 if (GetCompleteType(type)) {
5539 const clang::RecordType *record_type =
5540 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5541 const clang::RecordDecl *record_decl = record_type->getDecl();
5542 uint32_t field_idx = 0;
5543 clang::RecordDecl::field_iterator field, field_end;
5544 for (field = record_decl->field_begin(),
5545 field_end = record_decl->field_end();
5546 field != field_end; ++field, ++field_idx) {
5547 if (idx == field_idx) {
5548 // Print the member type if requested
5549 // Print the member name and equal sign
5550 name.assign(field->getNameAsString());
5551
5552 // Figure out the type byte size (field_type_info.first) and
5553 // alignment (field_type_info.second) from the AST context.
5554 if (bit_offset_ptr) {
5555 const clang::ASTRecordLayout &record_layout =
5556 getASTContext().getASTRecordLayout(record_decl);
5557 *bit_offset_ptr = record_layout.getFieldOffset(field_idx);
5558 }
5559
5560 const bool is_bitfield = field->isBitField();
5561
5562 if (bitfield_bit_size_ptr) {
5563 *bitfield_bit_size_ptr = 0;
5564
5565 if (is_bitfield) {
5566 clang::Expr *bitfield_bit_size_expr = field->getBitWidth();
5567 clang::Expr::EvalResult result;
5568 if (bitfield_bit_size_expr &&
5569 bitfield_bit_size_expr->EvaluateAsInt(result,
5570 getASTContext())) {
5571 llvm::APSInt bitfield_apsint = result.Val.getInt();
5572 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5573 }
5574 }
5575 }
5576 if (is_bitfield_ptr)
5577 *is_bitfield_ptr = is_bitfield;
5578
5579 return GetType(field->getType());
5580 }
5581 }
5582 }
5583 break;
5584
5585 case clang::Type::ObjCObjectPointer: {
5586 const clang::ObjCObjectPointerType *objc_class_type =
5587 qual_type->getAs<clang::ObjCObjectPointerType>();
5588 const clang::ObjCInterfaceType *objc_interface_type =
5589 objc_class_type->getInterfaceType();
5590 if (objc_interface_type &&
5591 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
5592 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5593 clang::ObjCInterfaceDecl *class_interface_decl =
5594 objc_interface_type->getDecl();
5595 if (class_interface_decl) {
5596 return CompilerType(
5597 this, GetObjCFieldAtIndex(&getASTContext(), class_interface_decl,
5598 idx, name, bit_offset_ptr,
5599 bitfield_bit_size_ptr, is_bitfield_ptr));
5600 }
5601 }
5602 break;
5603 }
5604
5605 case clang::Type::ObjCObject:
5606 case clang::Type::ObjCInterface:
5607 if (GetCompleteType(type)) {
5608 const clang::ObjCObjectType *objc_class_type =
5609 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5610 assert(objc_class_type);
5611 if (objc_class_type) {
5612 clang::ObjCInterfaceDecl *class_interface_decl =
5613 objc_class_type->getInterface();
5614 return CompilerType(
5615 this, GetObjCFieldAtIndex(&getASTContext(), class_interface_decl,
5616 idx, name, bit_offset_ptr,
5617 bitfield_bit_size_ptr, is_bitfield_ptr));
5618 }
5619 }
5620 break;
5621
5622 default:
5623 break;
5624 }
5625 return CompilerType();
5626 }
5627
5628 uint32_t
GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type)5629 TypeSystemClang::GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type) {
5630 uint32_t count = 0;
5631 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5632 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5633 switch (type_class) {
5634 case clang::Type::Record:
5635 if (GetCompleteType(type)) {
5636 const clang::CXXRecordDecl *cxx_record_decl =
5637 qual_type->getAsCXXRecordDecl();
5638 if (cxx_record_decl)
5639 count = cxx_record_decl->getNumBases();
5640 }
5641 break;
5642
5643 case clang::Type::ObjCObjectPointer:
5644 count = GetPointeeType(type).GetNumDirectBaseClasses();
5645 break;
5646
5647 case clang::Type::ObjCObject:
5648 if (GetCompleteType(type)) {
5649 const clang::ObjCObjectType *objc_class_type =
5650 qual_type->getAsObjCQualifiedInterfaceType();
5651 if (objc_class_type) {
5652 clang::ObjCInterfaceDecl *class_interface_decl =
5653 objc_class_type->getInterface();
5654
5655 if (class_interface_decl && class_interface_decl->getSuperClass())
5656 count = 1;
5657 }
5658 }
5659 break;
5660 case clang::Type::ObjCInterface:
5661 if (GetCompleteType(type)) {
5662 const clang::ObjCInterfaceType *objc_interface_type =
5663 qual_type->getAs<clang::ObjCInterfaceType>();
5664 if (objc_interface_type) {
5665 clang::ObjCInterfaceDecl *class_interface_decl =
5666 objc_interface_type->getInterface();
5667
5668 if (class_interface_decl && class_interface_decl->getSuperClass())
5669 count = 1;
5670 }
5671 }
5672 break;
5673
5674 default:
5675 break;
5676 }
5677 return count;
5678 }
5679
5680 uint32_t
GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type)5681 TypeSystemClang::GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type) {
5682 uint32_t count = 0;
5683 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5684 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5685 switch (type_class) {
5686 case clang::Type::Record:
5687 if (GetCompleteType(type)) {
5688 const clang::CXXRecordDecl *cxx_record_decl =
5689 qual_type->getAsCXXRecordDecl();
5690 if (cxx_record_decl)
5691 count = cxx_record_decl->getNumVBases();
5692 }
5693 break;
5694
5695 default:
5696 break;
5697 }
5698 return count;
5699 }
5700
GetDirectBaseClassAtIndex(lldb::opaque_compiler_type_t type,size_t idx,uint32_t * bit_offset_ptr)5701 CompilerType TypeSystemClang::GetDirectBaseClassAtIndex(
5702 lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
5703 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5704 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5705 switch (type_class) {
5706 case clang::Type::Record:
5707 if (GetCompleteType(type)) {
5708 const clang::CXXRecordDecl *cxx_record_decl =
5709 qual_type->getAsCXXRecordDecl();
5710 if (cxx_record_decl) {
5711 uint32_t curr_idx = 0;
5712 clang::CXXRecordDecl::base_class_const_iterator base_class,
5713 base_class_end;
5714 for (base_class = cxx_record_decl->bases_begin(),
5715 base_class_end = cxx_record_decl->bases_end();
5716 base_class != base_class_end; ++base_class, ++curr_idx) {
5717 if (curr_idx == idx) {
5718 if (bit_offset_ptr) {
5719 const clang::ASTRecordLayout &record_layout =
5720 getASTContext().getASTRecordLayout(cxx_record_decl);
5721 const clang::CXXRecordDecl *base_class_decl =
5722 llvm::cast<clang::CXXRecordDecl>(
5723 base_class->getType()
5724 ->getAs<clang::RecordType>()
5725 ->getDecl());
5726 if (base_class->isVirtual())
5727 *bit_offset_ptr =
5728 record_layout.getVBaseClassOffset(base_class_decl)
5729 .getQuantity() *
5730 8;
5731 else
5732 *bit_offset_ptr =
5733 record_layout.getBaseClassOffset(base_class_decl)
5734 .getQuantity() *
5735 8;
5736 }
5737 return GetType(base_class->getType());
5738 }
5739 }
5740 }
5741 }
5742 break;
5743
5744 case clang::Type::ObjCObjectPointer:
5745 return GetPointeeType(type).GetDirectBaseClassAtIndex(idx, bit_offset_ptr);
5746
5747 case clang::Type::ObjCObject:
5748 if (idx == 0 && GetCompleteType(type)) {
5749 const clang::ObjCObjectType *objc_class_type =
5750 qual_type->getAsObjCQualifiedInterfaceType();
5751 if (objc_class_type) {
5752 clang::ObjCInterfaceDecl *class_interface_decl =
5753 objc_class_type->getInterface();
5754
5755 if (class_interface_decl) {
5756 clang::ObjCInterfaceDecl *superclass_interface_decl =
5757 class_interface_decl->getSuperClass();
5758 if (superclass_interface_decl) {
5759 if (bit_offset_ptr)
5760 *bit_offset_ptr = 0;
5761 return GetType(getASTContext().getObjCInterfaceType(
5762 superclass_interface_decl));
5763 }
5764 }
5765 }
5766 }
5767 break;
5768 case clang::Type::ObjCInterface:
5769 if (idx == 0 && GetCompleteType(type)) {
5770 const clang::ObjCObjectType *objc_interface_type =
5771 qual_type->getAs<clang::ObjCInterfaceType>();
5772 if (objc_interface_type) {
5773 clang::ObjCInterfaceDecl *class_interface_decl =
5774 objc_interface_type->getInterface();
5775
5776 if (class_interface_decl) {
5777 clang::ObjCInterfaceDecl *superclass_interface_decl =
5778 class_interface_decl->getSuperClass();
5779 if (superclass_interface_decl) {
5780 if (bit_offset_ptr)
5781 *bit_offset_ptr = 0;
5782 return GetType(getASTContext().getObjCInterfaceType(
5783 superclass_interface_decl));
5784 }
5785 }
5786 }
5787 }
5788 break;
5789
5790 default:
5791 break;
5792 }
5793 return CompilerType();
5794 }
5795
GetVirtualBaseClassAtIndex(lldb::opaque_compiler_type_t type,size_t idx,uint32_t * bit_offset_ptr)5796 CompilerType TypeSystemClang::GetVirtualBaseClassAtIndex(
5797 lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
5798 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5799 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5800 switch (type_class) {
5801 case clang::Type::Record:
5802 if (GetCompleteType(type)) {
5803 const clang::CXXRecordDecl *cxx_record_decl =
5804 qual_type->getAsCXXRecordDecl();
5805 if (cxx_record_decl) {
5806 uint32_t curr_idx = 0;
5807 clang::CXXRecordDecl::base_class_const_iterator base_class,
5808 base_class_end;
5809 for (base_class = cxx_record_decl->vbases_begin(),
5810 base_class_end = cxx_record_decl->vbases_end();
5811 base_class != base_class_end; ++base_class, ++curr_idx) {
5812 if (curr_idx == idx) {
5813 if (bit_offset_ptr) {
5814 const clang::ASTRecordLayout &record_layout =
5815 getASTContext().getASTRecordLayout(cxx_record_decl);
5816 const clang::CXXRecordDecl *base_class_decl =
5817 llvm::cast<clang::CXXRecordDecl>(
5818 base_class->getType()
5819 ->getAs<clang::RecordType>()
5820 ->getDecl());
5821 *bit_offset_ptr =
5822 record_layout.getVBaseClassOffset(base_class_decl)
5823 .getQuantity() *
5824 8;
5825 }
5826 return GetType(base_class->getType());
5827 }
5828 }
5829 }
5830 }
5831 break;
5832
5833 default:
5834 break;
5835 }
5836 return CompilerType();
5837 }
5838
5839 // If a pointer to a pointee type (the clang_type arg) says that it has no
5840 // children, then we either need to trust it, or override it and return a
5841 // different result. For example, an "int *" has one child that is an integer,
5842 // but a function pointer doesn't have any children. Likewise if a Record type
5843 // claims it has no children, then there really is nothing to show.
GetNumPointeeChildren(clang::QualType type)5844 uint32_t TypeSystemClang::GetNumPointeeChildren(clang::QualType type) {
5845 if (type.isNull())
5846 return 0;
5847
5848 clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType());
5849 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5850 switch (type_class) {
5851 case clang::Type::Builtin:
5852 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5853 case clang::BuiltinType::UnknownAny:
5854 case clang::BuiltinType::Void:
5855 case clang::BuiltinType::NullPtr:
5856 case clang::BuiltinType::OCLEvent:
5857 case clang::BuiltinType::OCLImage1dRO:
5858 case clang::BuiltinType::OCLImage1dWO:
5859 case clang::BuiltinType::OCLImage1dRW:
5860 case clang::BuiltinType::OCLImage1dArrayRO:
5861 case clang::BuiltinType::OCLImage1dArrayWO:
5862 case clang::BuiltinType::OCLImage1dArrayRW:
5863 case clang::BuiltinType::OCLImage1dBufferRO:
5864 case clang::BuiltinType::OCLImage1dBufferWO:
5865 case clang::BuiltinType::OCLImage1dBufferRW:
5866 case clang::BuiltinType::OCLImage2dRO:
5867 case clang::BuiltinType::OCLImage2dWO:
5868 case clang::BuiltinType::OCLImage2dRW:
5869 case clang::BuiltinType::OCLImage2dArrayRO:
5870 case clang::BuiltinType::OCLImage2dArrayWO:
5871 case clang::BuiltinType::OCLImage2dArrayRW:
5872 case clang::BuiltinType::OCLImage3dRO:
5873 case clang::BuiltinType::OCLImage3dWO:
5874 case clang::BuiltinType::OCLImage3dRW:
5875 case clang::BuiltinType::OCLSampler:
5876 return 0;
5877 case clang::BuiltinType::Bool:
5878 case clang::BuiltinType::Char_U:
5879 case clang::BuiltinType::UChar:
5880 case clang::BuiltinType::WChar_U:
5881 case clang::BuiltinType::Char16:
5882 case clang::BuiltinType::Char32:
5883 case clang::BuiltinType::UShort:
5884 case clang::BuiltinType::UInt:
5885 case clang::BuiltinType::ULong:
5886 case clang::BuiltinType::ULongLong:
5887 case clang::BuiltinType::UInt128:
5888 case clang::BuiltinType::Char_S:
5889 case clang::BuiltinType::SChar:
5890 case clang::BuiltinType::WChar_S:
5891 case clang::BuiltinType::Short:
5892 case clang::BuiltinType::Int:
5893 case clang::BuiltinType::Long:
5894 case clang::BuiltinType::LongLong:
5895 case clang::BuiltinType::Int128:
5896 case clang::BuiltinType::Float:
5897 case clang::BuiltinType::Double:
5898 case clang::BuiltinType::LongDouble:
5899 case clang::BuiltinType::Dependent:
5900 case clang::BuiltinType::Overload:
5901 case clang::BuiltinType::ObjCId:
5902 case clang::BuiltinType::ObjCClass:
5903 case clang::BuiltinType::ObjCSel:
5904 case clang::BuiltinType::BoundMember:
5905 case clang::BuiltinType::Half:
5906 case clang::BuiltinType::ARCUnbridgedCast:
5907 case clang::BuiltinType::PseudoObject:
5908 case clang::BuiltinType::BuiltinFn:
5909 case clang::BuiltinType::OMPArraySection:
5910 return 1;
5911 default:
5912 return 0;
5913 }
5914 break;
5915
5916 case clang::Type::Complex:
5917 return 1;
5918 case clang::Type::Pointer:
5919 return 1;
5920 case clang::Type::BlockPointer:
5921 return 0; // If block pointers don't have debug info, then no children for
5922 // them
5923 case clang::Type::LValueReference:
5924 return 1;
5925 case clang::Type::RValueReference:
5926 return 1;
5927 case clang::Type::MemberPointer:
5928 return 0;
5929 case clang::Type::ConstantArray:
5930 return 0;
5931 case clang::Type::IncompleteArray:
5932 return 0;
5933 case clang::Type::VariableArray:
5934 return 0;
5935 case clang::Type::DependentSizedArray:
5936 return 0;
5937 case clang::Type::DependentSizedExtVector:
5938 return 0;
5939 case clang::Type::Vector:
5940 return 0;
5941 case clang::Type::ExtVector:
5942 return 0;
5943 case clang::Type::FunctionProto:
5944 return 0; // When we function pointers, they have no children...
5945 case clang::Type::FunctionNoProto:
5946 return 0; // When we function pointers, they have no children...
5947 case clang::Type::UnresolvedUsing:
5948 return 0;
5949 case clang::Type::Record:
5950 return 0;
5951 case clang::Type::Enum:
5952 return 1;
5953 case clang::Type::TemplateTypeParm:
5954 return 1;
5955 case clang::Type::SubstTemplateTypeParm:
5956 return 1;
5957 case clang::Type::TemplateSpecialization:
5958 return 1;
5959 case clang::Type::InjectedClassName:
5960 return 0;
5961 case clang::Type::DependentName:
5962 return 1;
5963 case clang::Type::DependentTemplateSpecialization:
5964 return 1;
5965 case clang::Type::ObjCObject:
5966 return 0;
5967 case clang::Type::ObjCInterface:
5968 return 0;
5969 case clang::Type::ObjCObjectPointer:
5970 return 1;
5971 default:
5972 break;
5973 }
5974 return 0;
5975 }
5976
GetChildCompilerTypeAtIndex(lldb::opaque_compiler_type_t type,ExecutionContext * exe_ctx,size_t idx,bool transparent_pointers,bool omit_empty_base_classes,bool ignore_array_bounds,std::string & child_name,uint32_t & child_byte_size,int32_t & child_byte_offset,uint32_t & child_bitfield_bit_size,uint32_t & child_bitfield_bit_offset,bool & child_is_base_class,bool & child_is_deref_of_parent,ValueObject * valobj,uint64_t & language_flags)5977 CompilerType TypeSystemClang::GetChildCompilerTypeAtIndex(
5978 lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, size_t idx,
5979 bool transparent_pointers, bool omit_empty_base_classes,
5980 bool ignore_array_bounds, std::string &child_name,
5981 uint32_t &child_byte_size, int32_t &child_byte_offset,
5982 uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset,
5983 bool &child_is_base_class, bool &child_is_deref_of_parent,
5984 ValueObject *valobj, uint64_t &language_flags) {
5985 if (!type)
5986 return CompilerType();
5987
5988 auto get_exe_scope = [&exe_ctx]() {
5989 return exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr;
5990 };
5991
5992 clang::QualType parent_qual_type(
5993 RemoveWrappingTypes(GetCanonicalQualType(type)));
5994 const clang::Type::TypeClass parent_type_class =
5995 parent_qual_type->getTypeClass();
5996 child_bitfield_bit_size = 0;
5997 child_bitfield_bit_offset = 0;
5998 child_is_base_class = false;
5999 language_flags = 0;
6000
6001 const bool idx_is_valid =
6002 idx < GetNumChildren(type, omit_empty_base_classes, exe_ctx);
6003 int32_t bit_offset;
6004 switch (parent_type_class) {
6005 case clang::Type::Builtin:
6006 if (idx_is_valid) {
6007 switch (llvm::cast<clang::BuiltinType>(parent_qual_type)->getKind()) {
6008 case clang::BuiltinType::ObjCId:
6009 case clang::BuiltinType::ObjCClass:
6010 child_name = "isa";
6011 child_byte_size =
6012 getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy) /
6013 CHAR_BIT;
6014 return GetType(getASTContext().ObjCBuiltinClassTy);
6015
6016 default:
6017 break;
6018 }
6019 }
6020 break;
6021
6022 case clang::Type::Record:
6023 if (idx_is_valid && GetCompleteType(type)) {
6024 const clang::RecordType *record_type =
6025 llvm::cast<clang::RecordType>(parent_qual_type.getTypePtr());
6026 const clang::RecordDecl *record_decl = record_type->getDecl();
6027 assert(record_decl);
6028 const clang::ASTRecordLayout &record_layout =
6029 getASTContext().getASTRecordLayout(record_decl);
6030 uint32_t child_idx = 0;
6031
6032 const clang::CXXRecordDecl *cxx_record_decl =
6033 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6034 if (cxx_record_decl) {
6035 // We might have base classes to print out first
6036 clang::CXXRecordDecl::base_class_const_iterator base_class,
6037 base_class_end;
6038 for (base_class = cxx_record_decl->bases_begin(),
6039 base_class_end = cxx_record_decl->bases_end();
6040 base_class != base_class_end; ++base_class) {
6041 const clang::CXXRecordDecl *base_class_decl = nullptr;
6042
6043 // Skip empty base classes
6044 if (omit_empty_base_classes) {
6045 base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6046 base_class->getType()->getAs<clang::RecordType>()->getDecl());
6047 if (!TypeSystemClang::RecordHasFields(base_class_decl))
6048 continue;
6049 }
6050
6051 if (idx == child_idx) {
6052 if (base_class_decl == nullptr)
6053 base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6054 base_class->getType()->getAs<clang::RecordType>()->getDecl());
6055
6056 if (base_class->isVirtual()) {
6057 bool handled = false;
6058 if (valobj) {
6059 clang::VTableContextBase *vtable_ctx =
6060 getASTContext().getVTableContext();
6061 if (vtable_ctx)
6062 handled = GetVBaseBitOffset(*vtable_ctx, *valobj,
6063 record_layout, cxx_record_decl,
6064 base_class_decl, bit_offset);
6065 }
6066 if (!handled)
6067 bit_offset = record_layout.getVBaseClassOffset(base_class_decl)
6068 .getQuantity() *
6069 8;
6070 } else
6071 bit_offset = record_layout.getBaseClassOffset(base_class_decl)
6072 .getQuantity() *
6073 8;
6074
6075 // Base classes should be a multiple of 8 bits in size
6076 child_byte_offset = bit_offset / 8;
6077 CompilerType base_class_clang_type = GetType(base_class->getType());
6078 child_name = base_class_clang_type.GetTypeName().AsCString("");
6079 Optional<uint64_t> size =
6080 base_class_clang_type.GetBitSize(get_exe_scope());
6081 if (!size)
6082 return {};
6083 uint64_t base_class_clang_type_bit_size = *size;
6084
6085 // Base classes bit sizes should be a multiple of 8 bits in size
6086 assert(base_class_clang_type_bit_size % 8 == 0);
6087 child_byte_size = base_class_clang_type_bit_size / 8;
6088 child_is_base_class = true;
6089 return base_class_clang_type;
6090 }
6091 // We don't increment the child index in the for loop since we might
6092 // be skipping empty base classes
6093 ++child_idx;
6094 }
6095 }
6096 // Make sure index is in range...
6097 uint32_t field_idx = 0;
6098 clang::RecordDecl::field_iterator field, field_end;
6099 for (field = record_decl->field_begin(),
6100 field_end = record_decl->field_end();
6101 field != field_end; ++field, ++field_idx, ++child_idx) {
6102 if (idx == child_idx) {
6103 // Print the member type if requested
6104 // Print the member name and equal sign
6105 child_name.assign(field->getNameAsString());
6106
6107 // Figure out the type byte size (field_type_info.first) and
6108 // alignment (field_type_info.second) from the AST context.
6109 CompilerType field_clang_type = GetType(field->getType());
6110 assert(field_idx < record_layout.getFieldCount());
6111 Optional<uint64_t> size =
6112 field_clang_type.GetByteSize(get_exe_scope());
6113 if (!size)
6114 return {};
6115 child_byte_size = *size;
6116 const uint32_t child_bit_size = child_byte_size * 8;
6117
6118 // Figure out the field offset within the current struct/union/class
6119 // type
6120 bit_offset = record_layout.getFieldOffset(field_idx);
6121 if (FieldIsBitfield(*field, child_bitfield_bit_size)) {
6122 child_bitfield_bit_offset = bit_offset % child_bit_size;
6123 const uint32_t child_bit_offset =
6124 bit_offset - child_bitfield_bit_offset;
6125 child_byte_offset = child_bit_offset / 8;
6126 } else {
6127 child_byte_offset = bit_offset / 8;
6128 }
6129
6130 return field_clang_type;
6131 }
6132 }
6133 }
6134 break;
6135
6136 case clang::Type::ObjCObject:
6137 case clang::Type::ObjCInterface:
6138 if (idx_is_valid && GetCompleteType(type)) {
6139 const clang::ObjCObjectType *objc_class_type =
6140 llvm::dyn_cast<clang::ObjCObjectType>(parent_qual_type.getTypePtr());
6141 assert(objc_class_type);
6142 if (objc_class_type) {
6143 uint32_t child_idx = 0;
6144 clang::ObjCInterfaceDecl *class_interface_decl =
6145 objc_class_type->getInterface();
6146
6147 if (class_interface_decl) {
6148
6149 const clang::ASTRecordLayout &interface_layout =
6150 getASTContext().getASTObjCInterfaceLayout(class_interface_decl);
6151 clang::ObjCInterfaceDecl *superclass_interface_decl =
6152 class_interface_decl->getSuperClass();
6153 if (superclass_interface_decl) {
6154 if (omit_empty_base_classes) {
6155 CompilerType base_class_clang_type =
6156 GetType(getASTContext().getObjCInterfaceType(
6157 superclass_interface_decl));
6158 if (base_class_clang_type.GetNumChildren(omit_empty_base_classes,
6159 exe_ctx) > 0) {
6160 if (idx == 0) {
6161 clang::QualType ivar_qual_type(
6162 getASTContext().getObjCInterfaceType(
6163 superclass_interface_decl));
6164
6165 child_name.assign(
6166 superclass_interface_decl->getNameAsString());
6167
6168 clang::TypeInfo ivar_type_info =
6169 getASTContext().getTypeInfo(ivar_qual_type.getTypePtr());
6170
6171 child_byte_size = ivar_type_info.Width / 8;
6172 child_byte_offset = 0;
6173 child_is_base_class = true;
6174
6175 return GetType(ivar_qual_type);
6176 }
6177
6178 ++child_idx;
6179 }
6180 } else
6181 ++child_idx;
6182 }
6183
6184 const uint32_t superclass_idx = child_idx;
6185
6186 if (idx < (child_idx + class_interface_decl->ivar_size())) {
6187 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6188 ivar_end = class_interface_decl->ivar_end();
6189
6190 for (ivar_pos = class_interface_decl->ivar_begin();
6191 ivar_pos != ivar_end; ++ivar_pos) {
6192 if (child_idx == idx) {
6193 clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6194
6195 clang::QualType ivar_qual_type(ivar_decl->getType());
6196
6197 child_name.assign(ivar_decl->getNameAsString());
6198
6199 clang::TypeInfo ivar_type_info =
6200 getASTContext().getTypeInfo(ivar_qual_type.getTypePtr());
6201
6202 child_byte_size = ivar_type_info.Width / 8;
6203
6204 // Figure out the field offset within the current
6205 // struct/union/class type For ObjC objects, we can't trust the
6206 // bit offset we get from the Clang AST, since that doesn't
6207 // account for the space taken up by unbacked properties, or
6208 // from the changing size of base classes that are newer than
6209 // this class. So if we have a process around that we can ask
6210 // about this object, do so.
6211 child_byte_offset = LLDB_INVALID_IVAR_OFFSET;
6212 Process *process = nullptr;
6213 if (exe_ctx)
6214 process = exe_ctx->GetProcessPtr();
6215 if (process) {
6216 ObjCLanguageRuntime *objc_runtime =
6217 ObjCLanguageRuntime::Get(*process);
6218 if (objc_runtime != nullptr) {
6219 CompilerType parent_ast_type = GetType(parent_qual_type);
6220 child_byte_offset = objc_runtime->GetByteOffsetForIvar(
6221 parent_ast_type, ivar_decl->getNameAsString().c_str());
6222 }
6223 }
6224
6225 // Setting this to INT32_MAX to make sure we don't compute it
6226 // twice...
6227 bit_offset = INT32_MAX;
6228
6229 if (child_byte_offset ==
6230 static_cast<int32_t>(LLDB_INVALID_IVAR_OFFSET)) {
6231 bit_offset = interface_layout.getFieldOffset(child_idx -
6232 superclass_idx);
6233 child_byte_offset = bit_offset / 8;
6234 }
6235
6236 // Note, the ObjC Ivar Byte offset is just that, it doesn't
6237 // account for the bit offset of a bitfield within its
6238 // containing object. So regardless of where we get the byte
6239 // offset from, we still need to get the bit offset for
6240 // bitfields from the layout.
6241
6242 if (FieldIsBitfield(ivar_decl, child_bitfield_bit_size)) {
6243 if (bit_offset == INT32_MAX)
6244 bit_offset = interface_layout.getFieldOffset(
6245 child_idx - superclass_idx);
6246
6247 child_bitfield_bit_offset = bit_offset % 8;
6248 }
6249 return GetType(ivar_qual_type);
6250 }
6251 ++child_idx;
6252 }
6253 }
6254 }
6255 }
6256 }
6257 break;
6258
6259 case clang::Type::ObjCObjectPointer:
6260 if (idx_is_valid) {
6261 CompilerType pointee_clang_type(GetPointeeType(type));
6262
6263 if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6264 child_is_deref_of_parent = false;
6265 bool tmp_child_is_deref_of_parent = false;
6266 return pointee_clang_type.GetChildCompilerTypeAtIndex(
6267 exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6268 ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6269 child_bitfield_bit_size, child_bitfield_bit_offset,
6270 child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6271 language_flags);
6272 } else {
6273 child_is_deref_of_parent = true;
6274 const char *parent_name =
6275 valobj ? valobj->GetName().GetCString() : nullptr;
6276 if (parent_name) {
6277 child_name.assign(1, '*');
6278 child_name += parent_name;
6279 }
6280
6281 // We have a pointer to an simple type
6282 if (idx == 0 && pointee_clang_type.GetCompleteType()) {
6283 if (Optional<uint64_t> size =
6284 pointee_clang_type.GetByteSize(get_exe_scope())) {
6285 child_byte_size = *size;
6286 child_byte_offset = 0;
6287 return pointee_clang_type;
6288 }
6289 }
6290 }
6291 }
6292 break;
6293
6294 case clang::Type::Vector:
6295 case clang::Type::ExtVector:
6296 if (idx_is_valid) {
6297 const clang::VectorType *array =
6298 llvm::cast<clang::VectorType>(parent_qual_type.getTypePtr());
6299 if (array) {
6300 CompilerType element_type = GetType(array->getElementType());
6301 if (element_type.GetCompleteType()) {
6302 char element_name[64];
6303 ::snprintf(element_name, sizeof(element_name), "[%" PRIu64 "]",
6304 static_cast<uint64_t>(idx));
6305 child_name.assign(element_name);
6306 if (Optional<uint64_t> size =
6307 element_type.GetByteSize(get_exe_scope())) {
6308 child_byte_size = *size;
6309 child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6310 return element_type;
6311 }
6312 }
6313 }
6314 }
6315 break;
6316
6317 case clang::Type::ConstantArray:
6318 case clang::Type::IncompleteArray:
6319 if (ignore_array_bounds || idx_is_valid) {
6320 const clang::ArrayType *array = GetQualType(type)->getAsArrayTypeUnsafe();
6321 if (array) {
6322 CompilerType element_type = GetType(array->getElementType());
6323 if (element_type.GetCompleteType()) {
6324 child_name = std::string(llvm::formatv("[{0}]", idx));
6325 if (Optional<uint64_t> size =
6326 element_type.GetByteSize(get_exe_scope())) {
6327 child_byte_size = *size;
6328 child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6329 return element_type;
6330 }
6331 }
6332 }
6333 }
6334 break;
6335
6336 case clang::Type::Pointer: {
6337 CompilerType pointee_clang_type(GetPointeeType(type));
6338
6339 // Don't dereference "void *" pointers
6340 if (pointee_clang_type.IsVoidType())
6341 return CompilerType();
6342
6343 if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6344 child_is_deref_of_parent = false;
6345 bool tmp_child_is_deref_of_parent = false;
6346 return pointee_clang_type.GetChildCompilerTypeAtIndex(
6347 exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6348 ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6349 child_bitfield_bit_size, child_bitfield_bit_offset,
6350 child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6351 language_flags);
6352 } else {
6353 child_is_deref_of_parent = true;
6354
6355 const char *parent_name =
6356 valobj ? valobj->GetName().GetCString() : nullptr;
6357 if (parent_name) {
6358 child_name.assign(1, '*');
6359 child_name += parent_name;
6360 }
6361
6362 // We have a pointer to an simple type
6363 if (idx == 0) {
6364 if (Optional<uint64_t> size =
6365 pointee_clang_type.GetByteSize(get_exe_scope())) {
6366 child_byte_size = *size;
6367 child_byte_offset = 0;
6368 return pointee_clang_type;
6369 }
6370 }
6371 }
6372 break;
6373 }
6374
6375 case clang::Type::LValueReference:
6376 case clang::Type::RValueReference:
6377 if (idx_is_valid) {
6378 const clang::ReferenceType *reference_type =
6379 llvm::cast<clang::ReferenceType>(parent_qual_type.getTypePtr());
6380 CompilerType pointee_clang_type =
6381 GetType(reference_type->getPointeeType());
6382 if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6383 child_is_deref_of_parent = false;
6384 bool tmp_child_is_deref_of_parent = false;
6385 return pointee_clang_type.GetChildCompilerTypeAtIndex(
6386 exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6387 ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6388 child_bitfield_bit_size, child_bitfield_bit_offset,
6389 child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6390 language_flags);
6391 } else {
6392 const char *parent_name =
6393 valobj ? valobj->GetName().GetCString() : nullptr;
6394 if (parent_name) {
6395 child_name.assign(1, '&');
6396 child_name += parent_name;
6397 }
6398
6399 // We have a pointer to an simple type
6400 if (idx == 0) {
6401 if (Optional<uint64_t> size =
6402 pointee_clang_type.GetByteSize(get_exe_scope())) {
6403 child_byte_size = *size;
6404 child_byte_offset = 0;
6405 return pointee_clang_type;
6406 }
6407 }
6408 }
6409 }
6410 break;
6411
6412 default:
6413 break;
6414 }
6415 return CompilerType();
6416 }
6417
GetIndexForRecordBase(const clang::RecordDecl * record_decl,const clang::CXXBaseSpecifier * base_spec,bool omit_empty_base_classes)6418 static uint32_t GetIndexForRecordBase(const clang::RecordDecl *record_decl,
6419 const clang::CXXBaseSpecifier *base_spec,
6420 bool omit_empty_base_classes) {
6421 uint32_t child_idx = 0;
6422
6423 const clang::CXXRecordDecl *cxx_record_decl =
6424 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6425
6426 if (cxx_record_decl) {
6427 clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
6428 for (base_class = cxx_record_decl->bases_begin(),
6429 base_class_end = cxx_record_decl->bases_end();
6430 base_class != base_class_end; ++base_class) {
6431 if (omit_empty_base_classes) {
6432 if (BaseSpecifierIsEmpty(base_class))
6433 continue;
6434 }
6435
6436 if (base_class == base_spec)
6437 return child_idx;
6438 ++child_idx;
6439 }
6440 }
6441
6442 return UINT32_MAX;
6443 }
6444
GetIndexForRecordChild(const clang::RecordDecl * record_decl,clang::NamedDecl * canonical_decl,bool omit_empty_base_classes)6445 static uint32_t GetIndexForRecordChild(const clang::RecordDecl *record_decl,
6446 clang::NamedDecl *canonical_decl,
6447 bool omit_empty_base_classes) {
6448 uint32_t child_idx = TypeSystemClang::GetNumBaseClasses(
6449 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl),
6450 omit_empty_base_classes);
6451
6452 clang::RecordDecl::field_iterator field, field_end;
6453 for (field = record_decl->field_begin(), field_end = record_decl->field_end();
6454 field != field_end; ++field, ++child_idx) {
6455 if (field->getCanonicalDecl() == canonical_decl)
6456 return child_idx;
6457 }
6458
6459 return UINT32_MAX;
6460 }
6461
6462 // Look for a child member (doesn't include base classes, but it does include
6463 // their members) in the type hierarchy. Returns an index path into
6464 // "clang_type" on how to reach the appropriate member.
6465 //
6466 // class A
6467 // {
6468 // public:
6469 // int m_a;
6470 // int m_b;
6471 // };
6472 //
6473 // class B
6474 // {
6475 // };
6476 //
6477 // class C :
6478 // public B,
6479 // public A
6480 // {
6481 // };
6482 //
6483 // If we have a clang type that describes "class C", and we wanted to looked
6484 // "m_b" in it:
6485 //
6486 // With omit_empty_base_classes == false we would get an integer array back
6487 // with: { 1, 1 } The first index 1 is the child index for "class A" within
6488 // class C The second index 1 is the child index for "m_b" within class A
6489 //
6490 // With omit_empty_base_classes == true we would get an integer array back
6491 // with: { 0, 1 } The first index 0 is the child index for "class A" within
6492 // class C (since class B doesn't have any members it doesn't count) The second
6493 // index 1 is the child index for "m_b" within class A
6494
GetIndexOfChildMemberWithName(lldb::opaque_compiler_type_t type,const char * name,bool omit_empty_base_classes,std::vector<uint32_t> & child_indexes)6495 size_t TypeSystemClang::GetIndexOfChildMemberWithName(
6496 lldb::opaque_compiler_type_t type, const char *name,
6497 bool omit_empty_base_classes, std::vector<uint32_t> &child_indexes) {
6498 if (type && name && name[0]) {
6499 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6500 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6501 switch (type_class) {
6502 case clang::Type::Record:
6503 if (GetCompleteType(type)) {
6504 const clang::RecordType *record_type =
6505 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
6506 const clang::RecordDecl *record_decl = record_type->getDecl();
6507
6508 assert(record_decl);
6509 uint32_t child_idx = 0;
6510
6511 const clang::CXXRecordDecl *cxx_record_decl =
6512 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6513
6514 // Try and find a field that matches NAME
6515 clang::RecordDecl::field_iterator field, field_end;
6516 llvm::StringRef name_sref(name);
6517 for (field = record_decl->field_begin(),
6518 field_end = record_decl->field_end();
6519 field != field_end; ++field, ++child_idx) {
6520 llvm::StringRef field_name = field->getName();
6521 if (field_name.empty()) {
6522 CompilerType field_type = GetType(field->getType());
6523 child_indexes.push_back(child_idx);
6524 if (field_type.GetIndexOfChildMemberWithName(
6525 name, omit_empty_base_classes, child_indexes))
6526 return child_indexes.size();
6527 child_indexes.pop_back();
6528
6529 } else if (field_name.equals(name_sref)) {
6530 // We have to add on the number of base classes to this index!
6531 child_indexes.push_back(
6532 child_idx + TypeSystemClang::GetNumBaseClasses(
6533 cxx_record_decl, omit_empty_base_classes));
6534 return child_indexes.size();
6535 }
6536 }
6537
6538 if (cxx_record_decl) {
6539 const clang::RecordDecl *parent_record_decl = cxx_record_decl;
6540
6541 // Didn't find things easily, lets let clang do its thang...
6542 clang::IdentifierInfo &ident_ref =
6543 getASTContext().Idents.get(name_sref);
6544 clang::DeclarationName decl_name(&ident_ref);
6545
6546 clang::CXXBasePaths paths;
6547 if (cxx_record_decl->lookupInBases(
6548 [decl_name](const clang::CXXBaseSpecifier *specifier,
6549 clang::CXXBasePath &path) {
6550 path.Decls =
6551 specifier->getType()->getAsCXXRecordDecl()->lookup(
6552 decl_name);
6553 return !path.Decls.empty();
6554 },
6555 paths)) {
6556 clang::CXXBasePaths::const_paths_iterator path,
6557 path_end = paths.end();
6558 for (path = paths.begin(); path != path_end; ++path) {
6559 const size_t num_path_elements = path->size();
6560 for (size_t e = 0; e < num_path_elements; ++e) {
6561 clang::CXXBasePathElement elem = (*path)[e];
6562
6563 child_idx = GetIndexForRecordBase(parent_record_decl, elem.Base,
6564 omit_empty_base_classes);
6565 if (child_idx == UINT32_MAX) {
6566 child_indexes.clear();
6567 return 0;
6568 } else {
6569 child_indexes.push_back(child_idx);
6570 parent_record_decl = llvm::cast<clang::RecordDecl>(
6571 elem.Base->getType()
6572 ->getAs<clang::RecordType>()
6573 ->getDecl());
6574 }
6575 }
6576 for (clang::NamedDecl *path_decl : path->Decls) {
6577 child_idx = GetIndexForRecordChild(
6578 parent_record_decl, path_decl, omit_empty_base_classes);
6579 if (child_idx == UINT32_MAX) {
6580 child_indexes.clear();
6581 return 0;
6582 } else {
6583 child_indexes.push_back(child_idx);
6584 }
6585 }
6586 }
6587 return child_indexes.size();
6588 }
6589 }
6590 }
6591 break;
6592
6593 case clang::Type::ObjCObject:
6594 case clang::Type::ObjCInterface:
6595 if (GetCompleteType(type)) {
6596 llvm::StringRef name_sref(name);
6597 const clang::ObjCObjectType *objc_class_type =
6598 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
6599 assert(objc_class_type);
6600 if (objc_class_type) {
6601 uint32_t child_idx = 0;
6602 clang::ObjCInterfaceDecl *class_interface_decl =
6603 objc_class_type->getInterface();
6604
6605 if (class_interface_decl) {
6606 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6607 ivar_end = class_interface_decl->ivar_end();
6608 clang::ObjCInterfaceDecl *superclass_interface_decl =
6609 class_interface_decl->getSuperClass();
6610
6611 for (ivar_pos = class_interface_decl->ivar_begin();
6612 ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
6613 const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6614
6615 if (ivar_decl->getName().equals(name_sref)) {
6616 if ((!omit_empty_base_classes && superclass_interface_decl) ||
6617 (omit_empty_base_classes &&
6618 ObjCDeclHasIVars(superclass_interface_decl, true)))
6619 ++child_idx;
6620
6621 child_indexes.push_back(child_idx);
6622 return child_indexes.size();
6623 }
6624 }
6625
6626 if (superclass_interface_decl) {
6627 // The super class index is always zero for ObjC classes, so we
6628 // push it onto the child indexes in case we find an ivar in our
6629 // superclass...
6630 child_indexes.push_back(0);
6631
6632 CompilerType superclass_clang_type =
6633 GetType(getASTContext().getObjCInterfaceType(
6634 superclass_interface_decl));
6635 if (superclass_clang_type.GetIndexOfChildMemberWithName(
6636 name, omit_empty_base_classes, child_indexes)) {
6637 // We did find an ivar in a superclass so just return the
6638 // results!
6639 return child_indexes.size();
6640 }
6641
6642 // We didn't find an ivar matching "name" in our superclass, pop
6643 // the superclass zero index that we pushed on above.
6644 child_indexes.pop_back();
6645 }
6646 }
6647 }
6648 }
6649 break;
6650
6651 case clang::Type::ObjCObjectPointer: {
6652 CompilerType objc_object_clang_type = GetType(
6653 llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
6654 ->getPointeeType());
6655 return objc_object_clang_type.GetIndexOfChildMemberWithName(
6656 name, omit_empty_base_classes, child_indexes);
6657 } break;
6658
6659 case clang::Type::ConstantArray: {
6660 // const clang::ConstantArrayType *array =
6661 // llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
6662 // const uint64_t element_count =
6663 // array->getSize().getLimitedValue();
6664 //
6665 // if (idx < element_count)
6666 // {
6667 // std::pair<uint64_t, unsigned> field_type_info =
6668 // ast->getTypeInfo(array->getElementType());
6669 //
6670 // char element_name[32];
6671 // ::snprintf (element_name, sizeof (element_name),
6672 // "%s[%u]", parent_name ? parent_name : "", idx);
6673 //
6674 // child_name.assign(element_name);
6675 // assert(field_type_info.first % 8 == 0);
6676 // child_byte_size = field_type_info.first / 8;
6677 // child_byte_offset = idx * child_byte_size;
6678 // return array->getElementType().getAsOpaquePtr();
6679 // }
6680 } break;
6681
6682 // case clang::Type::MemberPointerType:
6683 // {
6684 // MemberPointerType *mem_ptr_type =
6685 // llvm::cast<MemberPointerType>(qual_type.getTypePtr());
6686 // clang::QualType pointee_type =
6687 // mem_ptr_type->getPointeeType();
6688 //
6689 // if (TypeSystemClang::IsAggregateType
6690 // (pointee_type.getAsOpaquePtr()))
6691 // {
6692 // return GetIndexOfChildWithName (ast,
6693 // mem_ptr_type->getPointeeType().getAsOpaquePtr(),
6694 // name);
6695 // }
6696 // }
6697 // break;
6698 //
6699 case clang::Type::LValueReference:
6700 case clang::Type::RValueReference: {
6701 const clang::ReferenceType *reference_type =
6702 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
6703 clang::QualType pointee_type(reference_type->getPointeeType());
6704 CompilerType pointee_clang_type = GetType(pointee_type);
6705
6706 if (pointee_clang_type.IsAggregateType()) {
6707 return pointee_clang_type.GetIndexOfChildMemberWithName(
6708 name, omit_empty_base_classes, child_indexes);
6709 }
6710 } break;
6711
6712 case clang::Type::Pointer: {
6713 CompilerType pointee_clang_type(GetPointeeType(type));
6714
6715 if (pointee_clang_type.IsAggregateType()) {
6716 return pointee_clang_type.GetIndexOfChildMemberWithName(
6717 name, omit_empty_base_classes, child_indexes);
6718 }
6719 } break;
6720
6721 default:
6722 break;
6723 }
6724 }
6725 return 0;
6726 }
6727
6728 // Get the index of the child of "clang_type" whose name matches. This function
6729 // doesn't descend into the children, but only looks one level deep and name
6730 // matches can include base class names.
6731
6732 uint32_t
GetIndexOfChildWithName(lldb::opaque_compiler_type_t type,const char * name,bool omit_empty_base_classes)6733 TypeSystemClang::GetIndexOfChildWithName(lldb::opaque_compiler_type_t type,
6734 const char *name,
6735 bool omit_empty_base_classes) {
6736 if (type && name && name[0]) {
6737 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6738
6739 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6740
6741 switch (type_class) {
6742 case clang::Type::Record:
6743 if (GetCompleteType(type)) {
6744 const clang::RecordType *record_type =
6745 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
6746 const clang::RecordDecl *record_decl = record_type->getDecl();
6747
6748 assert(record_decl);
6749 uint32_t child_idx = 0;
6750
6751 const clang::CXXRecordDecl *cxx_record_decl =
6752 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6753
6754 if (cxx_record_decl) {
6755 clang::CXXRecordDecl::base_class_const_iterator base_class,
6756 base_class_end;
6757 for (base_class = cxx_record_decl->bases_begin(),
6758 base_class_end = cxx_record_decl->bases_end();
6759 base_class != base_class_end; ++base_class) {
6760 // Skip empty base classes
6761 clang::CXXRecordDecl *base_class_decl =
6762 llvm::cast<clang::CXXRecordDecl>(
6763 base_class->getType()
6764 ->getAs<clang::RecordType>()
6765 ->getDecl());
6766 if (omit_empty_base_classes &&
6767 !TypeSystemClang::RecordHasFields(base_class_decl))
6768 continue;
6769
6770 CompilerType base_class_clang_type = GetType(base_class->getType());
6771 std::string base_class_type_name(
6772 base_class_clang_type.GetTypeName().AsCString(""));
6773 if (base_class_type_name == name)
6774 return child_idx;
6775 ++child_idx;
6776 }
6777 }
6778
6779 // Try and find a field that matches NAME
6780 clang::RecordDecl::field_iterator field, field_end;
6781 llvm::StringRef name_sref(name);
6782 for (field = record_decl->field_begin(),
6783 field_end = record_decl->field_end();
6784 field != field_end; ++field, ++child_idx) {
6785 if (field->getName().equals(name_sref))
6786 return child_idx;
6787 }
6788 }
6789 break;
6790
6791 case clang::Type::ObjCObject:
6792 case clang::Type::ObjCInterface:
6793 if (GetCompleteType(type)) {
6794 llvm::StringRef name_sref(name);
6795 const clang::ObjCObjectType *objc_class_type =
6796 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
6797 assert(objc_class_type);
6798 if (objc_class_type) {
6799 uint32_t child_idx = 0;
6800 clang::ObjCInterfaceDecl *class_interface_decl =
6801 objc_class_type->getInterface();
6802
6803 if (class_interface_decl) {
6804 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6805 ivar_end = class_interface_decl->ivar_end();
6806 clang::ObjCInterfaceDecl *superclass_interface_decl =
6807 class_interface_decl->getSuperClass();
6808
6809 for (ivar_pos = class_interface_decl->ivar_begin();
6810 ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
6811 const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6812
6813 if (ivar_decl->getName().equals(name_sref)) {
6814 if ((!omit_empty_base_classes && superclass_interface_decl) ||
6815 (omit_empty_base_classes &&
6816 ObjCDeclHasIVars(superclass_interface_decl, true)))
6817 ++child_idx;
6818
6819 return child_idx;
6820 }
6821 }
6822
6823 if (superclass_interface_decl) {
6824 if (superclass_interface_decl->getName().equals(name_sref))
6825 return 0;
6826 }
6827 }
6828 }
6829 }
6830 break;
6831
6832 case clang::Type::ObjCObjectPointer: {
6833 CompilerType pointee_clang_type = GetType(
6834 llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
6835 ->getPointeeType());
6836 return pointee_clang_type.GetIndexOfChildWithName(
6837 name, omit_empty_base_classes);
6838 } break;
6839
6840 case clang::Type::ConstantArray: {
6841 // const clang::ConstantArrayType *array =
6842 // llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
6843 // const uint64_t element_count =
6844 // array->getSize().getLimitedValue();
6845 //
6846 // if (idx < element_count)
6847 // {
6848 // std::pair<uint64_t, unsigned> field_type_info =
6849 // ast->getTypeInfo(array->getElementType());
6850 //
6851 // char element_name[32];
6852 // ::snprintf (element_name, sizeof (element_name),
6853 // "%s[%u]", parent_name ? parent_name : "", idx);
6854 //
6855 // child_name.assign(element_name);
6856 // assert(field_type_info.first % 8 == 0);
6857 // child_byte_size = field_type_info.first / 8;
6858 // child_byte_offset = idx * child_byte_size;
6859 // return array->getElementType().getAsOpaquePtr();
6860 // }
6861 } break;
6862
6863 // case clang::Type::MemberPointerType:
6864 // {
6865 // MemberPointerType *mem_ptr_type =
6866 // llvm::cast<MemberPointerType>(qual_type.getTypePtr());
6867 // clang::QualType pointee_type =
6868 // mem_ptr_type->getPointeeType();
6869 //
6870 // if (TypeSystemClang::IsAggregateType
6871 // (pointee_type.getAsOpaquePtr()))
6872 // {
6873 // return GetIndexOfChildWithName (ast,
6874 // mem_ptr_type->getPointeeType().getAsOpaquePtr(),
6875 // name);
6876 // }
6877 // }
6878 // break;
6879 //
6880 case clang::Type::LValueReference:
6881 case clang::Type::RValueReference: {
6882 const clang::ReferenceType *reference_type =
6883 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
6884 CompilerType pointee_type = GetType(reference_type->getPointeeType());
6885
6886 if (pointee_type.IsAggregateType()) {
6887 return pointee_type.GetIndexOfChildWithName(name,
6888 omit_empty_base_classes);
6889 }
6890 } break;
6891
6892 case clang::Type::Pointer: {
6893 const clang::PointerType *pointer_type =
6894 llvm::cast<clang::PointerType>(qual_type.getTypePtr());
6895 CompilerType pointee_type = GetType(pointer_type->getPointeeType());
6896
6897 if (pointee_type.IsAggregateType()) {
6898 return pointee_type.GetIndexOfChildWithName(name,
6899 omit_empty_base_classes);
6900 } else {
6901 // if (parent_name)
6902 // {
6903 // child_name.assign(1, '*');
6904 // child_name += parent_name;
6905 // }
6906 //
6907 // // We have a pointer to an simple type
6908 // if (idx == 0)
6909 // {
6910 // std::pair<uint64_t, unsigned> clang_type_info
6911 // = ast->getTypeInfo(pointee_type);
6912 // assert(clang_type_info.first % 8 == 0);
6913 // child_byte_size = clang_type_info.first / 8;
6914 // child_byte_offset = 0;
6915 // return pointee_type.getAsOpaquePtr();
6916 // }
6917 }
6918 } break;
6919
6920 default:
6921 break;
6922 }
6923 }
6924 return UINT32_MAX;
6925 }
6926
6927 size_t
GetNumTemplateArguments(lldb::opaque_compiler_type_t type)6928 TypeSystemClang::GetNumTemplateArguments(lldb::opaque_compiler_type_t type) {
6929 if (!type)
6930 return 0;
6931
6932 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6933 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6934 switch (type_class) {
6935 case clang::Type::Record:
6936 if (GetCompleteType(type)) {
6937 const clang::CXXRecordDecl *cxx_record_decl =
6938 qual_type->getAsCXXRecordDecl();
6939 if (cxx_record_decl) {
6940 const clang::ClassTemplateSpecializationDecl *template_decl =
6941 llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
6942 cxx_record_decl);
6943 if (template_decl)
6944 return template_decl->getTemplateArgs().size();
6945 }
6946 }
6947 break;
6948
6949 default:
6950 break;
6951 }
6952
6953 return 0;
6954 }
6955
6956 const clang::ClassTemplateSpecializationDecl *
GetAsTemplateSpecialization(lldb::opaque_compiler_type_t type)6957 TypeSystemClang::GetAsTemplateSpecialization(
6958 lldb::opaque_compiler_type_t type) {
6959 if (!type)
6960 return nullptr;
6961
6962 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
6963 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6964 switch (type_class) {
6965 case clang::Type::Record: {
6966 if (! GetCompleteType(type))
6967 return nullptr;
6968 const clang::CXXRecordDecl *cxx_record_decl =
6969 qual_type->getAsCXXRecordDecl();
6970 if (!cxx_record_decl)
6971 return nullptr;
6972 return llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
6973 cxx_record_decl);
6974 }
6975
6976 default:
6977 return nullptr;
6978 }
6979 }
6980
6981 lldb::TemplateArgumentKind
GetTemplateArgumentKind(lldb::opaque_compiler_type_t type,size_t arg_idx)6982 TypeSystemClang::GetTemplateArgumentKind(lldb::opaque_compiler_type_t type,
6983 size_t arg_idx) {
6984 const clang::ClassTemplateSpecializationDecl *template_decl =
6985 GetAsTemplateSpecialization(type);
6986 if (! template_decl || arg_idx >= template_decl->getTemplateArgs().size())
6987 return eTemplateArgumentKindNull;
6988
6989 switch (template_decl->getTemplateArgs()[arg_idx].getKind()) {
6990 case clang::TemplateArgument::Null:
6991 return eTemplateArgumentKindNull;
6992
6993 case clang::TemplateArgument::NullPtr:
6994 return eTemplateArgumentKindNullPtr;
6995
6996 case clang::TemplateArgument::Type:
6997 return eTemplateArgumentKindType;
6998
6999 case clang::TemplateArgument::Declaration:
7000 return eTemplateArgumentKindDeclaration;
7001
7002 case clang::TemplateArgument::Integral:
7003 return eTemplateArgumentKindIntegral;
7004
7005 case clang::TemplateArgument::Template:
7006 return eTemplateArgumentKindTemplate;
7007
7008 case clang::TemplateArgument::TemplateExpansion:
7009 return eTemplateArgumentKindTemplateExpansion;
7010
7011 case clang::TemplateArgument::Expression:
7012 return eTemplateArgumentKindExpression;
7013
7014 case clang::TemplateArgument::Pack:
7015 return eTemplateArgumentKindPack;
7016 }
7017 llvm_unreachable("Unhandled clang::TemplateArgument::ArgKind");
7018 }
7019
7020 CompilerType
GetTypeTemplateArgument(lldb::opaque_compiler_type_t type,size_t idx)7021 TypeSystemClang::GetTypeTemplateArgument(lldb::opaque_compiler_type_t type,
7022 size_t idx) {
7023 const clang::ClassTemplateSpecializationDecl *template_decl =
7024 GetAsTemplateSpecialization(type);
7025 if (!template_decl || idx >= template_decl->getTemplateArgs().size())
7026 return CompilerType();
7027
7028 const clang::TemplateArgument &template_arg =
7029 template_decl->getTemplateArgs()[idx];
7030 if (template_arg.getKind() != clang::TemplateArgument::Type)
7031 return CompilerType();
7032
7033 return GetType(template_arg.getAsType());
7034 }
7035
7036 Optional<CompilerType::IntegralTemplateArgument>
GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type,size_t idx)7037 TypeSystemClang::GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type,
7038 size_t idx) {
7039 const clang::ClassTemplateSpecializationDecl *template_decl =
7040 GetAsTemplateSpecialization(type);
7041 if (! template_decl || idx >= template_decl->getTemplateArgs().size())
7042 return llvm::None;
7043
7044 const clang::TemplateArgument &template_arg =
7045 template_decl->getTemplateArgs()[idx];
7046 if (template_arg.getKind() != clang::TemplateArgument::Integral)
7047 return llvm::None;
7048
7049 return {
7050 {template_arg.getAsIntegral(), GetType(template_arg.getIntegralType())}};
7051 }
7052
GetTypeForFormatters(void * type)7053 CompilerType TypeSystemClang::GetTypeForFormatters(void *type) {
7054 if (type)
7055 return ClangUtil::RemoveFastQualifiers(CompilerType(this, type));
7056 return CompilerType();
7057 }
7058
GetAsEnumDecl(const CompilerType & type)7059 clang::EnumDecl *TypeSystemClang::GetAsEnumDecl(const CompilerType &type) {
7060 const clang::EnumType *enutype =
7061 llvm::dyn_cast<clang::EnumType>(ClangUtil::GetCanonicalQualType(type));
7062 if (enutype)
7063 return enutype->getDecl();
7064 return nullptr;
7065 }
7066
GetAsRecordDecl(const CompilerType & type)7067 clang::RecordDecl *TypeSystemClang::GetAsRecordDecl(const CompilerType &type) {
7068 const clang::RecordType *record_type =
7069 llvm::dyn_cast<clang::RecordType>(ClangUtil::GetCanonicalQualType(type));
7070 if (record_type)
7071 return record_type->getDecl();
7072 return nullptr;
7073 }
7074
GetAsTagDecl(const CompilerType & type)7075 clang::TagDecl *TypeSystemClang::GetAsTagDecl(const CompilerType &type) {
7076 return ClangUtil::GetAsTagDecl(type);
7077 }
7078
7079 clang::TypedefNameDecl *
GetAsTypedefDecl(const CompilerType & type)7080 TypeSystemClang::GetAsTypedefDecl(const CompilerType &type) {
7081 const clang::TypedefType *typedef_type =
7082 llvm::dyn_cast<clang::TypedefType>(ClangUtil::GetQualType(type));
7083 if (typedef_type)
7084 return typedef_type->getDecl();
7085 return nullptr;
7086 }
7087
7088 clang::CXXRecordDecl *
GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type)7089 TypeSystemClang::GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type) {
7090 return GetCanonicalQualType(type)->getAsCXXRecordDecl();
7091 }
7092
7093 clang::ObjCInterfaceDecl *
GetAsObjCInterfaceDecl(const CompilerType & type)7094 TypeSystemClang::GetAsObjCInterfaceDecl(const CompilerType &type) {
7095 const clang::ObjCObjectType *objc_class_type =
7096 llvm::dyn_cast<clang::ObjCObjectType>(
7097 ClangUtil::GetCanonicalQualType(type));
7098 if (objc_class_type)
7099 return objc_class_type->getInterface();
7100 return nullptr;
7101 }
7102
AddFieldToRecordType(const CompilerType & type,llvm::StringRef name,const CompilerType & field_clang_type,AccessType access,uint32_t bitfield_bit_size)7103 clang::FieldDecl *TypeSystemClang::AddFieldToRecordType(
7104 const CompilerType &type, llvm::StringRef name,
7105 const CompilerType &field_clang_type, AccessType access,
7106 uint32_t bitfield_bit_size) {
7107 if (!type.IsValid() || !field_clang_type.IsValid())
7108 return nullptr;
7109 TypeSystemClang *ast =
7110 llvm::dyn_cast_or_null<TypeSystemClang>(type.GetTypeSystem());
7111 if (!ast)
7112 return nullptr;
7113 clang::ASTContext &clang_ast = ast->getASTContext();
7114 clang::IdentifierInfo *ident = nullptr;
7115 if (!name.empty())
7116 ident = &clang_ast.Idents.get(name);
7117
7118 clang::FieldDecl *field = nullptr;
7119
7120 clang::Expr *bit_width = nullptr;
7121 if (bitfield_bit_size != 0) {
7122 llvm::APInt bitfield_bit_size_apint(clang_ast.getTypeSize(clang_ast.IntTy),
7123 bitfield_bit_size);
7124 bit_width = new (clang_ast)
7125 clang::IntegerLiteral(clang_ast, bitfield_bit_size_apint,
7126 clang_ast.IntTy, clang::SourceLocation());
7127 }
7128
7129 clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7130 if (record_decl) {
7131 field = clang::FieldDecl::CreateDeserialized(clang_ast, 0);
7132 field->setDeclContext(record_decl);
7133 field->setDeclName(ident);
7134 field->setType(ClangUtil::GetQualType(field_clang_type));
7135 if (bit_width)
7136 field->setBitWidth(bit_width);
7137 SetMemberOwningModule(field, record_decl);
7138
7139 if (name.empty()) {
7140 // Determine whether this field corresponds to an anonymous struct or
7141 // union.
7142 if (const clang::TagType *TagT =
7143 field->getType()->getAs<clang::TagType>()) {
7144 if (clang::RecordDecl *Rec =
7145 llvm::dyn_cast<clang::RecordDecl>(TagT->getDecl()))
7146 if (!Rec->getDeclName()) {
7147 Rec->setAnonymousStructOrUnion(true);
7148 field->setImplicit();
7149 }
7150 }
7151 }
7152
7153 if (field) {
7154 field->setAccess(
7155 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access));
7156
7157 record_decl->addDecl(field);
7158
7159 VerifyDecl(field);
7160 }
7161 } else {
7162 clang::ObjCInterfaceDecl *class_interface_decl =
7163 ast->GetAsObjCInterfaceDecl(type);
7164
7165 if (class_interface_decl) {
7166 const bool is_synthesized = false;
7167
7168 field_clang_type.GetCompleteType();
7169
7170 auto *ivar = clang::ObjCIvarDecl::CreateDeserialized(clang_ast, 0);
7171 ivar->setDeclContext(class_interface_decl);
7172 ivar->setDeclName(ident);
7173 ivar->setType(ClangUtil::GetQualType(field_clang_type));
7174 ivar->setAccessControl(ConvertAccessTypeToObjCIvarAccessControl(access));
7175 if (bit_width)
7176 ivar->setBitWidth(bit_width);
7177 ivar->setSynthesize(is_synthesized);
7178 field = ivar;
7179 SetMemberOwningModule(field, class_interface_decl);
7180
7181 if (field) {
7182 class_interface_decl->addDecl(field);
7183
7184 VerifyDecl(field);
7185 }
7186 }
7187 }
7188 return field;
7189 }
7190
BuildIndirectFields(const CompilerType & type)7191 void TypeSystemClang::BuildIndirectFields(const CompilerType &type) {
7192 if (!type)
7193 return;
7194
7195 TypeSystemClang *ast = llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
7196 if (!ast)
7197 return;
7198
7199 clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7200
7201 if (!record_decl)
7202 return;
7203
7204 typedef llvm::SmallVector<clang::IndirectFieldDecl *, 1> IndirectFieldVector;
7205
7206 IndirectFieldVector indirect_fields;
7207 clang::RecordDecl::field_iterator field_pos;
7208 clang::RecordDecl::field_iterator field_end_pos = record_decl->field_end();
7209 clang::RecordDecl::field_iterator last_field_pos = field_end_pos;
7210 for (field_pos = record_decl->field_begin(); field_pos != field_end_pos;
7211 last_field_pos = field_pos++) {
7212 if (field_pos->isAnonymousStructOrUnion()) {
7213 clang::QualType field_qual_type = field_pos->getType();
7214
7215 const clang::RecordType *field_record_type =
7216 field_qual_type->getAs<clang::RecordType>();
7217
7218 if (!field_record_type)
7219 continue;
7220
7221 clang::RecordDecl *field_record_decl = field_record_type->getDecl();
7222
7223 if (!field_record_decl)
7224 continue;
7225
7226 for (clang::RecordDecl::decl_iterator
7227 di = field_record_decl->decls_begin(),
7228 de = field_record_decl->decls_end();
7229 di != de; ++di) {
7230 if (clang::FieldDecl *nested_field_decl =
7231 llvm::dyn_cast<clang::FieldDecl>(*di)) {
7232 clang::NamedDecl **chain =
7233 new (ast->getASTContext()) clang::NamedDecl *[2];
7234 chain[0] = *field_pos;
7235 chain[1] = nested_field_decl;
7236 clang::IndirectFieldDecl *indirect_field =
7237 clang::IndirectFieldDecl::Create(
7238 ast->getASTContext(), record_decl, clang::SourceLocation(),
7239 nested_field_decl->getIdentifier(),
7240 nested_field_decl->getType(), {chain, 2});
7241 SetMemberOwningModule(indirect_field, record_decl);
7242
7243 indirect_field->setImplicit();
7244
7245 indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers(
7246 field_pos->getAccess(), nested_field_decl->getAccess()));
7247
7248 indirect_fields.push_back(indirect_field);
7249 } else if (clang::IndirectFieldDecl *nested_indirect_field_decl =
7250 llvm::dyn_cast<clang::IndirectFieldDecl>(*di)) {
7251 size_t nested_chain_size =
7252 nested_indirect_field_decl->getChainingSize();
7253 clang::NamedDecl **chain = new (ast->getASTContext())
7254 clang::NamedDecl *[nested_chain_size + 1];
7255 chain[0] = *field_pos;
7256
7257 int chain_index = 1;
7258 for (clang::IndirectFieldDecl::chain_iterator
7259 nci = nested_indirect_field_decl->chain_begin(),
7260 nce = nested_indirect_field_decl->chain_end();
7261 nci < nce; ++nci) {
7262 chain[chain_index] = *nci;
7263 chain_index++;
7264 }
7265
7266 clang::IndirectFieldDecl *indirect_field =
7267 clang::IndirectFieldDecl::Create(
7268 ast->getASTContext(), record_decl, clang::SourceLocation(),
7269 nested_indirect_field_decl->getIdentifier(),
7270 nested_indirect_field_decl->getType(),
7271 {chain, nested_chain_size + 1});
7272 SetMemberOwningModule(indirect_field, record_decl);
7273
7274 indirect_field->setImplicit();
7275
7276 indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers(
7277 field_pos->getAccess(), nested_indirect_field_decl->getAccess()));
7278
7279 indirect_fields.push_back(indirect_field);
7280 }
7281 }
7282 }
7283 }
7284
7285 // Check the last field to see if it has an incomplete array type as its last
7286 // member and if it does, the tell the record decl about it
7287 if (last_field_pos != field_end_pos) {
7288 if (last_field_pos->getType()->isIncompleteArrayType())
7289 record_decl->hasFlexibleArrayMember();
7290 }
7291
7292 for (IndirectFieldVector::iterator ifi = indirect_fields.begin(),
7293 ife = indirect_fields.end();
7294 ifi < ife; ++ifi) {
7295 record_decl->addDecl(*ifi);
7296 }
7297 }
7298
SetIsPacked(const CompilerType & type)7299 void TypeSystemClang::SetIsPacked(const CompilerType &type) {
7300 if (type) {
7301 TypeSystemClang *ast =
7302 llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
7303 if (ast) {
7304 clang::RecordDecl *record_decl = GetAsRecordDecl(type);
7305
7306 if (!record_decl)
7307 return;
7308
7309 record_decl->addAttr(
7310 clang::PackedAttr::CreateImplicit(ast->getASTContext()));
7311 }
7312 }
7313 }
7314
AddVariableToRecordType(const CompilerType & type,llvm::StringRef name,const CompilerType & var_type,AccessType access)7315 clang::VarDecl *TypeSystemClang::AddVariableToRecordType(
7316 const CompilerType &type, llvm::StringRef name,
7317 const CompilerType &var_type, AccessType access) {
7318 if (!type.IsValid() || !var_type.IsValid())
7319 return nullptr;
7320
7321 TypeSystemClang *ast = llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
7322 if (!ast)
7323 return nullptr;
7324
7325 clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7326 if (!record_decl)
7327 return nullptr;
7328
7329 clang::VarDecl *var_decl = nullptr;
7330 clang::IdentifierInfo *ident = nullptr;
7331 if (!name.empty())
7332 ident = &ast->getASTContext().Idents.get(name);
7333
7334 var_decl = clang::VarDecl::CreateDeserialized(ast->getASTContext(), 0);
7335 var_decl->setDeclContext(record_decl);
7336 var_decl->setDeclName(ident);
7337 var_decl->setType(ClangUtil::GetQualType(var_type));
7338 var_decl->setStorageClass(clang::SC_Static);
7339 SetMemberOwningModule(var_decl, record_decl);
7340 if (!var_decl)
7341 return nullptr;
7342
7343 var_decl->setAccess(
7344 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access));
7345 record_decl->addDecl(var_decl);
7346
7347 VerifyDecl(var_decl);
7348
7349 return var_decl;
7350 }
7351
SetIntegerInitializerForVariable(VarDecl * var,const llvm::APInt & init_value)7352 void TypeSystemClang::SetIntegerInitializerForVariable(
7353 VarDecl *var, const llvm::APInt &init_value) {
7354 assert(!var->hasInit() && "variable already initialized");
7355
7356 clang::ASTContext &ast = var->getASTContext();
7357 QualType qt = var->getType();
7358 assert(qt->isIntegralOrEnumerationType() &&
7359 "only integer or enum types supported");
7360 // If the variable is an enum type, take the underlying integer type as
7361 // the type of the integer literal.
7362 if (const EnumType *enum_type = llvm::dyn_cast<EnumType>(qt.getTypePtr())) {
7363 const EnumDecl *enum_decl = enum_type->getDecl();
7364 qt = enum_decl->getIntegerType();
7365 }
7366 var->setInit(IntegerLiteral::Create(ast, init_value, qt.getUnqualifiedType(),
7367 SourceLocation()));
7368 }
7369
SetFloatingInitializerForVariable(clang::VarDecl * var,const llvm::APFloat & init_value)7370 void TypeSystemClang::SetFloatingInitializerForVariable(
7371 clang::VarDecl *var, const llvm::APFloat &init_value) {
7372 assert(!var->hasInit() && "variable already initialized");
7373
7374 clang::ASTContext &ast = var->getASTContext();
7375 QualType qt = var->getType();
7376 assert(qt->isFloatingType() && "only floating point types supported");
7377 var->setInit(FloatingLiteral::Create(
7378 ast, init_value, true, qt.getUnqualifiedType(), SourceLocation()));
7379 }
7380
AddMethodToCXXRecordType(lldb::opaque_compiler_type_t type,llvm::StringRef name,const char * mangled_name,const CompilerType & method_clang_type,lldb::AccessType access,bool is_virtual,bool is_static,bool is_inline,bool is_explicit,bool is_attr_used,bool is_artificial)7381 clang::CXXMethodDecl *TypeSystemClang::AddMethodToCXXRecordType(
7382 lldb::opaque_compiler_type_t type, llvm::StringRef name,
7383 const char *mangled_name, const CompilerType &method_clang_type,
7384 lldb::AccessType access, bool is_virtual, bool is_static, bool is_inline,
7385 bool is_explicit, bool is_attr_used, bool is_artificial) {
7386 if (!type || !method_clang_type.IsValid() || name.empty())
7387 return nullptr;
7388
7389 clang::QualType record_qual_type(GetCanonicalQualType(type));
7390
7391 clang::CXXRecordDecl *cxx_record_decl =
7392 record_qual_type->getAsCXXRecordDecl();
7393
7394 if (cxx_record_decl == nullptr)
7395 return nullptr;
7396
7397 clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
7398
7399 clang::CXXMethodDecl *cxx_method_decl = nullptr;
7400
7401 clang::DeclarationName decl_name(&getASTContext().Idents.get(name));
7402
7403 const clang::FunctionType *function_type =
7404 llvm::dyn_cast<clang::FunctionType>(method_qual_type.getTypePtr());
7405
7406 if (function_type == nullptr)
7407 return nullptr;
7408
7409 const clang::FunctionProtoType *method_function_prototype(
7410 llvm::dyn_cast<clang::FunctionProtoType>(function_type));
7411
7412 if (!method_function_prototype)
7413 return nullptr;
7414
7415 unsigned int num_params = method_function_prototype->getNumParams();
7416
7417 clang::CXXDestructorDecl *cxx_dtor_decl(nullptr);
7418 clang::CXXConstructorDecl *cxx_ctor_decl(nullptr);
7419
7420 if (is_artificial)
7421 return nullptr; // skip everything artificial
7422
7423 const clang::ExplicitSpecifier explicit_spec(
7424 nullptr /*expr*/, is_explicit ? clang::ExplicitSpecKind::ResolvedTrue
7425 : clang::ExplicitSpecKind::ResolvedFalse);
7426
7427 if (name.startswith("~")) {
7428 cxx_dtor_decl =
7429 clang::CXXDestructorDecl::CreateDeserialized(getASTContext(), 0);
7430 cxx_dtor_decl->setDeclContext(cxx_record_decl);
7431 cxx_dtor_decl->setDeclName(
7432 getASTContext().DeclarationNames.getCXXDestructorName(
7433 getASTContext().getCanonicalType(record_qual_type)));
7434 cxx_dtor_decl->setType(method_qual_type);
7435 cxx_dtor_decl->setImplicit(is_artificial);
7436 cxx_dtor_decl->setInlineSpecified(is_inline);
7437 cxx_dtor_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7438 cxx_method_decl = cxx_dtor_decl;
7439 } else if (decl_name == cxx_record_decl->getDeclName()) {
7440 cxx_ctor_decl = clang::CXXConstructorDecl::CreateDeserialized(
7441 getASTContext(), 0, 0);
7442 cxx_ctor_decl->setDeclContext(cxx_record_decl);
7443 cxx_ctor_decl->setDeclName(
7444 getASTContext().DeclarationNames.getCXXConstructorName(
7445 getASTContext().getCanonicalType(record_qual_type)));
7446 cxx_ctor_decl->setType(method_qual_type);
7447 cxx_ctor_decl->setImplicit(is_artificial);
7448 cxx_ctor_decl->setInlineSpecified(is_inline);
7449 cxx_ctor_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7450 cxx_ctor_decl->setNumCtorInitializers(0);
7451 cxx_ctor_decl->setExplicitSpecifier(explicit_spec);
7452 cxx_method_decl = cxx_ctor_decl;
7453 } else {
7454 clang::StorageClass SC = is_static ? clang::SC_Static : clang::SC_None;
7455 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
7456
7457 if (IsOperator(name, op_kind)) {
7458 if (op_kind != clang::NUM_OVERLOADED_OPERATORS) {
7459 // Check the number of operator parameters. Sometimes we have seen bad
7460 // DWARF that doesn't correctly describe operators and if we try to
7461 // create a method and add it to the class, clang will assert and
7462 // crash, so we need to make sure things are acceptable.
7463 const bool is_method = true;
7464 if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
7465 is_method, op_kind, num_params))
7466 return nullptr;
7467 cxx_method_decl =
7468 clang::CXXMethodDecl::CreateDeserialized(getASTContext(), 0);
7469 cxx_method_decl->setDeclContext(cxx_record_decl);
7470 cxx_method_decl->setDeclName(
7471 getASTContext().DeclarationNames.getCXXOperatorName(op_kind));
7472 cxx_method_decl->setType(method_qual_type);
7473 cxx_method_decl->setStorageClass(SC);
7474 cxx_method_decl->setInlineSpecified(is_inline);
7475 cxx_method_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7476 } else if (num_params == 0) {
7477 // Conversion operators don't take params...
7478 auto *cxx_conversion_decl =
7479 clang::CXXConversionDecl::CreateDeserialized(getASTContext(), 0);
7480 cxx_conversion_decl->setDeclContext(cxx_record_decl);
7481 cxx_conversion_decl->setDeclName(
7482 getASTContext().DeclarationNames.getCXXConversionFunctionName(
7483 getASTContext().getCanonicalType(
7484 function_type->getReturnType())));
7485 cxx_conversion_decl->setType(method_qual_type);
7486 cxx_conversion_decl->setInlineSpecified(is_inline);
7487 cxx_conversion_decl->setExplicitSpecifier(explicit_spec);
7488 cxx_conversion_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7489 cxx_method_decl = cxx_conversion_decl;
7490 }
7491 }
7492
7493 if (cxx_method_decl == nullptr) {
7494 cxx_method_decl =
7495 clang::CXXMethodDecl::CreateDeserialized(getASTContext(), 0);
7496 cxx_method_decl->setDeclContext(cxx_record_decl);
7497 cxx_method_decl->setDeclName(decl_name);
7498 cxx_method_decl->setType(method_qual_type);
7499 cxx_method_decl->setInlineSpecified(is_inline);
7500 cxx_method_decl->setStorageClass(SC);
7501 cxx_method_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7502 }
7503 }
7504 SetMemberOwningModule(cxx_method_decl, cxx_record_decl);
7505
7506 clang::AccessSpecifier access_specifier =
7507 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access);
7508
7509 cxx_method_decl->setAccess(access_specifier);
7510 cxx_method_decl->setVirtualAsWritten(is_virtual);
7511
7512 if (is_attr_used)
7513 cxx_method_decl->addAttr(clang::UsedAttr::CreateImplicit(getASTContext()));
7514
7515 if (mangled_name != nullptr) {
7516 cxx_method_decl->addAttr(clang::AsmLabelAttr::CreateImplicit(
7517 getASTContext(), mangled_name, /*literal=*/false));
7518 }
7519
7520 // Populate the method decl with parameter decls
7521
7522 llvm::SmallVector<clang::ParmVarDecl *, 12> params;
7523
7524 for (unsigned param_index = 0; param_index < num_params; ++param_index) {
7525 params.push_back(clang::ParmVarDecl::Create(
7526 getASTContext(), cxx_method_decl, clang::SourceLocation(),
7527 clang::SourceLocation(),
7528 nullptr, // anonymous
7529 method_function_prototype->getParamType(param_index), nullptr,
7530 clang::SC_None, nullptr));
7531 }
7532
7533 cxx_method_decl->setParams(llvm::ArrayRef<clang::ParmVarDecl *>(params));
7534
7535 cxx_record_decl->addDecl(cxx_method_decl);
7536
7537 // Sometimes the debug info will mention a constructor (default/copy/move),
7538 // destructor, or assignment operator (copy/move) but there won't be any
7539 // version of this in the code. So we check if the function was artificially
7540 // generated and if it is trivial and this lets the compiler/backend know
7541 // that it can inline the IR for these when it needs to and we can avoid a
7542 // "missing function" error when running expressions.
7543
7544 if (is_artificial) {
7545 if (cxx_ctor_decl && ((cxx_ctor_decl->isDefaultConstructor() &&
7546 cxx_record_decl->hasTrivialDefaultConstructor()) ||
7547 (cxx_ctor_decl->isCopyConstructor() &&
7548 cxx_record_decl->hasTrivialCopyConstructor()) ||
7549 (cxx_ctor_decl->isMoveConstructor() &&
7550 cxx_record_decl->hasTrivialMoveConstructor()))) {
7551 cxx_ctor_decl->setDefaulted();
7552 cxx_ctor_decl->setTrivial(true);
7553 } else if (cxx_dtor_decl) {
7554 if (cxx_record_decl->hasTrivialDestructor()) {
7555 cxx_dtor_decl->setDefaulted();
7556 cxx_dtor_decl->setTrivial(true);
7557 }
7558 } else if ((cxx_method_decl->isCopyAssignmentOperator() &&
7559 cxx_record_decl->hasTrivialCopyAssignment()) ||
7560 (cxx_method_decl->isMoveAssignmentOperator() &&
7561 cxx_record_decl->hasTrivialMoveAssignment())) {
7562 cxx_method_decl->setDefaulted();
7563 cxx_method_decl->setTrivial(true);
7564 }
7565 }
7566
7567 VerifyDecl(cxx_method_decl);
7568
7569 return cxx_method_decl;
7570 }
7571
AddMethodOverridesForCXXRecordType(lldb::opaque_compiler_type_t type)7572 void TypeSystemClang::AddMethodOverridesForCXXRecordType(
7573 lldb::opaque_compiler_type_t type) {
7574 if (auto *record = GetAsCXXRecordDecl(type))
7575 for (auto *method : record->methods())
7576 addOverridesForMethod(method);
7577 }
7578
7579 #pragma mark C++ Base Classes
7580
7581 std::unique_ptr<clang::CXXBaseSpecifier>
CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type,AccessType access,bool is_virtual,bool base_of_class)7582 TypeSystemClang::CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type,
7583 AccessType access, bool is_virtual,
7584 bool base_of_class) {
7585 if (!type)
7586 return nullptr;
7587
7588 return std::make_unique<clang::CXXBaseSpecifier>(
7589 clang::SourceRange(), is_virtual, base_of_class,
7590 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access),
7591 getASTContext().getTrivialTypeSourceInfo(GetQualType(type)),
7592 clang::SourceLocation());
7593 }
7594
TransferBaseClasses(lldb::opaque_compiler_type_t type,std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases)7595 bool TypeSystemClang::TransferBaseClasses(
7596 lldb::opaque_compiler_type_t type,
7597 std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases) {
7598 if (!type)
7599 return false;
7600 clang::CXXRecordDecl *cxx_record_decl = GetAsCXXRecordDecl(type);
7601 if (!cxx_record_decl)
7602 return false;
7603 std::vector<clang::CXXBaseSpecifier *> raw_bases;
7604 raw_bases.reserve(bases.size());
7605
7606 // Clang will make a copy of them, so it's ok that we pass pointers that we're
7607 // about to destroy.
7608 for (auto &b : bases)
7609 raw_bases.push_back(b.get());
7610 cxx_record_decl->setBases(raw_bases.data(), raw_bases.size());
7611 return true;
7612 }
7613
SetObjCSuperClass(const CompilerType & type,const CompilerType & superclass_clang_type)7614 bool TypeSystemClang::SetObjCSuperClass(
7615 const CompilerType &type, const CompilerType &superclass_clang_type) {
7616 TypeSystemClang *ast =
7617 llvm::dyn_cast_or_null<TypeSystemClang>(type.GetTypeSystem());
7618 if (!ast)
7619 return false;
7620 clang::ASTContext &clang_ast = ast->getASTContext();
7621
7622 if (type && superclass_clang_type.IsValid() &&
7623 superclass_clang_type.GetTypeSystem() == type.GetTypeSystem()) {
7624 clang::ObjCInterfaceDecl *class_interface_decl =
7625 GetAsObjCInterfaceDecl(type);
7626 clang::ObjCInterfaceDecl *super_interface_decl =
7627 GetAsObjCInterfaceDecl(superclass_clang_type);
7628 if (class_interface_decl && super_interface_decl) {
7629 class_interface_decl->setSuperClass(clang_ast.getTrivialTypeSourceInfo(
7630 clang_ast.getObjCInterfaceType(super_interface_decl)));
7631 return true;
7632 }
7633 }
7634 return false;
7635 }
7636
AddObjCClassProperty(const CompilerType & type,const char * property_name,const CompilerType & property_clang_type,clang::ObjCIvarDecl * ivar_decl,const char * property_setter_name,const char * property_getter_name,uint32_t property_attributes,ClangASTMetadata * metadata)7637 bool TypeSystemClang::AddObjCClassProperty(
7638 const CompilerType &type, const char *property_name,
7639 const CompilerType &property_clang_type, clang::ObjCIvarDecl *ivar_decl,
7640 const char *property_setter_name, const char *property_getter_name,
7641 uint32_t property_attributes, ClangASTMetadata *metadata) {
7642 if (!type || !property_clang_type.IsValid() || property_name == nullptr ||
7643 property_name[0] == '\0')
7644 return false;
7645 TypeSystemClang *ast = llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
7646 if (!ast)
7647 return false;
7648 clang::ASTContext &clang_ast = ast->getASTContext();
7649
7650 clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
7651 if (!class_interface_decl)
7652 return false;
7653
7654 CompilerType property_clang_type_to_access;
7655
7656 if (property_clang_type.IsValid())
7657 property_clang_type_to_access = property_clang_type;
7658 else if (ivar_decl)
7659 property_clang_type_to_access = ast->GetType(ivar_decl->getType());
7660
7661 if (!class_interface_decl || !property_clang_type_to_access.IsValid())
7662 return false;
7663
7664 clang::TypeSourceInfo *prop_type_source;
7665 if (ivar_decl)
7666 prop_type_source = clang_ast.getTrivialTypeSourceInfo(ivar_decl->getType());
7667 else
7668 prop_type_source = clang_ast.getTrivialTypeSourceInfo(
7669 ClangUtil::GetQualType(property_clang_type));
7670
7671 clang::ObjCPropertyDecl *property_decl =
7672 clang::ObjCPropertyDecl::CreateDeserialized(clang_ast, 0);
7673 property_decl->setDeclContext(class_interface_decl);
7674 property_decl->setDeclName(&clang_ast.Idents.get(property_name));
7675 property_decl->setType(ivar_decl
7676 ? ivar_decl->getType()
7677 : ClangUtil::GetQualType(property_clang_type),
7678 prop_type_source);
7679 SetMemberOwningModule(property_decl, class_interface_decl);
7680
7681 if (!property_decl)
7682 return false;
7683
7684 if (metadata)
7685 ast->SetMetadata(property_decl, *metadata);
7686
7687 class_interface_decl->addDecl(property_decl);
7688
7689 clang::Selector setter_sel, getter_sel;
7690
7691 if (property_setter_name) {
7692 std::string property_setter_no_colon(property_setter_name,
7693 strlen(property_setter_name) - 1);
7694 clang::IdentifierInfo *setter_ident =
7695 &clang_ast.Idents.get(property_setter_no_colon);
7696 setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident);
7697 } else if (!(property_attributes & DW_APPLE_PROPERTY_readonly)) {
7698 std::string setter_sel_string("set");
7699 setter_sel_string.push_back(::toupper(property_name[0]));
7700 setter_sel_string.append(&property_name[1]);
7701 clang::IdentifierInfo *setter_ident =
7702 &clang_ast.Idents.get(setter_sel_string);
7703 setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident);
7704 }
7705 property_decl->setSetterName(setter_sel);
7706 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_setter);
7707
7708 if (property_getter_name != nullptr) {
7709 clang::IdentifierInfo *getter_ident =
7710 &clang_ast.Idents.get(property_getter_name);
7711 getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident);
7712 } else {
7713 clang::IdentifierInfo *getter_ident = &clang_ast.Idents.get(property_name);
7714 getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident);
7715 }
7716 property_decl->setGetterName(getter_sel);
7717 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_getter);
7718
7719 if (ivar_decl)
7720 property_decl->setPropertyIvarDecl(ivar_decl);
7721
7722 if (property_attributes & DW_APPLE_PROPERTY_readonly)
7723 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readonly);
7724 if (property_attributes & DW_APPLE_PROPERTY_readwrite)
7725 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readwrite);
7726 if (property_attributes & DW_APPLE_PROPERTY_assign)
7727 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_assign);
7728 if (property_attributes & DW_APPLE_PROPERTY_retain)
7729 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_retain);
7730 if (property_attributes & DW_APPLE_PROPERTY_copy)
7731 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_copy);
7732 if (property_attributes & DW_APPLE_PROPERTY_nonatomic)
7733 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_nonatomic);
7734 if (property_attributes & ObjCPropertyAttribute::kind_nullability)
7735 property_decl->setPropertyAttributes(
7736 ObjCPropertyAttribute::kind_nullability);
7737 if (property_attributes & ObjCPropertyAttribute::kind_null_resettable)
7738 property_decl->setPropertyAttributes(
7739 ObjCPropertyAttribute::kind_null_resettable);
7740 if (property_attributes & ObjCPropertyAttribute::kind_class)
7741 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_class);
7742
7743 const bool isInstance =
7744 (property_attributes & ObjCPropertyAttribute::kind_class) == 0;
7745
7746 clang::ObjCMethodDecl *getter = nullptr;
7747 if (!getter_sel.isNull())
7748 getter = isInstance ? class_interface_decl->lookupInstanceMethod(getter_sel)
7749 : class_interface_decl->lookupClassMethod(getter_sel);
7750 if (!getter_sel.isNull() && !getter) {
7751 const bool isVariadic = false;
7752 const bool isPropertyAccessor = true;
7753 const bool isSynthesizedAccessorStub = false;
7754 const bool isImplicitlyDeclared = true;
7755 const bool isDefined = false;
7756 const clang::ObjCMethodDecl::ImplementationControl impControl =
7757 clang::ObjCMethodDecl::None;
7758 const bool HasRelatedResultType = false;
7759
7760 getter = clang::ObjCMethodDecl::CreateDeserialized(clang_ast, 0);
7761 getter->setDeclName(getter_sel);
7762 getter->setReturnType(ClangUtil::GetQualType(property_clang_type_to_access));
7763 getter->setDeclContext(class_interface_decl);
7764 getter->setInstanceMethod(isInstance);
7765 getter->setVariadic(isVariadic);
7766 getter->setPropertyAccessor(isPropertyAccessor);
7767 getter->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
7768 getter->setImplicit(isImplicitlyDeclared);
7769 getter->setDefined(isDefined);
7770 getter->setDeclImplementation(impControl);
7771 getter->setRelatedResultType(HasRelatedResultType);
7772 SetMemberOwningModule(getter, class_interface_decl);
7773
7774 if (getter) {
7775 if (metadata)
7776 ast->SetMetadata(getter, *metadata);
7777
7778 getter->setMethodParams(clang_ast, llvm::ArrayRef<clang::ParmVarDecl *>(),
7779 llvm::ArrayRef<clang::SourceLocation>());
7780 class_interface_decl->addDecl(getter);
7781 }
7782 }
7783 if (getter) {
7784 getter->setPropertyAccessor(true);
7785 property_decl->setGetterMethodDecl(getter);
7786 }
7787
7788 clang::ObjCMethodDecl *setter = nullptr;
7789 setter = isInstance ? class_interface_decl->lookupInstanceMethod(setter_sel)
7790 : class_interface_decl->lookupClassMethod(setter_sel);
7791 if (!setter_sel.isNull() && !setter) {
7792 clang::QualType result_type = clang_ast.VoidTy;
7793 const bool isVariadic = false;
7794 const bool isPropertyAccessor = true;
7795 const bool isSynthesizedAccessorStub = false;
7796 const bool isImplicitlyDeclared = true;
7797 const bool isDefined = false;
7798 const clang::ObjCMethodDecl::ImplementationControl impControl =
7799 clang::ObjCMethodDecl::None;
7800 const bool HasRelatedResultType = false;
7801
7802 setter = clang::ObjCMethodDecl::CreateDeserialized(clang_ast, 0);
7803 setter->setDeclName(setter_sel);
7804 setter->setReturnType(result_type);
7805 setter->setDeclContext(class_interface_decl);
7806 setter->setInstanceMethod(isInstance);
7807 setter->setVariadic(isVariadic);
7808 setter->setPropertyAccessor(isPropertyAccessor);
7809 setter->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
7810 setter->setImplicit(isImplicitlyDeclared);
7811 setter->setDefined(isDefined);
7812 setter->setDeclImplementation(impControl);
7813 setter->setRelatedResultType(HasRelatedResultType);
7814 SetMemberOwningModule(setter, class_interface_decl);
7815
7816 if (setter) {
7817 if (metadata)
7818 ast->SetMetadata(setter, *metadata);
7819
7820 llvm::SmallVector<clang::ParmVarDecl *, 1> params;
7821 params.push_back(clang::ParmVarDecl::Create(
7822 clang_ast, setter, clang::SourceLocation(), clang::SourceLocation(),
7823 nullptr, // anonymous
7824 ClangUtil::GetQualType(property_clang_type_to_access), nullptr,
7825 clang::SC_Auto, nullptr));
7826
7827 setter->setMethodParams(clang_ast,
7828 llvm::ArrayRef<clang::ParmVarDecl *>(params),
7829 llvm::ArrayRef<clang::SourceLocation>());
7830
7831 class_interface_decl->addDecl(setter);
7832 }
7833 }
7834 if (setter) {
7835 setter->setPropertyAccessor(true);
7836 property_decl->setSetterMethodDecl(setter);
7837 }
7838
7839 return true;
7840 }
7841
IsObjCClassTypeAndHasIVars(const CompilerType & type,bool check_superclass)7842 bool TypeSystemClang::IsObjCClassTypeAndHasIVars(const CompilerType &type,
7843 bool check_superclass) {
7844 clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
7845 if (class_interface_decl)
7846 return ObjCDeclHasIVars(class_interface_decl, check_superclass);
7847 return false;
7848 }
7849
AddMethodToObjCObjectType(const CompilerType & type,const char * name,const CompilerType & method_clang_type,lldb::AccessType access,bool is_artificial,bool is_variadic,bool is_objc_direct_call)7850 clang::ObjCMethodDecl *TypeSystemClang::AddMethodToObjCObjectType(
7851 const CompilerType &type,
7852 const char *name, // the full symbol name as seen in the symbol table
7853 // (lldb::opaque_compiler_type_t type, "-[NString
7854 // stringWithCString:]")
7855 const CompilerType &method_clang_type, lldb::AccessType access,
7856 bool is_artificial, bool is_variadic, bool is_objc_direct_call) {
7857 if (!type || !method_clang_type.IsValid())
7858 return nullptr;
7859
7860 clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
7861
7862 if (class_interface_decl == nullptr)
7863 return nullptr;
7864 TypeSystemClang *lldb_ast =
7865 llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
7866 if (lldb_ast == nullptr)
7867 return nullptr;
7868 clang::ASTContext &ast = lldb_ast->getASTContext();
7869
7870 const char *selector_start = ::strchr(name, ' ');
7871 if (selector_start == nullptr)
7872 return nullptr;
7873
7874 selector_start++;
7875 llvm::SmallVector<clang::IdentifierInfo *, 12> selector_idents;
7876
7877 size_t len = 0;
7878 const char *start;
7879
7880 unsigned num_selectors_with_args = 0;
7881 for (start = selector_start; start && *start != '\0' && *start != ']';
7882 start += len) {
7883 len = ::strcspn(start, ":]");
7884 bool has_arg = (start[len] == ':');
7885 if (has_arg)
7886 ++num_selectors_with_args;
7887 selector_idents.push_back(&ast.Idents.get(llvm::StringRef(start, len)));
7888 if (has_arg)
7889 len += 1;
7890 }
7891
7892 if (selector_idents.size() == 0)
7893 return nullptr;
7894
7895 clang::Selector method_selector = ast.Selectors.getSelector(
7896 num_selectors_with_args ? selector_idents.size() : 0,
7897 selector_idents.data());
7898
7899 clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
7900
7901 // Populate the method decl with parameter decls
7902 const clang::Type *method_type(method_qual_type.getTypePtr());
7903
7904 if (method_type == nullptr)
7905 return nullptr;
7906
7907 const clang::FunctionProtoType *method_function_prototype(
7908 llvm::dyn_cast<clang::FunctionProtoType>(method_type));
7909
7910 if (!method_function_prototype)
7911 return nullptr;
7912
7913 const bool isInstance = (name[0] == '-');
7914 const bool isVariadic = is_variadic;
7915 const bool isPropertyAccessor = false;
7916 const bool isSynthesizedAccessorStub = false;
7917 /// Force this to true because we don't have source locations.
7918 const bool isImplicitlyDeclared = true;
7919 const bool isDefined = false;
7920 const clang::ObjCMethodDecl::ImplementationControl impControl =
7921 clang::ObjCMethodDecl::None;
7922 const bool HasRelatedResultType = false;
7923
7924 const unsigned num_args = method_function_prototype->getNumParams();
7925
7926 if (num_args != num_selectors_with_args)
7927 return nullptr; // some debug information is corrupt. We are not going to
7928 // deal with it.
7929
7930 auto *objc_method_decl = clang::ObjCMethodDecl::CreateDeserialized(ast, 0);
7931 objc_method_decl->setDeclName(method_selector);
7932 objc_method_decl->setReturnType(method_function_prototype->getReturnType());
7933 objc_method_decl->setDeclContext(
7934 lldb_ast->GetDeclContextForType(ClangUtil::GetQualType(type)));
7935 objc_method_decl->setInstanceMethod(isInstance);
7936 objc_method_decl->setVariadic(isVariadic);
7937 objc_method_decl->setPropertyAccessor(isPropertyAccessor);
7938 objc_method_decl->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
7939 objc_method_decl->setImplicit(isImplicitlyDeclared);
7940 objc_method_decl->setDefined(isDefined);
7941 objc_method_decl->setDeclImplementation(impControl);
7942 objc_method_decl->setRelatedResultType(HasRelatedResultType);
7943 SetMemberOwningModule(objc_method_decl, class_interface_decl);
7944
7945 if (objc_method_decl == nullptr)
7946 return nullptr;
7947
7948 if (num_args > 0) {
7949 llvm::SmallVector<clang::ParmVarDecl *, 12> params;
7950
7951 for (unsigned param_index = 0; param_index < num_args; ++param_index) {
7952 params.push_back(clang::ParmVarDecl::Create(
7953 ast, objc_method_decl, clang::SourceLocation(),
7954 clang::SourceLocation(),
7955 nullptr, // anonymous
7956 method_function_prototype->getParamType(param_index), nullptr,
7957 clang::SC_Auto, nullptr));
7958 }
7959
7960 objc_method_decl->setMethodParams(
7961 ast, llvm::ArrayRef<clang::ParmVarDecl *>(params),
7962 llvm::ArrayRef<clang::SourceLocation>());
7963 }
7964
7965 if (is_objc_direct_call) {
7966 // Add a the objc_direct attribute to the declaration we generate that
7967 // we generate a direct method call for this ObjCMethodDecl.
7968 objc_method_decl->addAttr(
7969 clang::ObjCDirectAttr::CreateImplicit(ast, SourceLocation()));
7970 // Usually Sema is creating implicit parameters (e.g., self) when it
7971 // parses the method. We don't have a parsing Sema when we build our own
7972 // AST here so we manually need to create these implicit parameters to
7973 // make the direct call code generation happy.
7974 objc_method_decl->createImplicitParams(ast, class_interface_decl);
7975 }
7976
7977 class_interface_decl->addDecl(objc_method_decl);
7978
7979 VerifyDecl(objc_method_decl);
7980
7981 return objc_method_decl;
7982 }
7983
SetHasExternalStorage(lldb::opaque_compiler_type_t type,bool has_extern)7984 bool TypeSystemClang::SetHasExternalStorage(lldb::opaque_compiler_type_t type,
7985 bool has_extern) {
7986 if (!type)
7987 return false;
7988
7989 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
7990
7991 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7992 switch (type_class) {
7993 case clang::Type::Record: {
7994 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
7995 if (cxx_record_decl) {
7996 cxx_record_decl->setHasExternalLexicalStorage(has_extern);
7997 cxx_record_decl->setHasExternalVisibleStorage(has_extern);
7998 return true;
7999 }
8000 } break;
8001
8002 case clang::Type::Enum: {
8003 clang::EnumDecl *enum_decl =
8004 llvm::cast<clang::EnumType>(qual_type)->getDecl();
8005 if (enum_decl) {
8006 enum_decl->setHasExternalLexicalStorage(has_extern);
8007 enum_decl->setHasExternalVisibleStorage(has_extern);
8008 return true;
8009 }
8010 } break;
8011
8012 case clang::Type::ObjCObject:
8013 case clang::Type::ObjCInterface: {
8014 const clang::ObjCObjectType *objc_class_type =
8015 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
8016 assert(objc_class_type);
8017 if (objc_class_type) {
8018 clang::ObjCInterfaceDecl *class_interface_decl =
8019 objc_class_type->getInterface();
8020
8021 if (class_interface_decl) {
8022 class_interface_decl->setHasExternalLexicalStorage(has_extern);
8023 class_interface_decl->setHasExternalVisibleStorage(has_extern);
8024 return true;
8025 }
8026 }
8027 } break;
8028
8029 default:
8030 break;
8031 }
8032 return false;
8033 }
8034
8035 #pragma mark TagDecl
8036
StartTagDeclarationDefinition(const CompilerType & type)8037 bool TypeSystemClang::StartTagDeclarationDefinition(const CompilerType &type) {
8038 clang::QualType qual_type(ClangUtil::GetQualType(type));
8039 if (!qual_type.isNull()) {
8040 const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8041 if (tag_type) {
8042 clang::TagDecl *tag_decl = tag_type->getDecl();
8043 if (tag_decl) {
8044 tag_decl->startDefinition();
8045 return true;
8046 }
8047 }
8048
8049 const clang::ObjCObjectType *object_type =
8050 qual_type->getAs<clang::ObjCObjectType>();
8051 if (object_type) {
8052 clang::ObjCInterfaceDecl *interface_decl = object_type->getInterface();
8053 if (interface_decl) {
8054 interface_decl->startDefinition();
8055 return true;
8056 }
8057 }
8058 }
8059 return false;
8060 }
8061
CompleteTagDeclarationDefinition(const CompilerType & type)8062 bool TypeSystemClang::CompleteTagDeclarationDefinition(
8063 const CompilerType &type) {
8064 clang::QualType qual_type(ClangUtil::GetQualType(type));
8065 if (qual_type.isNull())
8066 return false;
8067
8068 // Make sure we use the same methodology as
8069 // TypeSystemClang::StartTagDeclarationDefinition() as to how we start/end
8070 // the definition.
8071 const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8072 if (tag_type) {
8073 clang::TagDecl *tag_decl = tag_type->getDecl();
8074
8075 if (auto *cxx_record_decl = llvm::dyn_cast<CXXRecordDecl>(tag_decl)) {
8076 // If we have a move constructor declared but no copy constructor we
8077 // need to explicitly mark it as deleted. Usually Sema would do this for
8078 // us in Sema::DeclareImplicitCopyConstructor but we don't have a Sema
8079 // when building an AST from debug information.
8080 // See also:
8081 // C++11 [class.copy]p7, p18:
8082 // If the class definition declares a move constructor or move assignment
8083 // operator, an implicitly declared copy constructor or copy assignment
8084 // operator is defined as deleted.
8085 if (cxx_record_decl->hasUserDeclaredMoveConstructor() ||
8086 cxx_record_decl->hasUserDeclaredMoveAssignment()) {
8087 if (cxx_record_decl->needsImplicitCopyConstructor())
8088 cxx_record_decl->setImplicitCopyConstructorIsDeleted();
8089 if (cxx_record_decl->needsImplicitCopyAssignment())
8090 cxx_record_decl->setImplicitCopyAssignmentIsDeleted();
8091 }
8092
8093 if (!cxx_record_decl->isCompleteDefinition())
8094 cxx_record_decl->completeDefinition();
8095 cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
8096 cxx_record_decl->setHasExternalLexicalStorage(false);
8097 cxx_record_decl->setHasExternalVisibleStorage(false);
8098 return true;
8099 }
8100 }
8101
8102 const clang::EnumType *enutype = qual_type->getAs<clang::EnumType>();
8103
8104 if (!enutype)
8105 return false;
8106 clang::EnumDecl *enum_decl = enutype->getDecl();
8107
8108 if (enum_decl->isCompleteDefinition())
8109 return true;
8110
8111 TypeSystemClang *lldb_ast =
8112 llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
8113 if (lldb_ast == nullptr)
8114 return false;
8115 clang::ASTContext &ast = lldb_ast->getASTContext();
8116
8117 /// TODO This really needs to be fixed.
8118
8119 QualType integer_type(enum_decl->getIntegerType());
8120 if (!integer_type.isNull()) {
8121 unsigned NumPositiveBits = 1;
8122 unsigned NumNegativeBits = 0;
8123
8124 clang::QualType promotion_qual_type;
8125 // If the enum integer type is less than an integer in bit width,
8126 // then we must promote it to an integer size.
8127 if (ast.getTypeSize(enum_decl->getIntegerType()) <
8128 ast.getTypeSize(ast.IntTy)) {
8129 if (enum_decl->getIntegerType()->isSignedIntegerType())
8130 promotion_qual_type = ast.IntTy;
8131 else
8132 promotion_qual_type = ast.UnsignedIntTy;
8133 } else
8134 promotion_qual_type = enum_decl->getIntegerType();
8135
8136 enum_decl->completeDefinition(enum_decl->getIntegerType(),
8137 promotion_qual_type, NumPositiveBits,
8138 NumNegativeBits);
8139 }
8140 return true;
8141 }
8142
AddEnumerationValueToEnumerationType(const CompilerType & enum_type,const Declaration & decl,const char * name,const llvm::APSInt & value)8143 clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType(
8144 const CompilerType &enum_type, const Declaration &decl, const char *name,
8145 const llvm::APSInt &value) {
8146
8147 if (!enum_type || ConstString(name).IsEmpty())
8148 return nullptr;
8149
8150 lldbassert(enum_type.GetTypeSystem() == static_cast<TypeSystem *>(this));
8151
8152 lldb::opaque_compiler_type_t enum_opaque_compiler_type =
8153 enum_type.GetOpaqueQualType();
8154
8155 if (!enum_opaque_compiler_type)
8156 return nullptr;
8157
8158 clang::QualType enum_qual_type(
8159 GetCanonicalQualType(enum_opaque_compiler_type));
8160
8161 const clang::Type *clang_type = enum_qual_type.getTypePtr();
8162
8163 if (!clang_type)
8164 return nullptr;
8165
8166 const clang::EnumType *enutype = llvm::dyn_cast<clang::EnumType>(clang_type);
8167
8168 if (!enutype)
8169 return nullptr;
8170
8171 clang::EnumConstantDecl *enumerator_decl =
8172 clang::EnumConstantDecl::CreateDeserialized(getASTContext(), 0);
8173 enumerator_decl->setDeclContext(enutype->getDecl());
8174 if (name && name[0])
8175 enumerator_decl->setDeclName(&getASTContext().Idents.get(name));
8176 enumerator_decl->setType(clang::QualType(enutype, 0));
8177 enumerator_decl->setInitVal(value);
8178 SetMemberOwningModule(enumerator_decl, enutype->getDecl());
8179
8180 if (!enumerator_decl)
8181 return nullptr;
8182
8183 enutype->getDecl()->addDecl(enumerator_decl);
8184
8185 VerifyDecl(enumerator_decl);
8186 return enumerator_decl;
8187 }
8188
AddEnumerationValueToEnumerationType(const CompilerType & enum_type,const Declaration & decl,const char * name,int64_t enum_value,uint32_t enum_value_bit_size)8189 clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType(
8190 const CompilerType &enum_type, const Declaration &decl, const char *name,
8191 int64_t enum_value, uint32_t enum_value_bit_size) {
8192 CompilerType underlying_type = GetEnumerationIntegerType(enum_type);
8193 bool is_signed = false;
8194 underlying_type.IsIntegerType(is_signed);
8195
8196 llvm::APSInt value(enum_value_bit_size, is_signed);
8197 value = enum_value;
8198
8199 return AddEnumerationValueToEnumerationType(enum_type, decl, name, value);
8200 }
8201
GetEnumerationIntegerType(CompilerType type)8202 CompilerType TypeSystemClang::GetEnumerationIntegerType(CompilerType type) {
8203 clang::QualType qt(ClangUtil::GetQualType(type));
8204 const clang::Type *clang_type = qt.getTypePtrOrNull();
8205 const auto *enum_type = llvm::dyn_cast_or_null<clang::EnumType>(clang_type);
8206 if (!enum_type)
8207 return CompilerType();
8208
8209 return GetType(enum_type->getDecl()->getIntegerType());
8210 }
8211
8212 CompilerType
CreateMemberPointerType(const CompilerType & type,const CompilerType & pointee_type)8213 TypeSystemClang::CreateMemberPointerType(const CompilerType &type,
8214 const CompilerType &pointee_type) {
8215 if (type && pointee_type.IsValid() &&
8216 type.GetTypeSystem() == pointee_type.GetTypeSystem()) {
8217 TypeSystemClang *ast =
8218 llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
8219 if (!ast)
8220 return CompilerType();
8221 return ast->GetType(ast->getASTContext().getMemberPointerType(
8222 ClangUtil::GetQualType(pointee_type),
8223 ClangUtil::GetQualType(type).getTypePtr()));
8224 }
8225 return CompilerType();
8226 }
8227
8228 // Dumping types
8229 #define DEPTH_INCREMENT 2
8230
8231 #ifndef NDEBUG
8232 LLVM_DUMP_METHOD void
dump(lldb::opaque_compiler_type_t type) const8233 TypeSystemClang::dump(lldb::opaque_compiler_type_t type) const {
8234 if (!type)
8235 return;
8236 clang::QualType qual_type(GetQualType(type));
8237 qual_type.dump();
8238 }
8239 #endif
8240
Dump(Stream & s)8241 void TypeSystemClang::Dump(Stream &s) {
8242 Decl *tu = Decl::castFromDeclContext(GetTranslationUnitDecl());
8243 tu->dump(s.AsRawOstream());
8244 }
8245
DumpFromSymbolFile(Stream & s,llvm::StringRef symbol_name)8246 void TypeSystemClang::DumpFromSymbolFile(Stream &s,
8247 llvm::StringRef symbol_name) {
8248 SymbolFile *symfile = GetSymbolFile();
8249
8250 if (!symfile)
8251 return;
8252
8253 lldb_private::TypeList type_list;
8254 symfile->GetTypes(nullptr, eTypeClassAny, type_list);
8255 size_t ntypes = type_list.GetSize();
8256
8257 for (size_t i = 0; i < ntypes; ++i) {
8258 TypeSP type = type_list.GetTypeAtIndex(i);
8259
8260 if (!symbol_name.empty())
8261 if (symbol_name != type->GetName().GetStringRef())
8262 continue;
8263
8264 s << type->GetName().AsCString() << "\n";
8265
8266 CompilerType full_type = type->GetFullCompilerType();
8267 if (clang::TagDecl *tag_decl = GetAsTagDecl(full_type)) {
8268 tag_decl->dump(s.AsRawOstream());
8269 continue;
8270 }
8271 if (clang::TypedefNameDecl *typedef_decl = GetAsTypedefDecl(full_type)) {
8272 typedef_decl->dump(s.AsRawOstream());
8273 continue;
8274 }
8275 if (auto *objc_obj = llvm::dyn_cast<clang::ObjCObjectType>(
8276 ClangUtil::GetQualType(full_type).getTypePtr())) {
8277 if (clang::ObjCInterfaceDecl *interface_decl = objc_obj->getInterface()) {
8278 interface_decl->dump(s.AsRawOstream());
8279 continue;
8280 }
8281 }
8282 GetCanonicalQualType(full_type.GetOpaqueQualType())
8283 .dump(s.AsRawOstream(), getASTContext());
8284 }
8285 }
8286
DumpValue(lldb::opaque_compiler_type_t type,ExecutionContext * exe_ctx,Stream * s,lldb::Format format,const lldb_private::DataExtractor & data,lldb::offset_t data_byte_offset,size_t data_byte_size,uint32_t bitfield_bit_size,uint32_t bitfield_bit_offset,bool show_types,bool show_summary,bool verbose,uint32_t depth)8287 void TypeSystemClang::DumpValue(
8288 lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, Stream *s,
8289 lldb::Format format, const lldb_private::DataExtractor &data,
8290 lldb::offset_t data_byte_offset, size_t data_byte_size,
8291 uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset, bool show_types,
8292 bool show_summary, bool verbose, uint32_t depth) {
8293 if (!type)
8294 return;
8295
8296 clang::QualType qual_type(GetQualType(type));
8297 switch (qual_type->getTypeClass()) {
8298 case clang::Type::Record:
8299 if (GetCompleteType(type)) {
8300 const clang::RecordType *record_type =
8301 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
8302 const clang::RecordDecl *record_decl = record_type->getDecl();
8303 assert(record_decl);
8304 uint32_t field_bit_offset = 0;
8305 uint32_t field_byte_offset = 0;
8306 const clang::ASTRecordLayout &record_layout =
8307 getASTContext().getASTRecordLayout(record_decl);
8308 uint32_t child_idx = 0;
8309
8310 const clang::CXXRecordDecl *cxx_record_decl =
8311 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
8312 if (cxx_record_decl) {
8313 // We might have base classes to print out first
8314 clang::CXXRecordDecl::base_class_const_iterator base_class,
8315 base_class_end;
8316 for (base_class = cxx_record_decl->bases_begin(),
8317 base_class_end = cxx_record_decl->bases_end();
8318 base_class != base_class_end; ++base_class) {
8319 const clang::CXXRecordDecl *base_class_decl =
8320 llvm::cast<clang::CXXRecordDecl>(
8321 base_class->getType()->getAs<clang::RecordType>()->getDecl());
8322
8323 // Skip empty base classes
8324 if (!verbose && !TypeSystemClang::RecordHasFields(base_class_decl))
8325 continue;
8326
8327 if (base_class->isVirtual())
8328 field_bit_offset =
8329 record_layout.getVBaseClassOffset(base_class_decl)
8330 .getQuantity() *
8331 8;
8332 else
8333 field_bit_offset = record_layout.getBaseClassOffset(base_class_decl)
8334 .getQuantity() *
8335 8;
8336 field_byte_offset = field_bit_offset / 8;
8337 assert(field_bit_offset % 8 == 0);
8338 if (child_idx == 0)
8339 s->PutChar('{');
8340 else
8341 s->PutChar(',');
8342
8343 clang::QualType base_class_qual_type = base_class->getType();
8344 std::string base_class_type_name(base_class_qual_type.getAsString());
8345
8346 // Indent and print the base class type name
8347 s->Format("\n{0}{1}", llvm::fmt_repeat(" ", depth + DEPTH_INCREMENT),
8348 base_class_type_name);
8349
8350 clang::TypeInfo base_class_type_info =
8351 getASTContext().getTypeInfo(base_class_qual_type);
8352
8353 // Dump the value of the member
8354 CompilerType base_clang_type = GetType(base_class_qual_type);
8355 base_clang_type.DumpValue(
8356 exe_ctx,
8357 s, // Stream to dump to
8358 base_clang_type
8359 .GetFormat(), // The format with which to display the member
8360 data, // Data buffer containing all bytes for this type
8361 data_byte_offset + field_byte_offset, // Offset into "data" where
8362 // to grab value from
8363 base_class_type_info.Width / 8, // Size of this type in bytes
8364 0, // Bitfield bit size
8365 0, // Bitfield bit offset
8366 show_types, // Boolean indicating if we should show the variable
8367 // types
8368 show_summary, // Boolean indicating if we should show a summary
8369 // for the current type
8370 verbose, // Verbose output?
8371 depth + DEPTH_INCREMENT); // Scope depth for any types that have
8372 // children
8373
8374 ++child_idx;
8375 }
8376 }
8377 uint32_t field_idx = 0;
8378 clang::RecordDecl::field_iterator field, field_end;
8379 for (field = record_decl->field_begin(),
8380 field_end = record_decl->field_end();
8381 field != field_end; ++field, ++field_idx, ++child_idx) {
8382 // Print the starting squiggly bracket (if this is the first member) or
8383 // comma (for member 2 and beyond) for the struct/union/class member.
8384 if (child_idx == 0)
8385 s->PutChar('{');
8386 else
8387 s->PutChar(',');
8388
8389 // Indent
8390 s->Printf("\n%*s", depth + DEPTH_INCREMENT, "");
8391
8392 clang::QualType field_type = field->getType();
8393 // Print the member type if requested
8394 // Figure out the type byte size (field_type_info.first) and alignment
8395 // (field_type_info.second) from the AST context.
8396 clang::TypeInfo field_type_info =
8397 getASTContext().getTypeInfo(field_type);
8398 assert(field_idx < record_layout.getFieldCount());
8399 // Figure out the field offset within the current struct/union/class
8400 // type
8401 field_bit_offset = record_layout.getFieldOffset(field_idx);
8402 field_byte_offset = field_bit_offset / 8;
8403 uint32_t field_bitfield_bit_size = 0;
8404 uint32_t field_bitfield_bit_offset = 0;
8405 if (FieldIsBitfield(*field, field_bitfield_bit_size))
8406 field_bitfield_bit_offset = field_bit_offset % 8;
8407
8408 if (show_types) {
8409 std::string field_type_name(field_type.getAsString());
8410 if (field_bitfield_bit_size > 0)
8411 s->Printf("(%s:%u) ", field_type_name.c_str(),
8412 field_bitfield_bit_size);
8413 else
8414 s->Printf("(%s) ", field_type_name.c_str());
8415 }
8416 // Print the member name and equal sign
8417 s->Printf("%s = ", field->getNameAsString().c_str());
8418
8419 // Dump the value of the member
8420 CompilerType field_clang_type = GetType(field_type);
8421 field_clang_type.DumpValue(
8422 exe_ctx,
8423 s, // Stream to dump to
8424 field_clang_type
8425 .GetFormat(), // The format with which to display the member
8426 data, // Data buffer containing all bytes for this type
8427 data_byte_offset + field_byte_offset, // Offset into "data" where to
8428 // grab value from
8429 field_type_info.Width / 8, // Size of this type in bytes
8430 field_bitfield_bit_size, // Bitfield bit size
8431 field_bitfield_bit_offset, // Bitfield bit offset
8432 show_types, // Boolean indicating if we should show the variable
8433 // types
8434 show_summary, // Boolean indicating if we should show a summary for
8435 // the current type
8436 verbose, // Verbose output?
8437 depth + DEPTH_INCREMENT); // Scope depth for any types that have
8438 // children
8439 }
8440
8441 // Indent the trailing squiggly bracket
8442 if (child_idx > 0)
8443 s->Printf("\n%*s}", depth, "");
8444 }
8445 return;
8446
8447 case clang::Type::Enum:
8448 if (GetCompleteType(type)) {
8449 const clang::EnumType *enutype =
8450 llvm::cast<clang::EnumType>(qual_type.getTypePtr());
8451 const clang::EnumDecl *enum_decl = enutype->getDecl();
8452 assert(enum_decl);
8453 clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
8454 lldb::offset_t offset = data_byte_offset;
8455 const int64_t enum_value = data.GetMaxU64Bitfield(
8456 &offset, data_byte_size, bitfield_bit_size, bitfield_bit_offset);
8457 for (enum_pos = enum_decl->enumerator_begin(),
8458 enum_end_pos = enum_decl->enumerator_end();
8459 enum_pos != enum_end_pos; ++enum_pos) {
8460 if (enum_pos->getInitVal() == enum_value) {
8461 s->Printf("%s", enum_pos->getNameAsString().c_str());
8462 return;
8463 }
8464 }
8465 // If we have gotten here we didn't get find the enumerator in the enum
8466 // decl, so just print the integer.
8467 s->Printf("%" PRIi64, enum_value);
8468 }
8469 return;
8470
8471 case clang::Type::ConstantArray: {
8472 const clang::ConstantArrayType *array =
8473 llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr());
8474 bool is_array_of_characters = false;
8475 clang::QualType element_qual_type = array->getElementType();
8476
8477 const clang::Type *canonical_type =
8478 element_qual_type->getCanonicalTypeInternal().getTypePtr();
8479 if (canonical_type)
8480 is_array_of_characters = canonical_type->isCharType();
8481
8482 const uint64_t element_count = array->getSize().getLimitedValue();
8483
8484 clang::TypeInfo field_type_info =
8485 getASTContext().getTypeInfo(element_qual_type);
8486
8487 uint32_t element_idx = 0;
8488 uint32_t element_offset = 0;
8489 uint64_t element_byte_size = field_type_info.Width / 8;
8490 uint32_t element_stride = element_byte_size;
8491
8492 if (is_array_of_characters) {
8493 s->PutChar('"');
8494 DumpDataExtractor(data, s, data_byte_offset, lldb::eFormatChar,
8495 element_byte_size, element_count, UINT32_MAX,
8496 LLDB_INVALID_ADDRESS, 0, 0);
8497 s->PutChar('"');
8498 return;
8499 } else {
8500 CompilerType element_clang_type = GetType(element_qual_type);
8501 lldb::Format element_format = element_clang_type.GetFormat();
8502
8503 for (element_idx = 0; element_idx < element_count; ++element_idx) {
8504 // Print the starting squiggly bracket (if this is the first member) or
8505 // comman (for member 2 and beyong) for the struct/union/class member.
8506 if (element_idx == 0)
8507 s->PutChar('{');
8508 else
8509 s->PutChar(',');
8510
8511 // Indent and print the index
8512 s->Printf("\n%*s[%u] ", depth + DEPTH_INCREMENT, "", element_idx);
8513
8514 // Figure out the field offset within the current struct/union/class
8515 // type
8516 element_offset = element_idx * element_stride;
8517
8518 // Dump the value of the member
8519 element_clang_type.DumpValue(
8520 exe_ctx,
8521 s, // Stream to dump to
8522 element_format, // The format with which to display the element
8523 data, // Data buffer containing all bytes for this type
8524 data_byte_offset +
8525 element_offset, // Offset into "data" where to grab value from
8526 element_byte_size, // Size of this type in bytes
8527 0, // Bitfield bit size
8528 0, // Bitfield bit offset
8529 show_types, // Boolean indicating if we should show the variable
8530 // types
8531 show_summary, // Boolean indicating if we should show a summary for
8532 // the current type
8533 verbose, // Verbose output?
8534 depth + DEPTH_INCREMENT); // Scope depth for any types that have
8535 // children
8536 }
8537
8538 // Indent the trailing squiggly bracket
8539 if (element_idx > 0)
8540 s->Printf("\n%*s}", depth, "");
8541 }
8542 }
8543 return;
8544
8545 case clang::Type::Typedef: {
8546 clang::QualType typedef_qual_type =
8547 llvm::cast<clang::TypedefType>(qual_type)
8548 ->getDecl()
8549 ->getUnderlyingType();
8550
8551 CompilerType typedef_clang_type = GetType(typedef_qual_type);
8552 lldb::Format typedef_format = typedef_clang_type.GetFormat();
8553 clang::TypeInfo typedef_type_info =
8554 getASTContext().getTypeInfo(typedef_qual_type);
8555 uint64_t typedef_byte_size = typedef_type_info.Width / 8;
8556
8557 return typedef_clang_type.DumpValue(
8558 exe_ctx,
8559 s, // Stream to dump to
8560 typedef_format, // The format with which to display the element
8561 data, // Data buffer containing all bytes for this type
8562 data_byte_offset, // Offset into "data" where to grab value from
8563 typedef_byte_size, // Size of this type in bytes
8564 bitfield_bit_size, // Bitfield bit size
8565 bitfield_bit_offset, // Bitfield bit offset
8566 show_types, // Boolean indicating if we should show the variable types
8567 show_summary, // Boolean indicating if we should show a summary for the
8568 // current type
8569 verbose, // Verbose output?
8570 depth); // Scope depth for any types that have children
8571 } break;
8572
8573 case clang::Type::Auto: {
8574 clang::QualType elaborated_qual_type =
8575 llvm::cast<clang::AutoType>(qual_type)->getDeducedType();
8576 CompilerType elaborated_clang_type = GetType(elaborated_qual_type);
8577 lldb::Format elaborated_format = elaborated_clang_type.GetFormat();
8578 clang::TypeInfo elaborated_type_info =
8579 getASTContext().getTypeInfo(elaborated_qual_type);
8580 uint64_t elaborated_byte_size = elaborated_type_info.Width / 8;
8581
8582 return elaborated_clang_type.DumpValue(
8583 exe_ctx,
8584 s, // Stream to dump to
8585 elaborated_format, // The format with which to display the element
8586 data, // Data buffer containing all bytes for this type
8587 data_byte_offset, // Offset into "data" where to grab value from
8588 elaborated_byte_size, // Size of this type in bytes
8589 bitfield_bit_size, // Bitfield bit size
8590 bitfield_bit_offset, // Bitfield bit offset
8591 show_types, // Boolean indicating if we should show the variable types
8592 show_summary, // Boolean indicating if we should show a summary for the
8593 // current type
8594 verbose, // Verbose output?
8595 depth); // Scope depth for any types that have children
8596 } break;
8597
8598 case clang::Type::Elaborated: {
8599 clang::QualType elaborated_qual_type =
8600 llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType();
8601 CompilerType elaborated_clang_type = GetType(elaborated_qual_type);
8602 lldb::Format elaborated_format = elaborated_clang_type.GetFormat();
8603 clang::TypeInfo elaborated_type_info =
8604 getASTContext().getTypeInfo(elaborated_qual_type);
8605 uint64_t elaborated_byte_size = elaborated_type_info.Width / 8;
8606
8607 return elaborated_clang_type.DumpValue(
8608 exe_ctx,
8609 s, // Stream to dump to
8610 elaborated_format, // The format with which to display the element
8611 data, // Data buffer containing all bytes for this type
8612 data_byte_offset, // Offset into "data" where to grab value from
8613 elaborated_byte_size, // Size of this type in bytes
8614 bitfield_bit_size, // Bitfield bit size
8615 bitfield_bit_offset, // Bitfield bit offset
8616 show_types, // Boolean indicating if we should show the variable types
8617 show_summary, // Boolean indicating if we should show a summary for the
8618 // current type
8619 verbose, // Verbose output?
8620 depth); // Scope depth for any types that have children
8621 } break;
8622
8623 case clang::Type::Paren: {
8624 clang::QualType desugar_qual_type =
8625 llvm::cast<clang::ParenType>(qual_type)->desugar();
8626 CompilerType desugar_clang_type = GetType(desugar_qual_type);
8627
8628 lldb::Format desugar_format = desugar_clang_type.GetFormat();
8629 clang::TypeInfo desugar_type_info =
8630 getASTContext().getTypeInfo(desugar_qual_type);
8631 uint64_t desugar_byte_size = desugar_type_info.Width / 8;
8632
8633 return desugar_clang_type.DumpValue(
8634 exe_ctx,
8635 s, // Stream to dump to
8636 desugar_format, // The format with which to display the element
8637 data, // Data buffer containing all bytes for this type
8638 data_byte_offset, // Offset into "data" where to grab value from
8639 desugar_byte_size, // Size of this type in bytes
8640 bitfield_bit_size, // Bitfield bit size
8641 bitfield_bit_offset, // Bitfield bit offset
8642 show_types, // Boolean indicating if we should show the variable types
8643 show_summary, // Boolean indicating if we should show a summary for the
8644 // current type
8645 verbose, // Verbose output?
8646 depth); // Scope depth for any types that have children
8647 } break;
8648
8649 default:
8650 // We are down to a scalar type that we just need to display.
8651 DumpDataExtractor(data, s, data_byte_offset, format, data_byte_size, 1,
8652 UINT32_MAX, LLDB_INVALID_ADDRESS, bitfield_bit_size,
8653 bitfield_bit_offset);
8654
8655 if (show_summary)
8656 DumpSummary(type, exe_ctx, s, data, data_byte_offset, data_byte_size);
8657 break;
8658 }
8659 }
8660
DumpEnumValue(const clang::QualType & qual_type,Stream * s,const DataExtractor & data,lldb::offset_t byte_offset,size_t byte_size,uint32_t bitfield_bit_offset,uint32_t bitfield_bit_size)8661 static bool DumpEnumValue(const clang::QualType &qual_type, Stream *s,
8662 const DataExtractor &data, lldb::offset_t byte_offset,
8663 size_t byte_size, uint32_t bitfield_bit_offset,
8664 uint32_t bitfield_bit_size) {
8665 const clang::EnumType *enutype =
8666 llvm::cast<clang::EnumType>(qual_type.getTypePtr());
8667 const clang::EnumDecl *enum_decl = enutype->getDecl();
8668 assert(enum_decl);
8669 lldb::offset_t offset = byte_offset;
8670 const uint64_t enum_svalue = data.GetMaxS64Bitfield(
8671 &offset, byte_size, bitfield_bit_size, bitfield_bit_offset);
8672 bool can_be_bitfield = true;
8673 uint64_t covered_bits = 0;
8674 int num_enumerators = 0;
8675
8676 // Try to find an exact match for the value.
8677 // At the same time, we're applying a heuristic to determine whether we want
8678 // to print this enum as a bitfield. We're likely dealing with a bitfield if
8679 // every enumerator is either a one bit value or a superset of the previous
8680 // enumerators. Also 0 doesn't make sense when the enumerators are used as
8681 // flags.
8682 for (auto *enumerator : enum_decl->enumerators()) {
8683 uint64_t val = enumerator->getInitVal().getSExtValue();
8684 val = llvm::SignExtend64(val, 8*byte_size);
8685 if (llvm::countPopulation(val) != 1 && (val & ~covered_bits) != 0)
8686 can_be_bitfield = false;
8687 covered_bits |= val;
8688 ++num_enumerators;
8689 if (val == enum_svalue) {
8690 // Found an exact match, that's all we need to do.
8691 s->PutCString(enumerator->getNameAsString());
8692 return true;
8693 }
8694 }
8695
8696 // Unsigned values make more sense for flags.
8697 offset = byte_offset;
8698 const uint64_t enum_uvalue = data.GetMaxU64Bitfield(
8699 &offset, byte_size, bitfield_bit_size, bitfield_bit_offset);
8700
8701 // No exact match, but we don't think this is a bitfield. Print the value as
8702 // decimal.
8703 if (!can_be_bitfield) {
8704 if (qual_type->isSignedIntegerOrEnumerationType())
8705 s->Printf("%" PRIi64, enum_svalue);
8706 else
8707 s->Printf("%" PRIu64, enum_uvalue);
8708 return true;
8709 }
8710
8711 uint64_t remaining_value = enum_uvalue;
8712 std::vector<std::pair<uint64_t, llvm::StringRef>> values;
8713 values.reserve(num_enumerators);
8714 for (auto *enumerator : enum_decl->enumerators())
8715 if (auto val = enumerator->getInitVal().getZExtValue())
8716 values.emplace_back(val, enumerator->getName());
8717
8718 // Sort in reverse order of the number of the population count, so that in
8719 // `enum {A, B, ALL = A|B }` we visit ALL first. Use a stable sort so that
8720 // A | C where A is declared before C is displayed in this order.
8721 std::stable_sort(values.begin(), values.end(), [](const auto &a, const auto &b) {
8722 return llvm::countPopulation(a.first) > llvm::countPopulation(b.first);
8723 });
8724
8725 for (const auto &val : values) {
8726 if ((remaining_value & val.first) != val.first)
8727 continue;
8728 remaining_value &= ~val.first;
8729 s->PutCString(val.second);
8730 if (remaining_value)
8731 s->PutCString(" | ");
8732 }
8733
8734 // If there is a remainder that is not covered by the value, print it as hex.
8735 if (remaining_value)
8736 s->Printf("0x%" PRIx64, remaining_value);
8737
8738 return true;
8739 }
8740
DumpTypeValue(lldb::opaque_compiler_type_t type,Stream * s,lldb::Format format,const lldb_private::DataExtractor & data,lldb::offset_t byte_offset,size_t byte_size,uint32_t bitfield_bit_size,uint32_t bitfield_bit_offset,ExecutionContextScope * exe_scope)8741 bool TypeSystemClang::DumpTypeValue(
8742 lldb::opaque_compiler_type_t type, Stream *s, lldb::Format format,
8743 const lldb_private::DataExtractor &data, lldb::offset_t byte_offset,
8744 size_t byte_size, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
8745 ExecutionContextScope *exe_scope) {
8746 if (!type)
8747 return false;
8748 if (IsAggregateType(type)) {
8749 return false;
8750 } else {
8751 clang::QualType qual_type(GetQualType(type));
8752
8753 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8754
8755 if (type_class == clang::Type::Elaborated) {
8756 qual_type = llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType();
8757 return DumpTypeValue(qual_type.getAsOpaquePtr(), s, format, data, byte_offset, byte_size,
8758 bitfield_bit_size, bitfield_bit_offset, exe_scope);
8759 }
8760
8761 switch (type_class) {
8762 case clang::Type::Typedef: {
8763 clang::QualType typedef_qual_type =
8764 llvm::cast<clang::TypedefType>(qual_type)
8765 ->getDecl()
8766 ->getUnderlyingType();
8767 CompilerType typedef_clang_type = GetType(typedef_qual_type);
8768 if (format == eFormatDefault)
8769 format = typedef_clang_type.GetFormat();
8770 clang::TypeInfo typedef_type_info =
8771 getASTContext().getTypeInfo(typedef_qual_type);
8772 uint64_t typedef_byte_size = typedef_type_info.Width / 8;
8773
8774 return typedef_clang_type.DumpTypeValue(
8775 s,
8776 format, // The format with which to display the element
8777 data, // Data buffer containing all bytes for this type
8778 byte_offset, // Offset into "data" where to grab value from
8779 typedef_byte_size, // Size of this type in bytes
8780 bitfield_bit_size, // Size in bits of a bitfield value, if zero don't
8781 // treat as a bitfield
8782 bitfield_bit_offset, // Offset in bits of a bitfield value if
8783 // bitfield_bit_size != 0
8784 exe_scope);
8785 } break;
8786
8787 case clang::Type::Enum:
8788 // If our format is enum or default, show the enumeration value as its
8789 // enumeration string value, else just display it as requested.
8790 if ((format == eFormatEnum || format == eFormatDefault) &&
8791 GetCompleteType(type))
8792 return DumpEnumValue(qual_type, s, data, byte_offset, byte_size,
8793 bitfield_bit_offset, bitfield_bit_size);
8794 // format was not enum, just fall through and dump the value as
8795 // requested....
8796 LLVM_FALLTHROUGH;
8797
8798 default:
8799 // We are down to a scalar type that we just need to display.
8800 {
8801 uint32_t item_count = 1;
8802 // A few formats, we might need to modify our size and count for
8803 // depending
8804 // on how we are trying to display the value...
8805 switch (format) {
8806 default:
8807 case eFormatBoolean:
8808 case eFormatBinary:
8809 case eFormatComplex:
8810 case eFormatCString: // NULL terminated C strings
8811 case eFormatDecimal:
8812 case eFormatEnum:
8813 case eFormatHex:
8814 case eFormatHexUppercase:
8815 case eFormatFloat:
8816 case eFormatOctal:
8817 case eFormatOSType:
8818 case eFormatUnsigned:
8819 case eFormatPointer:
8820 case eFormatVectorOfChar:
8821 case eFormatVectorOfSInt8:
8822 case eFormatVectorOfUInt8:
8823 case eFormatVectorOfSInt16:
8824 case eFormatVectorOfUInt16:
8825 case eFormatVectorOfSInt32:
8826 case eFormatVectorOfUInt32:
8827 case eFormatVectorOfSInt64:
8828 case eFormatVectorOfUInt64:
8829 case eFormatVectorOfFloat32:
8830 case eFormatVectorOfFloat64:
8831 case eFormatVectorOfUInt128:
8832 break;
8833
8834 case eFormatChar:
8835 case eFormatCharPrintable:
8836 case eFormatCharArray:
8837 case eFormatBytes:
8838 case eFormatBytesWithASCII:
8839 item_count = byte_size;
8840 byte_size = 1;
8841 break;
8842
8843 case eFormatUnicode16:
8844 item_count = byte_size / 2;
8845 byte_size = 2;
8846 break;
8847
8848 case eFormatUnicode32:
8849 item_count = byte_size / 4;
8850 byte_size = 4;
8851 break;
8852 }
8853 return DumpDataExtractor(data, s, byte_offset, format, byte_size,
8854 item_count, UINT32_MAX, LLDB_INVALID_ADDRESS,
8855 bitfield_bit_size, bitfield_bit_offset,
8856 exe_scope);
8857 }
8858 break;
8859 }
8860 }
8861 return false;
8862 }
8863
DumpSummary(lldb::opaque_compiler_type_t type,ExecutionContext * exe_ctx,Stream * s,const lldb_private::DataExtractor & data,lldb::offset_t data_byte_offset,size_t data_byte_size)8864 void TypeSystemClang::DumpSummary(lldb::opaque_compiler_type_t type,
8865 ExecutionContext *exe_ctx, Stream *s,
8866 const lldb_private::DataExtractor &data,
8867 lldb::offset_t data_byte_offset,
8868 size_t data_byte_size) {
8869 uint32_t length = 0;
8870 if (IsCStringType(type, length)) {
8871 if (exe_ctx) {
8872 Process *process = exe_ctx->GetProcessPtr();
8873 if (process) {
8874 lldb::offset_t offset = data_byte_offset;
8875 lldb::addr_t pointer_address = data.GetMaxU64(&offset, data_byte_size);
8876 std::vector<uint8_t> buf;
8877 if (length > 0)
8878 buf.resize(length);
8879 else
8880 buf.resize(256);
8881
8882 DataExtractor cstr_data(&buf.front(), buf.size(),
8883 process->GetByteOrder(), 4);
8884 buf.back() = '\0';
8885 size_t bytes_read;
8886 size_t total_cstr_len = 0;
8887 Status error;
8888 while ((bytes_read = process->ReadMemory(pointer_address, &buf.front(),
8889 buf.size(), error)) > 0) {
8890 const size_t len = strlen((const char *)&buf.front());
8891 if (len == 0)
8892 break;
8893 if (total_cstr_len == 0)
8894 s->PutCString(" \"");
8895 DumpDataExtractor(cstr_data, s, 0, lldb::eFormatChar, 1, len,
8896 UINT32_MAX, LLDB_INVALID_ADDRESS, 0, 0);
8897 total_cstr_len += len;
8898 if (len < buf.size())
8899 break;
8900 pointer_address += total_cstr_len;
8901 }
8902 if (total_cstr_len > 0)
8903 s->PutChar('"');
8904 }
8905 }
8906 }
8907 }
8908
DumpTypeDescription(lldb::opaque_compiler_type_t type,lldb::DescriptionLevel level)8909 void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type,
8910 lldb::DescriptionLevel level) {
8911 StreamFile s(stdout, false);
8912 DumpTypeDescription(type, &s, level);
8913
8914 CompilerType ct(this, type);
8915 const clang::Type *clang_type = ClangUtil::GetQualType(ct).getTypePtr();
8916 ClangASTMetadata *metadata = GetMetadata(clang_type);
8917 if (metadata) {
8918 metadata->Dump(&s);
8919 }
8920 }
8921
DumpTypeDescription(lldb::opaque_compiler_type_t type,Stream * s,lldb::DescriptionLevel level)8922 void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type,
8923 Stream *s,
8924 lldb::DescriptionLevel level) {
8925 if (type) {
8926 clang::QualType qual_type =
8927 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
8928
8929 llvm::SmallVector<char, 1024> buf;
8930 llvm::raw_svector_ostream llvm_ostrm(buf);
8931
8932 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8933 switch (type_class) {
8934 case clang::Type::ObjCObject:
8935 case clang::Type::ObjCInterface: {
8936 GetCompleteType(type);
8937
8938 auto *objc_class_type =
8939 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
8940 assert(objc_class_type);
8941 if (!objc_class_type)
8942 break;
8943 clang::ObjCInterfaceDecl *class_interface_decl =
8944 objc_class_type->getInterface();
8945 if (!class_interface_decl)
8946 break;
8947 if (level == eDescriptionLevelVerbose)
8948 class_interface_decl->dump(llvm_ostrm);
8949 else
8950 class_interface_decl->print(llvm_ostrm,
8951 getASTContext().getPrintingPolicy(),
8952 s->GetIndentLevel());
8953 } break;
8954
8955 case clang::Type::Typedef: {
8956 auto *typedef_type = qual_type->getAs<clang::TypedefType>();
8957 if (!typedef_type)
8958 break;
8959 const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
8960 if (level == eDescriptionLevelVerbose)
8961 typedef_decl->dump(llvm_ostrm);
8962 else {
8963 std::string clang_typedef_name(GetTypeNameForDecl(typedef_decl));
8964 if (!clang_typedef_name.empty()) {
8965 s->PutCString("typedef ");
8966 s->PutCString(clang_typedef_name);
8967 }
8968 }
8969 } break;
8970
8971 case clang::Type::Record: {
8972 GetCompleteType(type);
8973
8974 auto *record_type = llvm::cast<clang::RecordType>(qual_type.getTypePtr());
8975 const clang::RecordDecl *record_decl = record_type->getDecl();
8976 if (level == eDescriptionLevelVerbose)
8977 record_decl->dump(llvm_ostrm);
8978 else {
8979 if (auto *cxx_record_decl =
8980 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl))
8981 cxx_record_decl->print(llvm_ostrm,
8982 getASTContext().getPrintingPolicy(),
8983 s->GetIndentLevel());
8984 else
8985 record_decl->print(llvm_ostrm, getASTContext().getPrintingPolicy(),
8986 s->GetIndentLevel());
8987 }
8988 } break;
8989
8990 default: {
8991 if (auto *tag_type =
8992 llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr())) {
8993 if (clang::TagDecl *tag_decl = tag_type->getDecl()) {
8994 if (level == eDescriptionLevelVerbose)
8995 tag_decl->dump(llvm_ostrm);
8996 else
8997 tag_decl->print(llvm_ostrm, 0);
8998 }
8999 } else {
9000 if (level == eDescriptionLevelVerbose)
9001 qual_type->dump(llvm_ostrm, getASTContext());
9002 else {
9003 std::string clang_type_name(qual_type.getAsString());
9004 if (!clang_type_name.empty())
9005 s->PutCString(clang_type_name);
9006 }
9007 }
9008 }
9009 }
9010
9011 if (buf.size() > 0) {
9012 s->Write(buf.data(), buf.size());
9013 }
9014 }
9015 }
9016
DumpTypeName(const CompilerType & type)9017 void TypeSystemClang::DumpTypeName(const CompilerType &type) {
9018 if (ClangUtil::IsClangType(type)) {
9019 clang::QualType qual_type(
9020 ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));
9021
9022 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9023 switch (type_class) {
9024 case clang::Type::Record: {
9025 const clang::CXXRecordDecl *cxx_record_decl =
9026 qual_type->getAsCXXRecordDecl();
9027 if (cxx_record_decl)
9028 printf("class %s", cxx_record_decl->getName().str().c_str());
9029 } break;
9030
9031 case clang::Type::Enum: {
9032 clang::EnumDecl *enum_decl =
9033 llvm::cast<clang::EnumType>(qual_type)->getDecl();
9034 if (enum_decl) {
9035 printf("enum %s", enum_decl->getName().str().c_str());
9036 }
9037 } break;
9038
9039 case clang::Type::ObjCObject:
9040 case clang::Type::ObjCInterface: {
9041 const clang::ObjCObjectType *objc_class_type =
9042 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
9043 if (objc_class_type) {
9044 clang::ObjCInterfaceDecl *class_interface_decl =
9045 objc_class_type->getInterface();
9046 // We currently can't complete objective C types through the newly
9047 // added ASTContext because it only supports TagDecl objects right
9048 // now...
9049 if (class_interface_decl)
9050 printf("@class %s", class_interface_decl->getName().str().c_str());
9051 }
9052 } break;
9053
9054 case clang::Type::Typedef:
9055 printf("typedef %s", llvm::cast<clang::TypedefType>(qual_type)
9056 ->getDecl()
9057 ->getName()
9058 .str()
9059 .c_str());
9060 break;
9061
9062 case clang::Type::Auto:
9063 printf("auto ");
9064 return DumpTypeName(CompilerType(type.GetTypeSystem(),
9065 llvm::cast<clang::AutoType>(qual_type)
9066 ->getDeducedType()
9067 .getAsOpaquePtr()));
9068
9069 case clang::Type::Elaborated:
9070 printf("elaborated ");
9071 return DumpTypeName(CompilerType(
9072 type.GetTypeSystem(), llvm::cast<clang::ElaboratedType>(qual_type)
9073 ->getNamedType()
9074 .getAsOpaquePtr()));
9075
9076 case clang::Type::Paren:
9077 printf("paren ");
9078 return DumpTypeName(CompilerType(
9079 type.GetTypeSystem(),
9080 llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
9081
9082 default:
9083 printf("TypeSystemClang::DumpTypeName() type_class = %u", type_class);
9084 break;
9085 }
9086 }
9087 }
9088
ParseClassTemplateDecl(clang::DeclContext * decl_ctx,OptionalClangModuleID owning_module,lldb::AccessType access_type,const char * parent_name,int tag_decl_kind,const TypeSystemClang::TemplateParameterInfos & template_param_infos)9089 clang::ClassTemplateDecl *TypeSystemClang::ParseClassTemplateDecl(
9090 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
9091 lldb::AccessType access_type, const char *parent_name, int tag_decl_kind,
9092 const TypeSystemClang::TemplateParameterInfos &template_param_infos) {
9093 if (template_param_infos.IsValid()) {
9094 std::string template_basename(parent_name);
9095 template_basename.erase(template_basename.find('<'));
9096
9097 return CreateClassTemplateDecl(decl_ctx, owning_module, access_type,
9098 template_basename.c_str(), tag_decl_kind,
9099 template_param_infos);
9100 }
9101 return nullptr;
9102 }
9103
CompleteTagDecl(clang::TagDecl * decl)9104 void TypeSystemClang::CompleteTagDecl(clang::TagDecl *decl) {
9105 SymbolFile *sym_file = GetSymbolFile();
9106 if (sym_file) {
9107 CompilerType clang_type = GetTypeForDecl(decl);
9108 if (clang_type)
9109 sym_file->CompleteType(clang_type);
9110 }
9111 }
9112
CompleteObjCInterfaceDecl(clang::ObjCInterfaceDecl * decl)9113 void TypeSystemClang::CompleteObjCInterfaceDecl(
9114 clang::ObjCInterfaceDecl *decl) {
9115 SymbolFile *sym_file = GetSymbolFile();
9116 if (sym_file) {
9117 CompilerType clang_type = GetTypeForDecl(decl);
9118 if (clang_type)
9119 sym_file->CompleteType(clang_type);
9120 }
9121 }
9122
GetDWARFParser()9123 DWARFASTParser *TypeSystemClang::GetDWARFParser() {
9124 if (!m_dwarf_ast_parser_up)
9125 m_dwarf_ast_parser_up = std::make_unique<DWARFASTParserClang>(*this);
9126 return m_dwarf_ast_parser_up.get();
9127 }
9128
GetPDBParser()9129 PDBASTParser *TypeSystemClang::GetPDBParser() {
9130 if (!m_pdb_ast_parser_up)
9131 m_pdb_ast_parser_up = std::make_unique<PDBASTParser>(*this);
9132 return m_pdb_ast_parser_up.get();
9133 }
9134
LayoutRecordType(const clang::RecordDecl * record_decl,uint64_t & bit_size,uint64_t & alignment,llvm::DenseMap<const clang::FieldDecl *,uint64_t> & field_offsets,llvm::DenseMap<const clang::CXXRecordDecl *,clang::CharUnits> & base_offsets,llvm::DenseMap<const clang::CXXRecordDecl *,clang::CharUnits> & vbase_offsets)9135 bool TypeSystemClang::LayoutRecordType(
9136 const clang::RecordDecl *record_decl, uint64_t &bit_size,
9137 uint64_t &alignment,
9138 llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
9139 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9140 &base_offsets,
9141 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9142 &vbase_offsets) {
9143 lldb_private::ClangASTImporter *importer = nullptr;
9144 if (m_dwarf_ast_parser_up)
9145 importer = &m_dwarf_ast_parser_up->GetClangASTImporter();
9146 if (!importer && m_pdb_ast_parser_up)
9147 importer = &m_pdb_ast_parser_up->GetClangASTImporter();
9148 if (!importer)
9149 return false;
9150
9151 return importer->LayoutRecordType(record_decl, bit_size, alignment,
9152 field_offsets, base_offsets, vbase_offsets);
9153 }
9154
9155 // CompilerDecl override functions
9156
DeclGetName(void * opaque_decl)9157 ConstString TypeSystemClang::DeclGetName(void *opaque_decl) {
9158 if (opaque_decl) {
9159 clang::NamedDecl *nd =
9160 llvm::dyn_cast<NamedDecl>((clang::Decl *)opaque_decl);
9161 if (nd != nullptr)
9162 return ConstString(nd->getDeclName().getAsString());
9163 }
9164 return ConstString();
9165 }
9166
DeclGetMangledName(void * opaque_decl)9167 ConstString TypeSystemClang::DeclGetMangledName(void *opaque_decl) {
9168 if (opaque_decl) {
9169 clang::NamedDecl *nd =
9170 llvm::dyn_cast<clang::NamedDecl>((clang::Decl *)opaque_decl);
9171 if (nd != nullptr && !llvm::isa<clang::ObjCMethodDecl>(nd)) {
9172 clang::MangleContext *mc = getMangleContext();
9173 if (mc && mc->shouldMangleCXXName(nd)) {
9174 llvm::SmallVector<char, 1024> buf;
9175 llvm::raw_svector_ostream llvm_ostrm(buf);
9176 if (llvm::isa<clang::CXXConstructorDecl>(nd)) {
9177 mc->mangleName(
9178 clang::GlobalDecl(llvm::dyn_cast<clang::CXXConstructorDecl>(nd),
9179 Ctor_Complete),
9180 llvm_ostrm);
9181 } else if (llvm::isa<clang::CXXDestructorDecl>(nd)) {
9182 mc->mangleName(
9183 clang::GlobalDecl(llvm::dyn_cast<clang::CXXDestructorDecl>(nd),
9184 Dtor_Complete),
9185 llvm_ostrm);
9186 } else {
9187 mc->mangleName(nd, llvm_ostrm);
9188 }
9189 if (buf.size() > 0)
9190 return ConstString(buf.data(), buf.size());
9191 }
9192 }
9193 }
9194 return ConstString();
9195 }
9196
DeclGetDeclContext(void * opaque_decl)9197 CompilerDeclContext TypeSystemClang::DeclGetDeclContext(void *opaque_decl) {
9198 if (opaque_decl)
9199 return CreateDeclContext(((clang::Decl *)opaque_decl)->getDeclContext());
9200 return CompilerDeclContext();
9201 }
9202
DeclGetFunctionReturnType(void * opaque_decl)9203 CompilerType TypeSystemClang::DeclGetFunctionReturnType(void *opaque_decl) {
9204 if (clang::FunctionDecl *func_decl =
9205 llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
9206 return GetType(func_decl->getReturnType());
9207 if (clang::ObjCMethodDecl *objc_method =
9208 llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
9209 return GetType(objc_method->getReturnType());
9210 else
9211 return CompilerType();
9212 }
9213
DeclGetFunctionNumArguments(void * opaque_decl)9214 size_t TypeSystemClang::DeclGetFunctionNumArguments(void *opaque_decl) {
9215 if (clang::FunctionDecl *func_decl =
9216 llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
9217 return func_decl->param_size();
9218 if (clang::ObjCMethodDecl *objc_method =
9219 llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
9220 return objc_method->param_size();
9221 else
9222 return 0;
9223 }
9224
DeclGetFunctionArgumentType(void * opaque_decl,size_t idx)9225 CompilerType TypeSystemClang::DeclGetFunctionArgumentType(void *opaque_decl,
9226 size_t idx) {
9227 if (clang::FunctionDecl *func_decl =
9228 llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl)) {
9229 if (idx < func_decl->param_size()) {
9230 ParmVarDecl *var_decl = func_decl->getParamDecl(idx);
9231 if (var_decl)
9232 return GetType(var_decl->getOriginalType());
9233 }
9234 } else if (clang::ObjCMethodDecl *objc_method =
9235 llvm::dyn_cast<clang::ObjCMethodDecl>(
9236 (clang::Decl *)opaque_decl)) {
9237 if (idx < objc_method->param_size())
9238 return GetType(objc_method->parameters()[idx]->getOriginalType());
9239 }
9240 return CompilerType();
9241 }
9242
9243 // CompilerDeclContext functions
9244
DeclContextFindDeclByName(void * opaque_decl_ctx,ConstString name,const bool ignore_using_decls)9245 std::vector<CompilerDecl> TypeSystemClang::DeclContextFindDeclByName(
9246 void *opaque_decl_ctx, ConstString name, const bool ignore_using_decls) {
9247 std::vector<CompilerDecl> found_decls;
9248 if (opaque_decl_ctx) {
9249 DeclContext *root_decl_ctx = (DeclContext *)opaque_decl_ctx;
9250 std::set<DeclContext *> searched;
9251 std::multimap<DeclContext *, DeclContext *> search_queue;
9252 SymbolFile *symbol_file = GetSymbolFile();
9253
9254 for (clang::DeclContext *decl_context = root_decl_ctx;
9255 decl_context != nullptr && found_decls.empty();
9256 decl_context = decl_context->getParent()) {
9257 search_queue.insert(std::make_pair(decl_context, decl_context));
9258
9259 for (auto it = search_queue.find(decl_context); it != search_queue.end();
9260 it++) {
9261 if (!searched.insert(it->second).second)
9262 continue;
9263 symbol_file->ParseDeclsForContext(
9264 CreateDeclContext(it->second));
9265
9266 for (clang::Decl *child : it->second->decls()) {
9267 if (clang::UsingDirectiveDecl *ud =
9268 llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
9269 if (ignore_using_decls)
9270 continue;
9271 clang::DeclContext *from = ud->getCommonAncestor();
9272 if (searched.find(ud->getNominatedNamespace()) == searched.end())
9273 search_queue.insert(
9274 std::make_pair(from, ud->getNominatedNamespace()));
9275 } else if (clang::UsingDecl *ud =
9276 llvm::dyn_cast<clang::UsingDecl>(child)) {
9277 if (ignore_using_decls)
9278 continue;
9279 for (clang::UsingShadowDecl *usd : ud->shadows()) {
9280 clang::Decl *target = usd->getTargetDecl();
9281 if (clang::NamedDecl *nd =
9282 llvm::dyn_cast<clang::NamedDecl>(target)) {
9283 IdentifierInfo *ii = nd->getIdentifier();
9284 if (ii != nullptr &&
9285 ii->getName().equals(name.AsCString(nullptr)))
9286 found_decls.push_back(GetCompilerDecl(nd));
9287 }
9288 }
9289 } else if (clang::NamedDecl *nd =
9290 llvm::dyn_cast<clang::NamedDecl>(child)) {
9291 IdentifierInfo *ii = nd->getIdentifier();
9292 if (ii != nullptr && ii->getName().equals(name.AsCString(nullptr)))
9293 found_decls.push_back(GetCompilerDecl(nd));
9294 }
9295 }
9296 }
9297 }
9298 }
9299 return found_decls;
9300 }
9301
9302 // Look for child_decl_ctx's lookup scope in frame_decl_ctx and its parents,
9303 // and return the number of levels it took to find it, or
9304 // LLDB_INVALID_DECL_LEVEL if not found. If the decl was imported via a using
9305 // declaration, its name and/or type, if set, will be used to check that the
9306 // decl found in the scope is a match.
9307 //
9308 // The optional name is required by languages (like C++) to handle using
9309 // declarations like:
9310 //
9311 // void poo();
9312 // namespace ns {
9313 // void foo();
9314 // void goo();
9315 // }
9316 // void bar() {
9317 // using ns::foo;
9318 // // CountDeclLevels returns 0 for 'foo', 1 for 'poo', and
9319 // // LLDB_INVALID_DECL_LEVEL for 'goo'.
9320 // }
9321 //
9322 // The optional type is useful in the case that there's a specific overload
9323 // that we're looking for that might otherwise be shadowed, like:
9324 //
9325 // void foo(int);
9326 // namespace ns {
9327 // void foo();
9328 // }
9329 // void bar() {
9330 // using ns::foo;
9331 // // CountDeclLevels returns 0 for { 'foo', void() },
9332 // // 1 for { 'foo', void(int) }, and
9333 // // LLDB_INVALID_DECL_LEVEL for { 'foo', void(int, int) }.
9334 // }
9335 //
9336 // NOTE: Because file statics are at the TranslationUnit along with globals, a
9337 // function at file scope will return the same level as a function at global
9338 // scope. Ideally we'd like to treat the file scope as an additional scope just
9339 // below the global scope. More work needs to be done to recognise that, if
9340 // the decl we're trying to look up is static, we should compare its source
9341 // file with that of the current scope and return a lower number for it.
CountDeclLevels(clang::DeclContext * frame_decl_ctx,clang::DeclContext * child_decl_ctx,ConstString * child_name,CompilerType * child_type)9342 uint32_t TypeSystemClang::CountDeclLevels(clang::DeclContext *frame_decl_ctx,
9343 clang::DeclContext *child_decl_ctx,
9344 ConstString *child_name,
9345 CompilerType *child_type) {
9346 if (frame_decl_ctx) {
9347 std::set<DeclContext *> searched;
9348 std::multimap<DeclContext *, DeclContext *> search_queue;
9349 SymbolFile *symbol_file = GetSymbolFile();
9350
9351 // Get the lookup scope for the decl we're trying to find.
9352 clang::DeclContext *parent_decl_ctx = child_decl_ctx->getParent();
9353
9354 // Look for it in our scope's decl context and its parents.
9355 uint32_t level = 0;
9356 for (clang::DeclContext *decl_ctx = frame_decl_ctx; decl_ctx != nullptr;
9357 decl_ctx = decl_ctx->getParent()) {
9358 if (!decl_ctx->isLookupContext())
9359 continue;
9360 if (decl_ctx == parent_decl_ctx)
9361 // Found it!
9362 return level;
9363 search_queue.insert(std::make_pair(decl_ctx, decl_ctx));
9364 for (auto it = search_queue.find(decl_ctx); it != search_queue.end();
9365 it++) {
9366 if (searched.find(it->second) != searched.end())
9367 continue;
9368
9369 // Currently DWARF has one shared translation unit for all Decls at top
9370 // level, so this would erroneously find using statements anywhere. So
9371 // don't look at the top-level translation unit.
9372 // TODO fix this and add a testcase that depends on it.
9373
9374 if (llvm::isa<clang::TranslationUnitDecl>(it->second))
9375 continue;
9376
9377 searched.insert(it->second);
9378 symbol_file->ParseDeclsForContext(
9379 CreateDeclContext(it->second));
9380
9381 for (clang::Decl *child : it->second->decls()) {
9382 if (clang::UsingDirectiveDecl *ud =
9383 llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
9384 clang::DeclContext *ns = ud->getNominatedNamespace();
9385 if (ns == parent_decl_ctx)
9386 // Found it!
9387 return level;
9388 clang::DeclContext *from = ud->getCommonAncestor();
9389 if (searched.find(ns) == searched.end())
9390 search_queue.insert(std::make_pair(from, ns));
9391 } else if (child_name) {
9392 if (clang::UsingDecl *ud =
9393 llvm::dyn_cast<clang::UsingDecl>(child)) {
9394 for (clang::UsingShadowDecl *usd : ud->shadows()) {
9395 clang::Decl *target = usd->getTargetDecl();
9396 clang::NamedDecl *nd = llvm::dyn_cast<clang::NamedDecl>(target);
9397 if (!nd)
9398 continue;
9399 // Check names.
9400 IdentifierInfo *ii = nd->getIdentifier();
9401 if (ii == nullptr ||
9402 !ii->getName().equals(child_name->AsCString(nullptr)))
9403 continue;
9404 // Check types, if one was provided.
9405 if (child_type) {
9406 CompilerType clang_type = GetTypeForDecl(nd);
9407 if (!AreTypesSame(clang_type, *child_type,
9408 /*ignore_qualifiers=*/true))
9409 continue;
9410 }
9411 // Found it!
9412 return level;
9413 }
9414 }
9415 }
9416 }
9417 }
9418 ++level;
9419 }
9420 }
9421 return LLDB_INVALID_DECL_LEVEL;
9422 }
9423
DeclContextGetName(void * opaque_decl_ctx)9424 ConstString TypeSystemClang::DeclContextGetName(void *opaque_decl_ctx) {
9425 if (opaque_decl_ctx) {
9426 clang::NamedDecl *named_decl =
9427 llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
9428 if (named_decl)
9429 return ConstString(named_decl->getName());
9430 }
9431 return ConstString();
9432 }
9433
9434 ConstString
DeclContextGetScopeQualifiedName(void * opaque_decl_ctx)9435 TypeSystemClang::DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) {
9436 if (opaque_decl_ctx) {
9437 clang::NamedDecl *named_decl =
9438 llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
9439 if (named_decl)
9440 return ConstString(GetTypeNameForDecl(named_decl));
9441 }
9442 return ConstString();
9443 }
9444
DeclContextIsClassMethod(void * opaque_decl_ctx,lldb::LanguageType * language_ptr,bool * is_instance_method_ptr,ConstString * language_object_name_ptr)9445 bool TypeSystemClang::DeclContextIsClassMethod(
9446 void *opaque_decl_ctx, lldb::LanguageType *language_ptr,
9447 bool *is_instance_method_ptr, ConstString *language_object_name_ptr) {
9448 if (opaque_decl_ctx) {
9449 clang::DeclContext *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9450 if (ObjCMethodDecl *objc_method =
9451 llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx)) {
9452 if (is_instance_method_ptr)
9453 *is_instance_method_ptr = objc_method->isInstanceMethod();
9454 if (language_ptr)
9455 *language_ptr = eLanguageTypeObjC;
9456 if (language_object_name_ptr)
9457 language_object_name_ptr->SetCString("self");
9458 return true;
9459 } else if (CXXMethodDecl *cxx_method =
9460 llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx)) {
9461 if (is_instance_method_ptr)
9462 *is_instance_method_ptr = cxx_method->isInstance();
9463 if (language_ptr)
9464 *language_ptr = eLanguageTypeC_plus_plus;
9465 if (language_object_name_ptr)
9466 language_object_name_ptr->SetCString("this");
9467 return true;
9468 } else if (clang::FunctionDecl *function_decl =
9469 llvm::dyn_cast<clang::FunctionDecl>(decl_ctx)) {
9470 ClangASTMetadata *metadata = GetMetadata(function_decl);
9471 if (metadata && metadata->HasObjectPtr()) {
9472 if (is_instance_method_ptr)
9473 *is_instance_method_ptr = true;
9474 if (language_ptr)
9475 *language_ptr = eLanguageTypeObjC;
9476 if (language_object_name_ptr)
9477 language_object_name_ptr->SetCString(metadata->GetObjectPtrName());
9478 return true;
9479 }
9480 }
9481 }
9482 return false;
9483 }
9484
DeclContextIsContainedInLookup(void * opaque_decl_ctx,void * other_opaque_decl_ctx)9485 bool TypeSystemClang::DeclContextIsContainedInLookup(
9486 void *opaque_decl_ctx, void *other_opaque_decl_ctx) {
9487 auto *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9488 auto *other = (clang::DeclContext *)other_opaque_decl_ctx;
9489
9490 do {
9491 // A decl context always includes its own contents in its lookup.
9492 if (decl_ctx == other)
9493 return true;
9494
9495 // If we have an inline namespace, then the lookup of the parent context
9496 // also includes the inline namespace contents.
9497 } while (other->isInlineNamespace() && (other = other->getParent()));
9498
9499 return false;
9500 }
9501
IsClangDeclContext(const CompilerDeclContext & dc)9502 static bool IsClangDeclContext(const CompilerDeclContext &dc) {
9503 return dc.IsValid() && isa<TypeSystemClang>(dc.GetTypeSystem());
9504 }
9505
9506 clang::DeclContext *
DeclContextGetAsDeclContext(const CompilerDeclContext & dc)9507 TypeSystemClang::DeclContextGetAsDeclContext(const CompilerDeclContext &dc) {
9508 if (IsClangDeclContext(dc))
9509 return (clang::DeclContext *)dc.GetOpaqueDeclContext();
9510 return nullptr;
9511 }
9512
9513 ObjCMethodDecl *
DeclContextGetAsObjCMethodDecl(const CompilerDeclContext & dc)9514 TypeSystemClang::DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc) {
9515 if (IsClangDeclContext(dc))
9516 return llvm::dyn_cast<clang::ObjCMethodDecl>(
9517 (clang::DeclContext *)dc.GetOpaqueDeclContext());
9518 return nullptr;
9519 }
9520
9521 CXXMethodDecl *
DeclContextGetAsCXXMethodDecl(const CompilerDeclContext & dc)9522 TypeSystemClang::DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc) {
9523 if (IsClangDeclContext(dc))
9524 return llvm::dyn_cast<clang::CXXMethodDecl>(
9525 (clang::DeclContext *)dc.GetOpaqueDeclContext());
9526 return nullptr;
9527 }
9528
9529 clang::FunctionDecl *
DeclContextGetAsFunctionDecl(const CompilerDeclContext & dc)9530 TypeSystemClang::DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc) {
9531 if (IsClangDeclContext(dc))
9532 return llvm::dyn_cast<clang::FunctionDecl>(
9533 (clang::DeclContext *)dc.GetOpaqueDeclContext());
9534 return nullptr;
9535 }
9536
9537 clang::NamespaceDecl *
DeclContextGetAsNamespaceDecl(const CompilerDeclContext & dc)9538 TypeSystemClang::DeclContextGetAsNamespaceDecl(const CompilerDeclContext &dc) {
9539 if (IsClangDeclContext(dc))
9540 return llvm::dyn_cast<clang::NamespaceDecl>(
9541 (clang::DeclContext *)dc.GetOpaqueDeclContext());
9542 return nullptr;
9543 }
9544
9545 ClangASTMetadata *
DeclContextGetMetaData(const CompilerDeclContext & dc,const Decl * object)9546 TypeSystemClang::DeclContextGetMetaData(const CompilerDeclContext &dc,
9547 const Decl *object) {
9548 TypeSystemClang *ast = llvm::cast<TypeSystemClang>(dc.GetTypeSystem());
9549 return ast->GetMetadata(object);
9550 }
9551
9552 clang::ASTContext *
DeclContextGetTypeSystemClang(const CompilerDeclContext & dc)9553 TypeSystemClang::DeclContextGetTypeSystemClang(const CompilerDeclContext &dc) {
9554 TypeSystemClang *ast =
9555 llvm::dyn_cast_or_null<TypeSystemClang>(dc.GetTypeSystem());
9556 if (ast)
9557 return &ast->getASTContext();
9558 return nullptr;
9559 }
9560
ScratchTypeSystemClang(Target & target,llvm::Triple triple)9561 ScratchTypeSystemClang::ScratchTypeSystemClang(Target &target,
9562 llvm::Triple triple)
9563 : TypeSystemClang("scratch ASTContext", triple),
9564 m_target_wp(target.shared_from_this()),
9565 m_persistent_variables(new ClangPersistentVariables) {
9566 m_scratch_ast_source_up = std::make_unique<ClangASTSource>(
9567 target.shared_from_this(), m_persistent_variables->GetClangASTImporter());
9568 m_scratch_ast_source_up->InstallASTContext(*this);
9569 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
9570 m_scratch_ast_source_up->CreateProxy());
9571 SetExternalSource(proxy_ast_source);
9572 }
9573
Finalize()9574 void ScratchTypeSystemClang::Finalize() {
9575 TypeSystemClang::Finalize();
9576 m_scratch_ast_source_up.reset();
9577 }
9578
GetForTarget(Target & target,bool create_on_demand)9579 TypeSystemClang *ScratchTypeSystemClang::GetForTarget(Target &target,
9580 bool create_on_demand) {
9581 auto type_system_or_err = target.GetScratchTypeSystemForLanguage(
9582 lldb::eLanguageTypeC, create_on_demand);
9583 if (auto err = type_system_or_err.takeError()) {
9584 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
9585 std::move(err), "Couldn't get scratch TypeSystemClang");
9586 return nullptr;
9587 }
9588 return llvm::dyn_cast<TypeSystemClang>(&type_system_or_err.get());
9589 }
9590
GetUserExpression(llvm::StringRef expr,llvm::StringRef prefix,lldb::LanguageType language,Expression::ResultType desired_type,const EvaluateExpressionOptions & options,ValueObject * ctx_obj)9591 UserExpression *ScratchTypeSystemClang::GetUserExpression(
9592 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
9593 Expression::ResultType desired_type,
9594 const EvaluateExpressionOptions &options, ValueObject *ctx_obj) {
9595 TargetSP target_sp = m_target_wp.lock();
9596 if (!target_sp)
9597 return nullptr;
9598
9599 return new ClangUserExpression(*target_sp.get(), expr, prefix, language,
9600 desired_type, options, ctx_obj);
9601 }
9602
GetFunctionCaller(const CompilerType & return_type,const Address & function_address,const ValueList & arg_value_list,const char * name)9603 FunctionCaller *ScratchTypeSystemClang::GetFunctionCaller(
9604 const CompilerType &return_type, const Address &function_address,
9605 const ValueList &arg_value_list, const char *name) {
9606 TargetSP target_sp = m_target_wp.lock();
9607 if (!target_sp)
9608 return nullptr;
9609
9610 Process *process = target_sp->GetProcessSP().get();
9611 if (!process)
9612 return nullptr;
9613
9614 return new ClangFunctionCaller(*process, return_type, function_address,
9615 arg_value_list, name);
9616 }
9617
9618 std::unique_ptr<UtilityFunction>
CreateUtilityFunction(std::string text,std::string name)9619 ScratchTypeSystemClang::CreateUtilityFunction(std::string text,
9620 std::string name) {
9621 TargetSP target_sp = m_target_wp.lock();
9622 if (!target_sp)
9623 return {};
9624
9625 return std::make_unique<ClangUtilityFunction>(
9626 *target_sp.get(), std::move(text), std::move(name));
9627 }
9628
9629 PersistentExpressionState *
GetPersistentExpressionState()9630 ScratchTypeSystemClang::GetPersistentExpressionState() {
9631 return m_persistent_variables.get();
9632 }
9633