Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
Warning:line 9076, column 17
Although the value stored to 'bytes_read' is used in the enclosing expression, the value is never actually read from 'bytes_read'

Annotated Source Code

Press '?' to see keyboard shortcuts

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