1 //===-- ClangASTContext.cpp -------------------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "lldb/Symbol/ClangASTContext.h"
11
12 // C Includes
13 // C++ Includes
14 #include <mutex> // std::once
15 #include <string>
16
17 // Other libraries and framework includes
18
19 // Clang headers like to use NDEBUG inside of them to enable/disable debug
20 // related features using "#ifndef NDEBUG" preprocessor blocks to do one thing
21 // or another. This is bad because it means that if clang was built in release
22 // mode, it assumes that you are building in release mode which is not always
23 // the case. You can end up with functions that are defined as empty in header
24 // files when NDEBUG is not defined, and this can cause link errors with the
25 // clang .a files that you have since you might be missing functions in the .a
26 // file. So we have to define NDEBUG when including clang headers to avoid any
27 // mismatches. This is covered by rdar://problem/8691220
28
29 #if !defined(NDEBUG) && !defined(LLVM_NDEBUG_OFF)
30 #define LLDB_DEFINED_NDEBUG_FOR_CLANG
31 #define NDEBUG
32 // Need to include assert.h so it is as clang would expect it to be (disabled)
33 #include <assert.h>
34 #endif
35
36 #include "clang/AST/ASTContext.h"
37 #include "clang/AST/ASTImporter.h"
38 #include "clang/AST/Attr.h"
39 #include "clang/AST/CXXInheritance.h"
40 #include "clang/AST/DeclObjC.h"
41 #include "clang/AST/DeclTemplate.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/Type.h"
44 #include "clang/Basic/Builtins.h"
45 #include "clang/Basic/Diagnostic.h"
46 #include "clang/Basic/FileManager.h"
47 #include "clang/Basic/FileSystemOptions.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/TargetInfo.h"
50 #include "clang/Basic/TargetOptions.h"
51 #include "clang/Frontend/FrontendOptions.h"
52 #include "clang/Frontend/LangStandard.h"
53
54 #ifdef LLDB_DEFINED_NDEBUG_FOR_CLANG
55 #undef NDEBUG
56 #undef LLDB_DEFINED_NDEBUG_FOR_CLANG
57 // Need to re-include assert.h so it is as _we_ would expect it to be (enabled)
58 #include <assert.h>
59 #endif
60
61 #include "lldb/Core/ArchSpec.h"
62 #include "lldb/Core/dwarf.h"
63 #include "lldb/Core/Flags.h"
64 #include "lldb/Core/Log.h"
65 #include "lldb/Core/RegularExpression.h"
66 #include "lldb/Core/ThreadSafeDenseMap.h"
67 #include "lldb/Core/UniqueCStringMap.h"
68 #include "lldb/Expression/ASTDumper.h"
69 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
70 #include "lldb/Symbol/VerifyDecl.h"
71 #include "lldb/Target/ExecutionContext.h"
72 #include "lldb/Target/Process.h"
73 #include "lldb/Target/ObjCLanguageRuntime.h"
74
75 #include <stdio.h>
76
77 #include <mutex>
78
79 using namespace lldb;
80 using namespace lldb_private;
81 using namespace llvm;
82 using namespace clang;
83
84 typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, ClangASTContext*> ClangASTMap;
85
86 static ClangASTMap &
GetASTMap()87 GetASTMap()
88 {
89 static ClangASTMap *g_map_ptr = nullptr;
90 static std::once_flag g_once_flag;
91 std::call_once(g_once_flag, []() {
92 g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins
93 });
94 return *g_map_ptr;
95 }
96
97
98 clang::AccessSpecifier
ConvertAccessTypeToAccessSpecifier(AccessType access)99 ClangASTContext::ConvertAccessTypeToAccessSpecifier (AccessType access)
100 {
101 switch (access)
102 {
103 default: break;
104 case eAccessNone: return AS_none;
105 case eAccessPublic: return AS_public;
106 case eAccessPrivate: return AS_private;
107 case eAccessProtected: return AS_protected;
108 }
109 return AS_none;
110 }
111
112 static void
ParseLangArgs(LangOptions & Opts,InputKind IK,const char * triple)113 ParseLangArgs (LangOptions &Opts, InputKind IK, const char* triple)
114 {
115 // FIXME: Cleanup per-file based stuff.
116
117 // Set some properties which depend solely on the input kind; it would be nice
118 // to move these to the language standard, and have the driver resolve the
119 // input kind + language standard.
120 if (IK == IK_Asm) {
121 Opts.AsmPreprocessor = 1;
122 } else if (IK == IK_ObjC ||
123 IK == IK_ObjCXX ||
124 IK == IK_PreprocessedObjC ||
125 IK == IK_PreprocessedObjCXX) {
126 Opts.ObjC1 = Opts.ObjC2 = 1;
127 }
128
129 LangStandard::Kind LangStd = LangStandard::lang_unspecified;
130
131 if (LangStd == LangStandard::lang_unspecified) {
132 // Based on the base language, pick one.
133 switch (IK) {
134 case IK_None:
135 case IK_AST:
136 case IK_LLVM_IR:
137 assert (!"Invalid input kind!");
138 case IK_OpenCL:
139 LangStd = LangStandard::lang_opencl;
140 break;
141 case IK_CUDA:
142 case IK_PreprocessedCuda:
143 LangStd = LangStandard::lang_cuda;
144 break;
145 case IK_Asm:
146 case IK_C:
147 case IK_PreprocessedC:
148 case IK_ObjC:
149 case IK_PreprocessedObjC:
150 LangStd = LangStandard::lang_gnu99;
151 break;
152 case IK_CXX:
153 case IK_PreprocessedCXX:
154 case IK_ObjCXX:
155 case IK_PreprocessedObjCXX:
156 LangStd = LangStandard::lang_gnucxx98;
157 break;
158 }
159 }
160
161 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
162 Opts.LineComment = Std.hasLineComments();
163 Opts.C99 = Std.isC99();
164 Opts.CPlusPlus = Std.isCPlusPlus();
165 Opts.CPlusPlus11 = Std.isCPlusPlus11();
166 Opts.Digraphs = Std.hasDigraphs();
167 Opts.GNUMode = Std.isGNUMode();
168 Opts.GNUInline = !Std.isC99();
169 Opts.HexFloats = Std.hasHexFloats();
170 Opts.ImplicitInt = Std.hasImplicitInt();
171
172 Opts.WChar = true;
173
174 // OpenCL has some additional defaults.
175 if (LangStd == LangStandard::lang_opencl) {
176 Opts.OpenCL = 1;
177 Opts.AltiVec = 1;
178 Opts.CXXOperatorNames = 1;
179 Opts.LaxVectorConversions = 1;
180 }
181
182 // OpenCL and C++ both have bool, true, false keywords.
183 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
184
185 // if (Opts.CPlusPlus)
186 // Opts.CXXOperatorNames = !Args.hasArg(OPT_fno_operator_names);
187 //
188 // if (Args.hasArg(OPT_fobjc_gc_only))
189 // Opts.setGCMode(LangOptions::GCOnly);
190 // else if (Args.hasArg(OPT_fobjc_gc))
191 // Opts.setGCMode(LangOptions::HybridGC);
192 //
193 // if (Args.hasArg(OPT_print_ivar_layout))
194 // Opts.ObjCGCBitmapPrint = 1;
195 //
196 // if (Args.hasArg(OPT_faltivec))
197 // Opts.AltiVec = 1;
198 //
199 // if (Args.hasArg(OPT_pthread))
200 // Opts.POSIXThreads = 1;
201 //
202 // llvm::StringRef Vis = getLastArgValue(Args, OPT_fvisibility,
203 // "default");
204 // if (Vis == "default")
205 Opts.setValueVisibilityMode(DefaultVisibility);
206 // else if (Vis == "hidden")
207 // Opts.setVisibilityMode(LangOptions::Hidden);
208 // else if (Vis == "protected")
209 // Opts.setVisibilityMode(LangOptions::Protected);
210 // else
211 // Diags.Report(diag::err_drv_invalid_value)
212 // << Args.getLastArg(OPT_fvisibility)->getAsString(Args) << Vis;
213
214 // Opts.OverflowChecking = Args.hasArg(OPT_ftrapv);
215
216 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
217 // is specified, or -std is set to a conforming mode.
218 Opts.Trigraphs = !Opts.GNUMode;
219 // if (Args.hasArg(OPT_trigraphs))
220 // Opts.Trigraphs = 1;
221 //
222 // Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
223 // OPT_fno_dollars_in_identifiers,
224 // !Opts.AsmPreprocessor);
225 // Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
226 // Opts.Microsoft = Args.hasArg(OPT_fms_extensions);
227 // Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
228 // if (Args.hasArg(OPT_fno_lax_vector_conversions))
229 // Opts.LaxVectorConversions = 0;
230 // Opts.Exceptions = Args.hasArg(OPT_fexceptions);
231 // Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
232 // Opts.Blocks = Args.hasArg(OPT_fblocks);
233 Opts.CharIsSigned = ArchSpec(triple).CharIsSignedByDefault();
234 // Opts.ShortWChar = Args.hasArg(OPT_fshort_wchar);
235 // Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
236 // Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
237 // Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
238 // Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
239 // Opts.AccessControl = Args.hasArg(OPT_faccess_control);
240 // Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
241 // Opts.MathErrno = !Args.hasArg(OPT_fno_math_errno);
242 // Opts.InstantiationDepth = getLastArgIntValue(Args, OPT_ftemplate_depth, 99,
243 // Diags);
244 // Opts.NeXTRuntime = !Args.hasArg(OPT_fgnu_runtime);
245 // Opts.ObjCConstantStringClass = getLastArgValue(Args,
246 // OPT_fconstant_string_class);
247 // Opts.ObjCNonFragileABI = Args.hasArg(OPT_fobjc_nonfragile_abi);
248 // Opts.CatchUndefined = Args.hasArg(OPT_fcatch_undefined_behavior);
249 // Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
250 // Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
251 // Opts.Static = Args.hasArg(OPT_static_define);
252 Opts.OptimizeSize = 0;
253
254 // FIXME: Eliminate this dependency.
255 // unsigned Opt =
256 // Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
257 // Opts.Optimize = Opt != 0;
258 unsigned Opt = 0;
259
260 // This is the __NO_INLINE__ define, which just depends on things like the
261 // optimization level and -fno-inline, not actually whether the backend has
262 // inlining enabled.
263 //
264 // FIXME: This is affected by other options (-fno-inline).
265 Opts.NoInlineDefine = !Opt;
266
267 // unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
268 // switch (SSP) {
269 // default:
270 // Diags.Report(diag::err_drv_invalid_value)
271 // << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
272 // break;
273 // case 0: Opts.setStackProtectorMode(LangOptions::SSPOff); break;
274 // case 1: Opts.setStackProtectorMode(LangOptions::SSPOn); break;
275 // case 2: Opts.setStackProtectorMode(LangOptions::SSPReq); break;
276 // }
277 }
278
279
ClangASTContext(const char * target_triple)280 ClangASTContext::ClangASTContext (const char *target_triple) :
281 m_target_triple(),
282 m_ast_ap(),
283 m_language_options_ap(),
284 m_source_manager_ap(),
285 m_diagnostics_engine_ap(),
286 m_target_options_rp(),
287 m_target_info_ap(),
288 m_identifier_table_ap(),
289 m_selector_table_ap(),
290 m_builtins_ap(),
291 m_callback_tag_decl (nullptr),
292 m_callback_objc_decl (nullptr),
293 m_callback_baton (nullptr),
294 m_pointer_byte_size (0)
295
296 {
297 if (target_triple && target_triple[0])
298 SetTargetTriple (target_triple);
299 }
300
301 //----------------------------------------------------------------------
302 // Destructor
303 //----------------------------------------------------------------------
~ClangASTContext()304 ClangASTContext::~ClangASTContext()
305 {
306 if (m_ast_ap.get())
307 {
308 GetASTMap().Erase(m_ast_ap.get());
309 }
310
311 m_builtins_ap.reset();
312 m_selector_table_ap.reset();
313 m_identifier_table_ap.reset();
314 m_target_info_ap.reset();
315 m_target_options_rp.reset();
316 m_diagnostics_engine_ap.reset();
317 m_source_manager_ap.reset();
318 m_language_options_ap.reset();
319 m_ast_ap.reset();
320 }
321
322
323 void
Clear()324 ClangASTContext::Clear()
325 {
326 m_ast_ap.reset();
327 m_language_options_ap.reset();
328 m_source_manager_ap.reset();
329 m_diagnostics_engine_ap.reset();
330 m_target_options_rp.reset();
331 m_target_info_ap.reset();
332 m_identifier_table_ap.reset();
333 m_selector_table_ap.reset();
334 m_builtins_ap.reset();
335 m_pointer_byte_size = 0;
336 }
337
338 const char *
GetTargetTriple()339 ClangASTContext::GetTargetTriple ()
340 {
341 return m_target_triple.c_str();
342 }
343
344 void
SetTargetTriple(const char * target_triple)345 ClangASTContext::SetTargetTriple (const char *target_triple)
346 {
347 Clear();
348 m_target_triple.assign(target_triple);
349 }
350
351 void
SetArchitecture(const ArchSpec & arch)352 ClangASTContext::SetArchitecture (const ArchSpec &arch)
353 {
354 SetTargetTriple(arch.GetTriple().str().c_str());
355 }
356
357 bool
HasExternalSource()358 ClangASTContext::HasExternalSource ()
359 {
360 ASTContext *ast = getASTContext();
361 if (ast)
362 return ast->getExternalSource () != nullptr;
363 return false;
364 }
365
366 void
SetExternalSource(llvm::IntrusiveRefCntPtr<ExternalASTSource> & ast_source_ap)367 ClangASTContext::SetExternalSource (llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_ap)
368 {
369 ASTContext *ast = getASTContext();
370 if (ast)
371 {
372 ast->setExternalSource (ast_source_ap);
373 ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
374 //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(true);
375 }
376 }
377
378 void
RemoveExternalSource()379 ClangASTContext::RemoveExternalSource ()
380 {
381 ASTContext *ast = getASTContext();
382
383 if (ast)
384 {
385 llvm::IntrusiveRefCntPtr<ExternalASTSource> empty_ast_source_ap;
386 ast->setExternalSource (empty_ast_source_ap);
387 ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(false);
388 //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(false);
389 }
390 }
391
392
393
394 ASTContext *
getASTContext()395 ClangASTContext::getASTContext()
396 {
397 if (m_ast_ap.get() == nullptr)
398 {
399 m_ast_ap.reset(new ASTContext (*getLanguageOptions(),
400 *getSourceManager(),
401 *getIdentifierTable(),
402 *getSelectorTable(),
403 *getBuiltinContext()));
404
405 m_ast_ap->getDiagnostics().setClient(getDiagnosticConsumer(), false);
406
407 // This can be NULL if we don't know anything about the architecture or if the
408 // target for an architecture isn't enabled in the llvm/clang that we built
409 TargetInfo *target_info = getTargetInfo();
410 if (target_info)
411 m_ast_ap->InitBuiltinTypes(*target_info);
412
413 if ((m_callback_tag_decl || m_callback_objc_decl) && m_callback_baton)
414 {
415 m_ast_ap->getTranslationUnitDecl()->setHasExternalLexicalStorage();
416 //m_ast_ap->getTranslationUnitDecl()->setHasExternalVisibleStorage();
417 }
418
419 GetASTMap().Insert(m_ast_ap.get(), this);
420 }
421 return m_ast_ap.get();
422 }
423
424 ClangASTContext*
GetASTContext(clang::ASTContext * ast)425 ClangASTContext::GetASTContext (clang::ASTContext* ast)
426 {
427 ClangASTContext *clang_ast = GetASTMap().Lookup(ast);
428 return clang_ast;
429 }
430
431 Builtin::Context *
getBuiltinContext()432 ClangASTContext::getBuiltinContext()
433 {
434 if (m_builtins_ap.get() == nullptr)
435 m_builtins_ap.reset (new Builtin::Context());
436 return m_builtins_ap.get();
437 }
438
439 IdentifierTable *
getIdentifierTable()440 ClangASTContext::getIdentifierTable()
441 {
442 if (m_identifier_table_ap.get() == nullptr)
443 m_identifier_table_ap.reset(new IdentifierTable (*ClangASTContext::getLanguageOptions(), nullptr));
444 return m_identifier_table_ap.get();
445 }
446
447 LangOptions *
getLanguageOptions()448 ClangASTContext::getLanguageOptions()
449 {
450 if (m_language_options_ap.get() == nullptr)
451 {
452 m_language_options_ap.reset(new LangOptions());
453 ParseLangArgs(*m_language_options_ap, IK_ObjCXX, GetTargetTriple());
454 // InitializeLangOptions(*m_language_options_ap, IK_ObjCXX);
455 }
456 return m_language_options_ap.get();
457 }
458
459 SelectorTable *
getSelectorTable()460 ClangASTContext::getSelectorTable()
461 {
462 if (m_selector_table_ap.get() == nullptr)
463 m_selector_table_ap.reset (new SelectorTable());
464 return m_selector_table_ap.get();
465 }
466
467 clang::FileManager *
getFileManager()468 ClangASTContext::getFileManager()
469 {
470 if (m_file_manager_ap.get() == nullptr)
471 {
472 clang::FileSystemOptions file_system_options;
473 m_file_manager_ap.reset(new clang::FileManager(file_system_options));
474 }
475 return m_file_manager_ap.get();
476 }
477
478 clang::SourceManager *
getSourceManager()479 ClangASTContext::getSourceManager()
480 {
481 if (m_source_manager_ap.get() == nullptr)
482 m_source_manager_ap.reset(new clang::SourceManager(*getDiagnosticsEngine(), *getFileManager()));
483 return m_source_manager_ap.get();
484 }
485
486 clang::DiagnosticsEngine *
getDiagnosticsEngine()487 ClangASTContext::getDiagnosticsEngine()
488 {
489 if (m_diagnostics_engine_ap.get() == nullptr)
490 {
491 llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
492 m_diagnostics_engine_ap.reset(new DiagnosticsEngine(diag_id_sp, new DiagnosticOptions()));
493 }
494 return m_diagnostics_engine_ap.get();
495 }
496
497 class NullDiagnosticConsumer : public DiagnosticConsumer
498 {
499 public:
NullDiagnosticConsumer()500 NullDiagnosticConsumer ()
501 {
502 m_log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
503 }
504
HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,const Diagnostic & info)505 void HandleDiagnostic (DiagnosticsEngine::Level DiagLevel, const Diagnostic &info)
506 {
507 if (m_log)
508 {
509 llvm::SmallVector<char, 32> diag_str(10);
510 info.FormatDiagnostic(diag_str);
511 diag_str.push_back('\0');
512 m_log->Printf("Compiler diagnostic: %s\n", diag_str.data());
513 }
514 }
515
clone(DiagnosticsEngine & Diags) const516 DiagnosticConsumer *clone (DiagnosticsEngine &Diags) const
517 {
518 return new NullDiagnosticConsumer ();
519 }
520 private:
521 Log * m_log;
522 };
523
524 DiagnosticConsumer *
getDiagnosticConsumer()525 ClangASTContext::getDiagnosticConsumer()
526 {
527 if (m_diagnostic_consumer_ap.get() == nullptr)
528 m_diagnostic_consumer_ap.reset(new NullDiagnosticConsumer);
529
530 return m_diagnostic_consumer_ap.get();
531 }
532
533 std::shared_ptr<TargetOptions> &
getTargetOptions()534 ClangASTContext::getTargetOptions() {
535 if (m_target_options_rp.get() == nullptr && !m_target_triple.empty())
536 {
537 m_target_options_rp = std::make_shared<TargetOptions>();
538 if (m_target_options_rp.get() != nullptr)
539 m_target_options_rp->Triple = m_target_triple;
540 }
541 return m_target_options_rp;
542 }
543
544
545 TargetInfo *
getTargetInfo()546 ClangASTContext::getTargetInfo()
547 {
548 // target_triple should be something like "x86_64-apple-macosx"
549 if (m_target_info_ap.get() == nullptr && !m_target_triple.empty())
550 m_target_info_ap.reset (TargetInfo::CreateTargetInfo(*getDiagnosticsEngine(), getTargetOptions()));
551 return m_target_info_ap.get();
552 }
553
554 #pragma mark Basic Types
555
556 static inline bool
QualTypeMatchesBitSize(const uint64_t bit_size,ASTContext * ast,QualType qual_type)557 QualTypeMatchesBitSize(const uint64_t bit_size, ASTContext *ast, QualType qual_type)
558 {
559 uint64_t qual_type_bit_size = ast->getTypeSize(qual_type);
560 if (qual_type_bit_size == bit_size)
561 return true;
562 return false;
563 }
564 ClangASTType
GetBuiltinTypeForEncodingAndBitSize(Encoding encoding,uint32_t bit_size)565 ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (Encoding encoding, uint32_t bit_size)
566 {
567 return ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (getASTContext(), encoding, bit_size);
568 }
569
570 ClangASTType
GetBuiltinTypeForEncodingAndBitSize(ASTContext * ast,Encoding encoding,uint32_t bit_size)571 ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (ASTContext *ast, Encoding encoding, uint32_t bit_size)
572 {
573 if (!ast)
574 return ClangASTType();
575
576 switch (encoding)
577 {
578 case eEncodingInvalid:
579 if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy))
580 return ClangASTType (ast, ast->VoidPtrTy.getAsOpaquePtr());
581 break;
582
583 case eEncodingUint:
584 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
585 return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
586 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
587 return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
588 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
589 return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr());
590 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
591 return ClangASTType (ast, ast->UnsignedLongTy.getAsOpaquePtr());
592 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
593 return ClangASTType (ast, ast->UnsignedLongLongTy.getAsOpaquePtr());
594 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
595 return ClangASTType (ast, ast->UnsignedInt128Ty.getAsOpaquePtr());
596 break;
597
598 case eEncodingSint:
599 if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
600 return ClangASTType (ast, ast->CharTy.getAsOpaquePtr());
601 if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
602 return ClangASTType (ast, ast->ShortTy.getAsOpaquePtr());
603 if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
604 return ClangASTType (ast, ast->IntTy.getAsOpaquePtr());
605 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
606 return ClangASTType (ast, ast->LongTy.getAsOpaquePtr());
607 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
608 return ClangASTType (ast, ast->LongLongTy.getAsOpaquePtr());
609 if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
610 return ClangASTType (ast, ast->Int128Ty.getAsOpaquePtr());
611 break;
612
613 case eEncodingIEEE754:
614 if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
615 return ClangASTType (ast, ast->FloatTy.getAsOpaquePtr());
616 if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
617 return ClangASTType (ast, ast->DoubleTy.getAsOpaquePtr());
618 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
619 return ClangASTType (ast, ast->LongDoubleTy.getAsOpaquePtr());
620 break;
621
622 case eEncodingVector:
623 // Sanity check that bit_size is a multiple of 8's.
624 if (bit_size && !(bit_size & 0x7u))
625 return ClangASTType (ast, ast->getExtVectorType (ast->UnsignedCharTy, bit_size/8).getAsOpaquePtr());
626 break;
627 }
628
629 return ClangASTType();
630 }
631
632
633
634 lldb::BasicType
GetBasicTypeEnumeration(const ConstString & name)635 ClangASTContext::GetBasicTypeEnumeration (const ConstString &name)
636 {
637 if (name)
638 {
639 typedef UniqueCStringMap<lldb::BasicType> TypeNameToBasicTypeMap;
640 static TypeNameToBasicTypeMap g_type_map;
641 static std::once_flag g_once_flag;
642 std::call_once(g_once_flag, [](){
643 // "void"
644 g_type_map.Append(ConstString("void").GetCString(), eBasicTypeVoid);
645
646 // "char"
647 g_type_map.Append(ConstString("char").GetCString(), eBasicTypeChar);
648 g_type_map.Append(ConstString("signed char").GetCString(), eBasicTypeSignedChar);
649 g_type_map.Append(ConstString("unsigned char").GetCString(), eBasicTypeUnsignedChar);
650 g_type_map.Append(ConstString("wchar_t").GetCString(), eBasicTypeWChar);
651 g_type_map.Append(ConstString("signed wchar_t").GetCString(), eBasicTypeSignedWChar);
652 g_type_map.Append(ConstString("unsigned wchar_t").GetCString(), eBasicTypeUnsignedWChar);
653 // "short"
654 g_type_map.Append(ConstString("short").GetCString(), eBasicTypeShort);
655 g_type_map.Append(ConstString("short int").GetCString(), eBasicTypeShort);
656 g_type_map.Append(ConstString("unsigned short").GetCString(), eBasicTypeUnsignedShort);
657 g_type_map.Append(ConstString("unsigned short int").GetCString(), eBasicTypeUnsignedShort);
658
659 // "int"
660 g_type_map.Append(ConstString("int").GetCString(), eBasicTypeInt);
661 g_type_map.Append(ConstString("signed int").GetCString(), eBasicTypeInt);
662 g_type_map.Append(ConstString("unsigned int").GetCString(), eBasicTypeUnsignedInt);
663 g_type_map.Append(ConstString("unsigned").GetCString(), eBasicTypeUnsignedInt);
664
665 // "long"
666 g_type_map.Append(ConstString("long").GetCString(), eBasicTypeLong);
667 g_type_map.Append(ConstString("long int").GetCString(), eBasicTypeLong);
668 g_type_map.Append(ConstString("unsigned long").GetCString(), eBasicTypeUnsignedLong);
669 g_type_map.Append(ConstString("unsigned long int").GetCString(), eBasicTypeUnsignedLong);
670
671 // "long long"
672 g_type_map.Append(ConstString("long long").GetCString(), eBasicTypeLongLong);
673 g_type_map.Append(ConstString("long long int").GetCString(), eBasicTypeLongLong);
674 g_type_map.Append(ConstString("unsigned long long").GetCString(), eBasicTypeUnsignedLongLong);
675 g_type_map.Append(ConstString("unsigned long long int").GetCString(), eBasicTypeUnsignedLongLong);
676
677 // "int128"
678 g_type_map.Append(ConstString("__int128_t").GetCString(), eBasicTypeInt128);
679 g_type_map.Append(ConstString("__uint128_t").GetCString(), eBasicTypeUnsignedInt128);
680
681 // Miscellaneous
682 g_type_map.Append(ConstString("bool").GetCString(), eBasicTypeBool);
683 g_type_map.Append(ConstString("float").GetCString(), eBasicTypeFloat);
684 g_type_map.Append(ConstString("double").GetCString(), eBasicTypeDouble);
685 g_type_map.Append(ConstString("long double").GetCString(), eBasicTypeLongDouble);
686 g_type_map.Append(ConstString("id").GetCString(), eBasicTypeObjCID);
687 g_type_map.Append(ConstString("SEL").GetCString(), eBasicTypeObjCSel);
688 g_type_map.Append(ConstString("nullptr").GetCString(), eBasicTypeNullPtr);
689 g_type_map.Sort();
690 });
691
692 return g_type_map.Find(name.GetCString(), eBasicTypeInvalid);
693 }
694 return eBasicTypeInvalid;
695 }
696
697 ClangASTType
GetBasicType(ASTContext * ast,const ConstString & name)698 ClangASTContext::GetBasicType (ASTContext *ast, const ConstString &name)
699 {
700 if (ast)
701 {
702 lldb::BasicType basic_type = ClangASTContext::GetBasicTypeEnumeration (name);
703 return ClangASTContext::GetBasicType (ast, basic_type);
704 }
705 return ClangASTType();
706 }
707
708 uint32_t
GetPointerByteSize()709 ClangASTContext::GetPointerByteSize ()
710 {
711 if (m_pointer_byte_size == 0)
712 m_pointer_byte_size = GetBasicType(lldb::eBasicTypeVoid).GetPointerType().GetByteSize(nullptr);
713 return m_pointer_byte_size;
714 }
715
716 ClangASTType
GetBasicType(lldb::BasicType basic_type)717 ClangASTContext::GetBasicType (lldb::BasicType basic_type)
718 {
719 return GetBasicType (getASTContext(), basic_type);
720 }
721
722 ClangASTType
GetBasicType(ASTContext * ast,lldb::BasicType basic_type)723 ClangASTContext::GetBasicType (ASTContext *ast, lldb::BasicType basic_type)
724 {
725 if (ast)
726 {
727 clang_type_t clang_type = nullptr;
728
729 switch (basic_type)
730 {
731 case eBasicTypeInvalid:
732 case eBasicTypeOther:
733 break;
734 case eBasicTypeVoid:
735 clang_type = ast->VoidTy.getAsOpaquePtr();
736 break;
737 case eBasicTypeChar:
738 clang_type = ast->CharTy.getAsOpaquePtr();
739 break;
740 case eBasicTypeSignedChar:
741 clang_type = ast->SignedCharTy.getAsOpaquePtr();
742 break;
743 case eBasicTypeUnsignedChar:
744 clang_type = ast->UnsignedCharTy.getAsOpaquePtr();
745 break;
746 case eBasicTypeWChar:
747 clang_type = ast->getWCharType().getAsOpaquePtr();
748 break;
749 case eBasicTypeSignedWChar:
750 clang_type = ast->getSignedWCharType().getAsOpaquePtr();
751 break;
752 case eBasicTypeUnsignedWChar:
753 clang_type = ast->getUnsignedWCharType().getAsOpaquePtr();
754 break;
755 case eBasicTypeChar16:
756 clang_type = ast->Char16Ty.getAsOpaquePtr();
757 break;
758 case eBasicTypeChar32:
759 clang_type = ast->Char32Ty.getAsOpaquePtr();
760 break;
761 case eBasicTypeShort:
762 clang_type = ast->ShortTy.getAsOpaquePtr();
763 break;
764 case eBasicTypeUnsignedShort:
765 clang_type = ast->UnsignedShortTy.getAsOpaquePtr();
766 break;
767 case eBasicTypeInt:
768 clang_type = ast->IntTy.getAsOpaquePtr();
769 break;
770 case eBasicTypeUnsignedInt:
771 clang_type = ast->UnsignedIntTy.getAsOpaquePtr();
772 break;
773 case eBasicTypeLong:
774 clang_type = ast->LongTy.getAsOpaquePtr();
775 break;
776 case eBasicTypeUnsignedLong:
777 clang_type = ast->UnsignedLongTy.getAsOpaquePtr();
778 break;
779 case eBasicTypeLongLong:
780 clang_type = ast->LongLongTy.getAsOpaquePtr();
781 break;
782 case eBasicTypeUnsignedLongLong:
783 clang_type = ast->UnsignedLongLongTy.getAsOpaquePtr();
784 break;
785 case eBasicTypeInt128:
786 clang_type = ast->Int128Ty.getAsOpaquePtr();
787 break;
788 case eBasicTypeUnsignedInt128:
789 clang_type = ast->UnsignedInt128Ty.getAsOpaquePtr();
790 break;
791 case eBasicTypeBool:
792 clang_type = ast->BoolTy.getAsOpaquePtr();
793 break;
794 case eBasicTypeHalf:
795 clang_type = ast->HalfTy.getAsOpaquePtr();
796 break;
797 case eBasicTypeFloat:
798 clang_type = ast->FloatTy.getAsOpaquePtr();
799 break;
800 case eBasicTypeDouble:
801 clang_type = ast->DoubleTy.getAsOpaquePtr();
802 break;
803 case eBasicTypeLongDouble:
804 clang_type = ast->LongDoubleTy.getAsOpaquePtr();
805 break;
806 case eBasicTypeFloatComplex:
807 clang_type = ast->FloatComplexTy.getAsOpaquePtr();
808 break;
809 case eBasicTypeDoubleComplex:
810 clang_type = ast->DoubleComplexTy.getAsOpaquePtr();
811 break;
812 case eBasicTypeLongDoubleComplex:
813 clang_type = ast->LongDoubleComplexTy.getAsOpaquePtr();
814 break;
815 case eBasicTypeObjCID:
816 clang_type = ast->getObjCIdType().getAsOpaquePtr();
817 break;
818 case eBasicTypeObjCClass:
819 clang_type = ast->getObjCClassType().getAsOpaquePtr();
820 break;
821 case eBasicTypeObjCSel:
822 clang_type = ast->getObjCSelType().getAsOpaquePtr();
823 break;
824 case eBasicTypeNullPtr:
825 clang_type = ast->NullPtrTy.getAsOpaquePtr();
826 break;
827 }
828
829 if (clang_type)
830 return ClangASTType (ast, clang_type);
831 }
832 return ClangASTType();
833 }
834
835
836 ClangASTType
GetBuiltinTypeForDWARFEncodingAndBitSize(const char * type_name,uint32_t dw_ate,uint32_t bit_size)837 ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize (const char *type_name, uint32_t dw_ate, uint32_t bit_size)
838 {
839 ASTContext *ast = getASTContext();
840
841 #define streq(a,b) strcmp(a,b) == 0
842 assert (ast != nullptr);
843 if (ast)
844 {
845 switch (dw_ate)
846 {
847 default:
848 break;
849
850 case DW_ATE_address:
851 if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy))
852 return ClangASTType (ast, ast->VoidPtrTy.getAsOpaquePtr());
853 break;
854
855 case DW_ATE_boolean:
856 if (QualTypeMatchesBitSize (bit_size, ast, ast->BoolTy))
857 return ClangASTType (ast, ast->BoolTy.getAsOpaquePtr());
858 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
859 return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
860 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
861 return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
862 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
863 return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr());
864 break;
865
866 case DW_ATE_lo_user:
867 // This has been seen to mean DW_AT_complex_integer
868 if (type_name)
869 {
870 if (::strstr(type_name, "complex"))
871 {
872 ClangASTType complex_int_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("int", DW_ATE_signed, bit_size/2);
873 return ClangASTType (ast, ast->getComplexType (complex_int_clang_type.GetQualType()).getAsOpaquePtr());
874 }
875 }
876 break;
877
878 case DW_ATE_complex_float:
879 if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatComplexTy))
880 return ClangASTType (ast, ast->FloatComplexTy.getAsOpaquePtr());
881 else if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleComplexTy))
882 return ClangASTType (ast, ast->DoubleComplexTy.getAsOpaquePtr());
883 else if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleComplexTy))
884 return ClangASTType (ast, ast->LongDoubleComplexTy.getAsOpaquePtr());
885 else
886 {
887 ClangASTType complex_float_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("float", DW_ATE_float, bit_size/2);
888 return ClangASTType (ast, ast->getComplexType (complex_float_clang_type.GetQualType()).getAsOpaquePtr());
889 }
890 break;
891
892 case DW_ATE_float:
893 if (streq(type_name, "float") && QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
894 return ClangASTType (ast, ast->FloatTy.getAsOpaquePtr());
895 if (streq(type_name, "double") && QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
896 return ClangASTType (ast, ast->DoubleTy.getAsOpaquePtr());
897 if (streq(type_name, "long double") && QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
898 return ClangASTType (ast, ast->LongDoubleTy.getAsOpaquePtr());
899 // Fall back to not requring a name match
900 if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
901 return ClangASTType (ast, ast->FloatTy.getAsOpaquePtr());
902 if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
903 return ClangASTType (ast, ast->DoubleTy.getAsOpaquePtr());
904 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
905 return ClangASTType (ast, ast->LongDoubleTy.getAsOpaquePtr());
906 break;
907
908 case DW_ATE_signed:
909 if (type_name)
910 {
911 if (streq(type_name, "wchar_t") &&
912 QualTypeMatchesBitSize (bit_size, ast, ast->WCharTy) &&
913 (getTargetInfo() && TargetInfo::isTypeSigned (getTargetInfo()->getWCharType())))
914 return ClangASTType (ast, ast->WCharTy.getAsOpaquePtr());
915 if (streq(type_name, "void") &&
916 QualTypeMatchesBitSize (bit_size, ast, ast->VoidTy))
917 return ClangASTType (ast, ast->VoidTy.getAsOpaquePtr());
918 if (strstr(type_name, "long long") &&
919 QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
920 return ClangASTType (ast, ast->LongLongTy.getAsOpaquePtr());
921 if (strstr(type_name, "long") &&
922 QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
923 return ClangASTType (ast, ast->LongTy.getAsOpaquePtr());
924 if (strstr(type_name, "short") &&
925 QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
926 return ClangASTType (ast, ast->ShortTy.getAsOpaquePtr());
927 if (strstr(type_name, "char"))
928 {
929 if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
930 return ClangASTType (ast, ast->CharTy.getAsOpaquePtr());
931 if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
932 return ClangASTType (ast, ast->SignedCharTy.getAsOpaquePtr());
933 }
934 if (strstr(type_name, "int"))
935 {
936 if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
937 return ClangASTType (ast, ast->IntTy.getAsOpaquePtr());
938 if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
939 return ClangASTType (ast, ast->Int128Ty.getAsOpaquePtr());
940 }
941 }
942 // We weren't able to match up a type name, just search by size
943 if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
944 return ClangASTType (ast, ast->CharTy.getAsOpaquePtr());
945 if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
946 return ClangASTType (ast, ast->ShortTy.getAsOpaquePtr());
947 if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
948 return ClangASTType (ast, ast->IntTy.getAsOpaquePtr());
949 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
950 return ClangASTType (ast, ast->LongTy.getAsOpaquePtr());
951 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
952 return ClangASTType (ast, ast->LongLongTy.getAsOpaquePtr());
953 if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
954 return ClangASTType (ast, ast->Int128Ty.getAsOpaquePtr());
955 break;
956
957 case DW_ATE_signed_char:
958 if (ast->getLangOpts().CharIsSigned && type_name && streq(type_name, "char"))
959 {
960 if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
961 return ClangASTType (ast, ast->CharTy.getAsOpaquePtr());
962 }
963 if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
964 return ClangASTType (ast, ast->SignedCharTy.getAsOpaquePtr());
965 break;
966
967 case DW_ATE_unsigned:
968 if (type_name)
969 {
970 if (streq(type_name, "wchar_t"))
971 {
972 if (QualTypeMatchesBitSize (bit_size, ast, ast->WCharTy))
973 {
974 if (!(getTargetInfo() && TargetInfo::isTypeSigned (getTargetInfo()->getWCharType())))
975 return ClangASTType (ast, ast->WCharTy.getAsOpaquePtr());
976 }
977 }
978 if (strstr(type_name, "long long"))
979 {
980 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
981 return ClangASTType (ast, ast->UnsignedLongLongTy.getAsOpaquePtr());
982 }
983 else if (strstr(type_name, "long"))
984 {
985 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
986 return ClangASTType (ast, ast->UnsignedLongTy.getAsOpaquePtr());
987 }
988 else if (strstr(type_name, "short"))
989 {
990 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
991 return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
992 }
993 else if (strstr(type_name, "char"))
994 {
995 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
996 return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
997 }
998 else if (strstr(type_name, "int"))
999 {
1000 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
1001 return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr());
1002 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
1003 return ClangASTType (ast, ast->UnsignedInt128Ty.getAsOpaquePtr());
1004 }
1005 }
1006 // We weren't able to match up a type name, just search by size
1007 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
1008 return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
1009 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
1010 return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
1011 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
1012 return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr());
1013 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
1014 return ClangASTType (ast, ast->UnsignedLongTy.getAsOpaquePtr());
1015 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
1016 return ClangASTType (ast, ast->UnsignedLongLongTy.getAsOpaquePtr());
1017 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
1018 return ClangASTType (ast, ast->UnsignedInt128Ty.getAsOpaquePtr());
1019 break;
1020
1021 case DW_ATE_unsigned_char:
1022 if (!ast->getLangOpts().CharIsSigned && type_name && streq(type_name, "char"))
1023 {
1024 if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
1025 return ClangASTType (ast, ast->CharTy.getAsOpaquePtr());
1026 }
1027 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
1028 return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
1029 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
1030 return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
1031 break;
1032
1033 case DW_ATE_imaginary_float:
1034 break;
1035
1036 case DW_ATE_UTF:
1037 if (type_name)
1038 {
1039 if (streq(type_name, "char16_t"))
1040 {
1041 return ClangASTType (ast, ast->Char16Ty.getAsOpaquePtr());
1042 }
1043 else if (streq(type_name, "char32_t"))
1044 {
1045 return ClangASTType (ast, ast->Char32Ty.getAsOpaquePtr());
1046 }
1047 }
1048 break;
1049 }
1050 }
1051 // This assert should fire for anything that we don't catch above so we know
1052 // to fix any issues we run into.
1053 if (type_name)
1054 {
1055 Host::SystemLog (Host::eSystemLogError, "error: need to add support for DW_TAG_base_type '%s' encoded with DW_ATE = 0x%x, bit_size = %u\n", type_name, dw_ate, bit_size);
1056 }
1057 else
1058 {
1059 Host::SystemLog (Host::eSystemLogError, "error: need to add support for DW_TAG_base_type encoded with DW_ATE = 0x%x, bit_size = %u\n", dw_ate, bit_size);
1060 }
1061 return ClangASTType ();
1062 }
1063
1064 ClangASTType
GetUnknownAnyType(clang::ASTContext * ast)1065 ClangASTContext::GetUnknownAnyType(clang::ASTContext *ast)
1066 {
1067 if (ast)
1068 return ClangASTType (ast, ast->UnknownAnyTy.getAsOpaquePtr());
1069 return ClangASTType();
1070 }
1071
1072 ClangASTType
GetCStringType(bool is_const)1073 ClangASTContext::GetCStringType (bool is_const)
1074 {
1075 ASTContext *ast = getASTContext();
1076 QualType char_type(ast->CharTy);
1077
1078 if (is_const)
1079 char_type.addConst();
1080
1081 return ClangASTType (ast, ast->getPointerType(char_type).getAsOpaquePtr());
1082 }
1083
1084 clang::DeclContext *
GetTranslationUnitDecl(clang::ASTContext * ast)1085 ClangASTContext::GetTranslationUnitDecl (clang::ASTContext *ast)
1086 {
1087 return ast->getTranslationUnitDecl();
1088 }
1089
1090 ClangASTType
CopyType(ASTContext * dst_ast,ClangASTType src)1091 ClangASTContext::CopyType (ASTContext *dst_ast,
1092 ClangASTType src)
1093 {
1094 FileSystemOptions file_system_options;
1095 ASTContext *src_ast = src.GetASTContext();
1096 FileManager file_manager (file_system_options);
1097 ASTImporter importer(*dst_ast, file_manager,
1098 *src_ast, file_manager,
1099 false);
1100
1101 QualType dst (importer.Import(src.GetQualType()));
1102
1103 return ClangASTType (dst_ast, dst.getAsOpaquePtr());
1104 }
1105
1106
1107 clang::Decl *
CopyDecl(ASTContext * dst_ast,ASTContext * src_ast,clang::Decl * source_decl)1108 ClangASTContext::CopyDecl (ASTContext *dst_ast,
1109 ASTContext *src_ast,
1110 clang::Decl *source_decl)
1111 {
1112 FileSystemOptions file_system_options;
1113 FileManager file_manager (file_system_options);
1114 ASTImporter importer(*dst_ast, file_manager,
1115 *src_ast, file_manager,
1116 false);
1117
1118 return importer.Import(source_decl);
1119 }
1120
1121 bool
AreTypesSame(ClangASTType type1,ClangASTType type2,bool ignore_qualifiers)1122 ClangASTContext::AreTypesSame (ClangASTType type1,
1123 ClangASTType type2,
1124 bool ignore_qualifiers)
1125 {
1126 ASTContext *ast = type1.GetASTContext();
1127 if (ast != type2.GetASTContext())
1128 return false;
1129
1130 if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType())
1131 return true;
1132
1133 QualType type1_qual = type1.GetQualType();
1134 QualType type2_qual = type2.GetQualType();
1135
1136 if (ignore_qualifiers)
1137 {
1138 type1_qual = type1_qual.getUnqualifiedType();
1139 type2_qual = type2_qual.getUnqualifiedType();
1140 }
1141
1142 return ast->hasSameType (type1_qual, type2_qual);
1143 }
1144
1145 ClangASTType
GetTypeForDecl(clang::NamedDecl * decl)1146 ClangASTContext::GetTypeForDecl (clang::NamedDecl *decl)
1147 {
1148 if (clang::ObjCInterfaceDecl *interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
1149 return GetTypeForDecl(interface_decl);
1150 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
1151 return GetTypeForDecl(tag_decl);
1152 return ClangASTType();
1153 }
1154
1155
1156 ClangASTType
GetTypeForDecl(TagDecl * decl)1157 ClangASTContext::GetTypeForDecl (TagDecl *decl)
1158 {
1159 // No need to call the getASTContext() accessor (which can create the AST
1160 // if it isn't created yet, because we can't have created a decl in this
1161 // AST if our AST didn't already exist...
1162 ASTContext *ast = &decl->getASTContext();
1163 if (ast)
1164 return ClangASTType (ast, ast->getTagDeclType(decl).getAsOpaquePtr());
1165 return ClangASTType();
1166 }
1167
1168 ClangASTType
GetTypeForDecl(ObjCInterfaceDecl * decl)1169 ClangASTContext::GetTypeForDecl (ObjCInterfaceDecl *decl)
1170 {
1171 // No need to call the getASTContext() accessor (which can create the AST
1172 // if it isn't created yet, because we can't have created a decl in this
1173 // AST if our AST didn't already exist...
1174 ASTContext *ast = &decl->getASTContext();
1175 if (ast)
1176 return ClangASTType (ast, ast->getObjCInterfaceType(decl).getAsOpaquePtr());
1177 return ClangASTType();
1178 }
1179
1180 #pragma mark Structure, Unions, Classes
1181
1182 ClangASTType
CreateRecordType(DeclContext * decl_ctx,AccessType access_type,const char * name,int kind,LanguageType language,ClangASTMetadata * metadata)1183 ClangASTContext::CreateRecordType (DeclContext *decl_ctx,
1184 AccessType access_type,
1185 const char *name,
1186 int kind,
1187 LanguageType language,
1188 ClangASTMetadata *metadata)
1189 {
1190 ASTContext *ast = getASTContext();
1191 assert (ast != nullptr);
1192
1193 if (decl_ctx == nullptr)
1194 decl_ctx = ast->getTranslationUnitDecl();
1195
1196
1197 if (language == eLanguageTypeObjC || language == eLanguageTypeObjC_plus_plus)
1198 {
1199 bool isForwardDecl = true;
1200 bool isInternal = false;
1201 return CreateObjCClass (name, decl_ctx, isForwardDecl, isInternal, metadata);
1202 }
1203
1204 // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1205 // we will need to update this code. I was told to currently always use
1206 // the CXXRecordDecl class since we often don't know from debug information
1207 // if something is struct or a class, so we default to always use the more
1208 // complete definition just in case.
1209
1210 bool is_anonymous = (!name) || (!name[0]);
1211
1212 CXXRecordDecl *decl = CXXRecordDecl::Create (*ast,
1213 (TagDecl::TagKind)kind,
1214 decl_ctx,
1215 SourceLocation(),
1216 SourceLocation(),
1217 is_anonymous ? nullptr : &ast->Idents.get(name));
1218
1219 if (is_anonymous)
1220 decl->setAnonymousStructOrUnion(true);
1221
1222 if (decl)
1223 {
1224 if (metadata)
1225 SetMetadata(ast, decl, *metadata);
1226
1227 if (access_type != eAccessNone)
1228 decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type));
1229
1230 if (decl_ctx)
1231 decl_ctx->addDecl (decl);
1232
1233 return ClangASTType(ast, ast->getTagDeclType(decl).getAsOpaquePtr());
1234 }
1235 return ClangASTType();
1236 }
1237
1238 static TemplateParameterList *
CreateTemplateParameterList(ASTContext * ast,const ClangASTContext::TemplateParameterInfos & template_param_infos,llvm::SmallVector<NamedDecl *,8> & template_param_decls)1239 CreateTemplateParameterList (ASTContext *ast,
1240 const ClangASTContext::TemplateParameterInfos &template_param_infos,
1241 llvm::SmallVector<NamedDecl *, 8> &template_param_decls)
1242 {
1243 const bool parameter_pack = false;
1244 const bool is_typename = false;
1245 const unsigned depth = 0;
1246 const size_t num_template_params = template_param_infos.GetSize();
1247 for (size_t i=0; i<num_template_params; ++i)
1248 {
1249 const char *name = template_param_infos.names[i];
1250
1251 IdentifierInfo *identifier_info = nullptr;
1252 if (name && name[0])
1253 identifier_info = &ast->Idents.get(name);
1254 if (template_param_infos.args[i].getKind() == TemplateArgument::Integral)
1255 {
1256 template_param_decls.push_back (NonTypeTemplateParmDecl::Create (*ast,
1257 ast->getTranslationUnitDecl(), // Is this the right decl context?, SourceLocation StartLoc,
1258 SourceLocation(),
1259 SourceLocation(),
1260 depth,
1261 i,
1262 identifier_info,
1263 template_param_infos.args[i].getIntegralType(),
1264 parameter_pack,
1265 nullptr));
1266
1267 }
1268 else
1269 {
1270 template_param_decls.push_back (TemplateTypeParmDecl::Create (*ast,
1271 ast->getTranslationUnitDecl(), // Is this the right decl context?
1272 SourceLocation(),
1273 SourceLocation(),
1274 depth,
1275 i,
1276 identifier_info,
1277 is_typename,
1278 parameter_pack));
1279 }
1280 }
1281
1282 TemplateParameterList *template_param_list = TemplateParameterList::Create (*ast,
1283 SourceLocation(),
1284 SourceLocation(),
1285 &template_param_decls.front(),
1286 template_param_decls.size(),
1287 SourceLocation());
1288 return template_param_list;
1289 }
1290
1291 clang::FunctionTemplateDecl *
CreateFunctionTemplateDecl(clang::DeclContext * decl_ctx,clang::FunctionDecl * func_decl,const char * name,const TemplateParameterInfos & template_param_infos)1292 ClangASTContext::CreateFunctionTemplateDecl (clang::DeclContext *decl_ctx,
1293 clang::FunctionDecl *func_decl,
1294 const char *name,
1295 const TemplateParameterInfos &template_param_infos)
1296 {
1297 // /// \brief Create a function template node.
1298 ASTContext *ast = getASTContext();
1299
1300 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1301
1302 TemplateParameterList *template_param_list = CreateTemplateParameterList (ast,
1303 template_param_infos,
1304 template_param_decls);
1305 FunctionTemplateDecl *func_tmpl_decl = FunctionTemplateDecl::Create (*ast,
1306 decl_ctx,
1307 func_decl->getLocation(),
1308 func_decl->getDeclName(),
1309 template_param_list,
1310 func_decl);
1311
1312 for (size_t i=0, template_param_decl_count = template_param_decls.size();
1313 i < template_param_decl_count;
1314 ++i)
1315 {
1316 // TODO: verify which decl context we should put template_param_decls into..
1317 template_param_decls[i]->setDeclContext (func_decl);
1318 }
1319
1320 return func_tmpl_decl;
1321 }
1322
1323 void
CreateFunctionTemplateSpecializationInfo(FunctionDecl * func_decl,clang::FunctionTemplateDecl * func_tmpl_decl,const TemplateParameterInfos & infos)1324 ClangASTContext::CreateFunctionTemplateSpecializationInfo (FunctionDecl *func_decl,
1325 clang::FunctionTemplateDecl *func_tmpl_decl,
1326 const TemplateParameterInfos &infos)
1327 {
1328 TemplateArgumentList template_args (TemplateArgumentList::OnStack,
1329 infos.args.data(),
1330 infos.args.size());
1331
1332 func_decl->setFunctionTemplateSpecialization (func_tmpl_decl,
1333 &template_args,
1334 nullptr);
1335 }
1336
1337
1338 ClassTemplateDecl *
CreateClassTemplateDecl(DeclContext * decl_ctx,lldb::AccessType access_type,const char * class_name,int kind,const TemplateParameterInfos & template_param_infos)1339 ClangASTContext::CreateClassTemplateDecl (DeclContext *decl_ctx,
1340 lldb::AccessType access_type,
1341 const char *class_name,
1342 int kind,
1343 const TemplateParameterInfos &template_param_infos)
1344 {
1345 ASTContext *ast = getASTContext();
1346
1347 ClassTemplateDecl *class_template_decl = nullptr;
1348 if (decl_ctx == nullptr)
1349 decl_ctx = ast->getTranslationUnitDecl();
1350
1351 IdentifierInfo &identifier_info = ast->Idents.get(class_name);
1352 DeclarationName decl_name (&identifier_info);
1353
1354 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1355
1356 for (NamedDecl *decl : result)
1357 {
1358 class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1359 if (class_template_decl)
1360 return class_template_decl;
1361 }
1362
1363 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1364
1365 TemplateParameterList *template_param_list = CreateTemplateParameterList (ast,
1366 template_param_infos,
1367 template_param_decls);
1368
1369 CXXRecordDecl *template_cxx_decl = CXXRecordDecl::Create (*ast,
1370 (TagDecl::TagKind)kind,
1371 decl_ctx, // What decl context do we use here? TU? The actual decl context?
1372 SourceLocation(),
1373 SourceLocation(),
1374 &identifier_info);
1375
1376 for (size_t i=0, template_param_decl_count = template_param_decls.size();
1377 i < template_param_decl_count;
1378 ++i)
1379 {
1380 template_param_decls[i]->setDeclContext (template_cxx_decl);
1381 }
1382
1383 // With templated classes, we say that a class is templated with
1384 // specializations, but that the bare class has no functions.
1385 //template_cxx_decl->startDefinition();
1386 //template_cxx_decl->completeDefinition();
1387
1388 class_template_decl = ClassTemplateDecl::Create (*ast,
1389 decl_ctx, // What decl context do we use here? TU? The actual decl context?
1390 SourceLocation(),
1391 decl_name,
1392 template_param_list,
1393 template_cxx_decl,
1394 nullptr);
1395
1396 if (class_template_decl)
1397 {
1398 if (access_type != eAccessNone)
1399 class_template_decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type));
1400
1401 //if (TagDecl *ctx_tag_decl = dyn_cast<TagDecl>(decl_ctx))
1402 // CompleteTagDeclarationDefinition(GetTypeForDecl(ctx_tag_decl));
1403
1404 decl_ctx->addDecl (class_template_decl);
1405
1406 #ifdef LLDB_CONFIGURATION_DEBUG
1407 VerifyDecl(class_template_decl);
1408 #endif
1409 }
1410
1411 return class_template_decl;
1412 }
1413
1414
1415 ClassTemplateSpecializationDecl *
CreateClassTemplateSpecializationDecl(DeclContext * decl_ctx,ClassTemplateDecl * class_template_decl,int kind,const TemplateParameterInfos & template_param_infos)1416 ClangASTContext::CreateClassTemplateSpecializationDecl (DeclContext *decl_ctx,
1417 ClassTemplateDecl *class_template_decl,
1418 int kind,
1419 const TemplateParameterInfos &template_param_infos)
1420 {
1421 ASTContext *ast = getASTContext();
1422 ClassTemplateSpecializationDecl *class_template_specialization_decl = ClassTemplateSpecializationDecl::Create (*ast,
1423 (TagDecl::TagKind)kind,
1424 decl_ctx,
1425 SourceLocation(),
1426 SourceLocation(),
1427 class_template_decl,
1428 &template_param_infos.args.front(),
1429 template_param_infos.args.size(),
1430 nullptr);
1431
1432 class_template_specialization_decl->setSpecializationKind(TSK_ExplicitSpecialization);
1433
1434 return class_template_specialization_decl;
1435 }
1436
1437 ClangASTType
CreateClassTemplateSpecializationType(ClassTemplateSpecializationDecl * class_template_specialization_decl)1438 ClangASTContext::CreateClassTemplateSpecializationType (ClassTemplateSpecializationDecl *class_template_specialization_decl)
1439 {
1440 if (class_template_specialization_decl)
1441 {
1442 ASTContext *ast = getASTContext();
1443 if (ast)
1444 return ClangASTType(ast, ast->getTagDeclType(class_template_specialization_decl).getAsOpaquePtr());
1445 }
1446 return ClangASTType();
1447 }
1448
1449 static inline bool
check_op_param(uint32_t op_kind,bool unary,bool binary,uint32_t num_params)1450 check_op_param (uint32_t op_kind, bool unary, bool binary, uint32_t num_params)
1451 {
1452 // Special-case call since it can take any number of operands
1453 if(op_kind == OO_Call)
1454 return true;
1455
1456 // The parameter count doesn't include "this"
1457 if (num_params == 0)
1458 return unary;
1459 if (num_params == 1)
1460 return binary;
1461 else
1462 return false;
1463 }
1464
1465 bool
CheckOverloadedOperatorKindParameterCount(uint32_t op_kind,uint32_t num_params)1466 ClangASTContext::CheckOverloadedOperatorKindParameterCount (uint32_t op_kind, uint32_t num_params)
1467 {
1468 switch (op_kind)
1469 {
1470 default:
1471 break;
1472 // C++ standard allows any number of arguments to new/delete
1473 case OO_New:
1474 case OO_Array_New:
1475 case OO_Delete:
1476 case OO_Array_Delete:
1477 return true;
1478 }
1479
1480 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) case OO_##Name: return check_op_param (op_kind, Unary, Binary, num_params);
1481 switch (op_kind)
1482 {
1483 #include "clang/Basic/OperatorKinds.def"
1484 default: break;
1485 }
1486 return false;
1487 }
1488
1489 clang::AccessSpecifier
UnifyAccessSpecifiers(clang::AccessSpecifier lhs,clang::AccessSpecifier rhs)1490 ClangASTContext::UnifyAccessSpecifiers (clang::AccessSpecifier lhs, clang::AccessSpecifier rhs)
1491 {
1492 clang::AccessSpecifier ret = lhs;
1493
1494 // Make the access equal to the stricter of the field and the nested field's access
1495 switch (ret)
1496 {
1497 case clang::AS_none:
1498 break;
1499 case clang::AS_private:
1500 break;
1501 case clang::AS_protected:
1502 if (rhs == AS_private)
1503 ret = AS_private;
1504 break;
1505 case clang::AS_public:
1506 ret = rhs;
1507 break;
1508 }
1509
1510 return ret;
1511 }
1512
1513 bool
FieldIsBitfield(FieldDecl * field,uint32_t & bitfield_bit_size)1514 ClangASTContext::FieldIsBitfield (FieldDecl* field, uint32_t& bitfield_bit_size)
1515 {
1516 return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
1517 }
1518
1519 bool
FieldIsBitfield(ASTContext * ast,FieldDecl * field,uint32_t & bitfield_bit_size)1520 ClangASTContext::FieldIsBitfield
1521 (
1522 ASTContext *ast,
1523 FieldDecl* field,
1524 uint32_t& bitfield_bit_size
1525 )
1526 {
1527 if (ast == nullptr || field == nullptr)
1528 return false;
1529
1530 if (field->isBitField())
1531 {
1532 Expr* bit_width_expr = field->getBitWidth();
1533 if (bit_width_expr)
1534 {
1535 llvm::APSInt bit_width_apsint;
1536 if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast))
1537 {
1538 bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
1539 return true;
1540 }
1541 }
1542 }
1543 return false;
1544 }
1545
1546 bool
RecordHasFields(const RecordDecl * record_decl)1547 ClangASTContext::RecordHasFields (const RecordDecl *record_decl)
1548 {
1549 if (record_decl == nullptr)
1550 return false;
1551
1552 if (!record_decl->field_empty())
1553 return true;
1554
1555 // No fields, lets check this is a CXX record and check the base classes
1556 const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1557 if (cxx_record_decl)
1558 {
1559 CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1560 for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1561 base_class != base_class_end;
1562 ++base_class)
1563 {
1564 const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1565 if (RecordHasFields(base_class_decl))
1566 return true;
1567 }
1568 }
1569 return false;
1570 }
1571
1572 #pragma mark Objective C Classes
1573
1574 ClangASTType
CreateObjCClass(const char * name,DeclContext * decl_ctx,bool isForwardDecl,bool isInternal,ClangASTMetadata * metadata)1575 ClangASTContext::CreateObjCClass
1576 (
1577 const char *name,
1578 DeclContext *decl_ctx,
1579 bool isForwardDecl,
1580 bool isInternal,
1581 ClangASTMetadata *metadata
1582 )
1583 {
1584 ASTContext *ast = getASTContext();
1585 assert (ast != nullptr);
1586 assert (name && name[0]);
1587 if (decl_ctx == nullptr)
1588 decl_ctx = ast->getTranslationUnitDecl();
1589
1590 ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create (*ast,
1591 decl_ctx,
1592 SourceLocation(),
1593 &ast->Idents.get(name),
1594 nullptr,
1595 nullptr,
1596 SourceLocation(),
1597 /*isForwardDecl,*/
1598 isInternal);
1599
1600 if (decl && metadata)
1601 SetMetadata(ast, decl, *metadata);
1602
1603 return ClangASTType (ast, ast->getObjCInterfaceType(decl));
1604 }
1605
1606 static inline bool
BaseSpecifierIsEmpty(const CXXBaseSpecifier * b)1607 BaseSpecifierIsEmpty (const CXXBaseSpecifier *b)
1608 {
1609 return ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl()) == false;
1610 }
1611
1612 uint32_t
GetNumBaseClasses(const CXXRecordDecl * cxx_record_decl,bool omit_empty_base_classes)1613 ClangASTContext::GetNumBaseClasses (const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes)
1614 {
1615 uint32_t num_bases = 0;
1616 if (cxx_record_decl)
1617 {
1618 if (omit_empty_base_classes)
1619 {
1620 CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1621 for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1622 base_class != base_class_end;
1623 ++base_class)
1624 {
1625 // Skip empty base classes
1626 if (omit_empty_base_classes)
1627 {
1628 if (BaseSpecifierIsEmpty (base_class))
1629 continue;
1630 }
1631 ++num_bases;
1632 }
1633 }
1634 else
1635 num_bases = cxx_record_decl->getNumBases();
1636 }
1637 return num_bases;
1638 }
1639
1640
1641 #pragma mark Namespace Declarations
1642
1643 NamespaceDecl *
GetUniqueNamespaceDeclaration(const char * name,DeclContext * decl_ctx)1644 ClangASTContext::GetUniqueNamespaceDeclaration (const char *name, DeclContext *decl_ctx)
1645 {
1646 NamespaceDecl *namespace_decl = nullptr;
1647 ASTContext *ast = getASTContext();
1648 TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl ();
1649 if (decl_ctx == nullptr)
1650 decl_ctx = translation_unit_decl;
1651
1652 if (name)
1653 {
1654 IdentifierInfo &identifier_info = ast->Idents.get(name);
1655 DeclarationName decl_name (&identifier_info);
1656 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1657 for (NamedDecl *decl : result)
1658 {
1659 namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
1660 if (namespace_decl)
1661 return namespace_decl;
1662 }
1663
1664 namespace_decl = NamespaceDecl::Create(*ast,
1665 decl_ctx,
1666 false,
1667 SourceLocation(),
1668 SourceLocation(),
1669 &identifier_info,
1670 nullptr);
1671
1672 decl_ctx->addDecl (namespace_decl);
1673 }
1674 else
1675 {
1676 if (decl_ctx == translation_unit_decl)
1677 {
1678 namespace_decl = translation_unit_decl->getAnonymousNamespace();
1679 if (namespace_decl)
1680 return namespace_decl;
1681
1682 namespace_decl = NamespaceDecl::Create(*ast,
1683 decl_ctx,
1684 false,
1685 SourceLocation(),
1686 SourceLocation(),
1687 nullptr,
1688 nullptr);
1689 translation_unit_decl->setAnonymousNamespace (namespace_decl);
1690 translation_unit_decl->addDecl (namespace_decl);
1691 assert (namespace_decl == translation_unit_decl->getAnonymousNamespace());
1692 }
1693 else
1694 {
1695 NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
1696 if (parent_namespace_decl)
1697 {
1698 namespace_decl = parent_namespace_decl->getAnonymousNamespace();
1699 if (namespace_decl)
1700 return namespace_decl;
1701 namespace_decl = NamespaceDecl::Create(*ast,
1702 decl_ctx,
1703 false,
1704 SourceLocation(),
1705 SourceLocation(),
1706 nullptr,
1707 nullptr);
1708 parent_namespace_decl->setAnonymousNamespace (namespace_decl);
1709 parent_namespace_decl->addDecl (namespace_decl);
1710 assert (namespace_decl == parent_namespace_decl->getAnonymousNamespace());
1711 }
1712 else
1713 {
1714 // BAD!!!
1715 }
1716 }
1717
1718
1719 if (namespace_decl)
1720 {
1721 // If we make it here, we are creating the anonymous namespace decl
1722 // for the first time, so we need to do the using directive magic
1723 // like SEMA does
1724 UsingDirectiveDecl* using_directive_decl = UsingDirectiveDecl::Create (*ast,
1725 decl_ctx,
1726 SourceLocation(),
1727 SourceLocation(),
1728 NestedNameSpecifierLoc(),
1729 SourceLocation(),
1730 namespace_decl,
1731 decl_ctx);
1732 using_directive_decl->setImplicit();
1733 decl_ctx->addDecl(using_directive_decl);
1734 }
1735 }
1736 #ifdef LLDB_CONFIGURATION_DEBUG
1737 VerifyDecl(namespace_decl);
1738 #endif
1739 return namespace_decl;
1740 }
1741
1742
1743 #pragma mark Function Types
1744
1745 FunctionDecl *
CreateFunctionDeclaration(DeclContext * decl_ctx,const char * name,const ClangASTType & function_clang_type,int storage,bool is_inline)1746 ClangASTContext::CreateFunctionDeclaration (DeclContext *decl_ctx,
1747 const char *name,
1748 const ClangASTType &function_clang_type,
1749 int storage,
1750 bool is_inline)
1751 {
1752 FunctionDecl *func_decl = nullptr;
1753 ASTContext *ast = getASTContext();
1754 if (decl_ctx == nullptr)
1755 decl_ctx = ast->getTranslationUnitDecl();
1756
1757
1758 const bool hasWrittenPrototype = true;
1759 const bool isConstexprSpecified = false;
1760
1761 if (name && name[0])
1762 {
1763 func_decl = FunctionDecl::Create (*ast,
1764 decl_ctx,
1765 SourceLocation(),
1766 SourceLocation(),
1767 DeclarationName (&ast->Idents.get(name)),
1768 function_clang_type.GetQualType(),
1769 nullptr,
1770 (clang::StorageClass)storage,
1771 is_inline,
1772 hasWrittenPrototype,
1773 isConstexprSpecified);
1774 }
1775 else
1776 {
1777 func_decl = FunctionDecl::Create (*ast,
1778 decl_ctx,
1779 SourceLocation(),
1780 SourceLocation(),
1781 DeclarationName (),
1782 function_clang_type.GetQualType(),
1783 nullptr,
1784 (clang::StorageClass)storage,
1785 is_inline,
1786 hasWrittenPrototype,
1787 isConstexprSpecified);
1788 }
1789 if (func_decl)
1790 decl_ctx->addDecl (func_decl);
1791
1792 #ifdef LLDB_CONFIGURATION_DEBUG
1793 VerifyDecl(func_decl);
1794 #endif
1795
1796 return func_decl;
1797 }
1798
1799 ClangASTType
CreateFunctionType(ASTContext * ast,const ClangASTType & result_type,const ClangASTType * args,unsigned num_args,bool is_variadic,unsigned type_quals)1800 ClangASTContext::CreateFunctionType (ASTContext *ast,
1801 const ClangASTType& result_type,
1802 const ClangASTType *args,
1803 unsigned num_args,
1804 bool is_variadic,
1805 unsigned type_quals)
1806 {
1807 assert (ast != nullptr);
1808 std::vector<QualType> qual_type_args;
1809 for (unsigned i=0; i<num_args; ++i)
1810 qual_type_args.push_back (args[i].GetQualType());
1811
1812 // TODO: Detect calling convention in DWARF?
1813 FunctionProtoType::ExtProtoInfo proto_info;
1814 proto_info.Variadic = is_variadic;
1815 proto_info.ExceptionSpec = EST_None;
1816 proto_info.TypeQuals = type_quals;
1817 proto_info.RefQualifier = RQ_None;
1818
1819 return ClangASTType (ast, ast->getFunctionType (result_type.GetQualType(),
1820 qual_type_args,
1821 proto_info).getAsOpaquePtr());
1822 }
1823
1824 ParmVarDecl *
CreateParameterDeclaration(const char * name,const ClangASTType & param_type,int storage)1825 ClangASTContext::CreateParameterDeclaration (const char *name, const ClangASTType ¶m_type, int storage)
1826 {
1827 ASTContext *ast = getASTContext();
1828 assert (ast != nullptr);
1829 return ParmVarDecl::Create(*ast,
1830 ast->getTranslationUnitDecl(),
1831 SourceLocation(),
1832 SourceLocation(),
1833 name && name[0] ? &ast->Idents.get(name) : nullptr,
1834 param_type.GetQualType(),
1835 nullptr,
1836 (clang::StorageClass)storage,
1837 nullptr);
1838 }
1839
1840 void
SetFunctionParameters(FunctionDecl * function_decl,ParmVarDecl ** params,unsigned num_params)1841 ClangASTContext::SetFunctionParameters (FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params)
1842 {
1843 if (function_decl)
1844 function_decl->setParams (ArrayRef<ParmVarDecl*>(params, num_params));
1845 }
1846
1847
1848 #pragma mark Array Types
1849
1850 ClangASTType
CreateArrayType(const ClangASTType & element_type,size_t element_count,bool is_vector)1851 ClangASTContext::CreateArrayType (const ClangASTType &element_type,
1852 size_t element_count,
1853 bool is_vector)
1854 {
1855 if (element_type.IsValid())
1856 {
1857 ASTContext *ast = getASTContext();
1858 assert (ast != nullptr);
1859
1860 if (is_vector)
1861 {
1862 return ClangASTType (ast, ast->getExtVectorType(element_type.GetQualType(), element_count).getAsOpaquePtr());
1863 }
1864 else
1865 {
1866
1867 llvm::APInt ap_element_count (64, element_count);
1868 if (element_count == 0)
1869 {
1870 return ClangASTType (ast, ast->getIncompleteArrayType (element_type.GetQualType(),
1871 ArrayType::Normal,
1872 0).getAsOpaquePtr());
1873 }
1874 else
1875 {
1876 return ClangASTType (ast, ast->getConstantArrayType (element_type.GetQualType(),
1877 ap_element_count,
1878 ArrayType::Normal,
1879 0).getAsOpaquePtr());
1880 }
1881 }
1882 }
1883 return ClangASTType();
1884 }
1885
1886 ClangASTType
GetOrCreateStructForIdentifier(const ConstString & type_name,const std::initializer_list<std::pair<const char *,ClangASTType>> & type_fields,bool packed)1887 ClangASTContext::GetOrCreateStructForIdentifier (const ConstString &type_name,
1888 const std::initializer_list< std::pair < const char *, ClangASTType > >& type_fields,
1889 bool packed)
1890 {
1891 ClangASTType type;
1892 if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid())
1893 return type;
1894 type = CreateRecordType(nullptr, lldb::eAccessPublic, type_name.GetCString(), clang::TTK_Struct, lldb::eLanguageTypeC);
1895 type.StartTagDeclarationDefinition();
1896 for (const auto& field : type_fields)
1897 type.AddFieldToRecordType(field.first, field.second, lldb::eAccessPublic, 0);
1898 if (packed)
1899 type.SetIsPacked();
1900 type.CompleteTagDeclarationDefinition();
1901 return type;
1902 }
1903
1904 #pragma mark Enumeration Types
1905
1906 ClangASTType
CreateEnumerationType(const char * name,DeclContext * decl_ctx,const Declaration & decl,const ClangASTType & integer_clang_type)1907 ClangASTContext::CreateEnumerationType
1908 (
1909 const char *name,
1910 DeclContext *decl_ctx,
1911 const Declaration &decl,
1912 const ClangASTType &integer_clang_type
1913 )
1914 {
1915 // TODO: Do something intelligent with the Declaration object passed in
1916 // like maybe filling in the SourceLocation with it...
1917 ASTContext *ast = getASTContext();
1918
1919 // TODO: ask about these...
1920 // const bool IsScoped = false;
1921 // const bool IsFixed = false;
1922
1923 EnumDecl *enum_decl = EnumDecl::Create (*ast,
1924 decl_ctx,
1925 SourceLocation(),
1926 SourceLocation(),
1927 name && name[0] ? &ast->Idents.get(name) : nullptr,
1928 nullptr,
1929 false, // IsScoped
1930 false, // IsScopedUsingClassTag
1931 false); // IsFixed
1932
1933
1934 if (enum_decl)
1935 {
1936 // TODO: check if we should be setting the promotion type too?
1937 enum_decl->setIntegerType(integer_clang_type.GetQualType());
1938
1939 enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
1940
1941 return ClangASTType (ast, ast->getTagDeclType(enum_decl).getAsOpaquePtr());
1942 }
1943 return ClangASTType();
1944 }
1945
1946 // Disable this for now since I can't seem to get a nicely formatted float
1947 // out of the APFloat class without just getting the float, double or quad
1948 // and then using a formatted print on it which defeats the purpose. We ideally
1949 // would like to get perfect string values for any kind of float semantics
1950 // so we can support remote targets. The code below also requires a patch to
1951 // llvm::APInt.
1952 //bool
1953 //ClangASTContext::ConvertFloatValueToString (ASTContext *ast, clang_type_t clang_type, const uint8_t* bytes, size_t byte_size, int apint_byte_order, std::string &float_str)
1954 //{
1955 // uint32_t count = 0;
1956 // bool is_complex = false;
1957 // if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
1958 // {
1959 // unsigned num_bytes_per_float = byte_size / count;
1960 // unsigned num_bits_per_float = num_bytes_per_float * 8;
1961 //
1962 // float_str.clear();
1963 // uint32_t i;
1964 // for (i=0; i<count; i++)
1965 // {
1966 // APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float, (APInt::ByteOrder)apint_byte_order);
1967 // bool is_ieee = false;
1968 // APFloat ap_float(ap_int, is_ieee);
1969 // char s[1024];
1970 // unsigned int hex_digits = 0;
1971 // bool upper_case = false;
1972 //
1973 // if (ap_float.convertToHexString(s, hex_digits, upper_case, APFloat::rmNearestTiesToEven) > 0)
1974 // {
1975 // if (i > 0)
1976 // float_str.append(", ");
1977 // float_str.append(s);
1978 // if (i == 1 && is_complex)
1979 // float_str.append(1, 'i');
1980 // }
1981 // }
1982 // return !float_str.empty();
1983 // }
1984 // return false;
1985 //}
1986
1987 ClangASTType
GetIntTypeFromBitSize(clang::ASTContext * ast,size_t bit_size,bool is_signed)1988 ClangASTContext::GetIntTypeFromBitSize (clang::ASTContext *ast,
1989 size_t bit_size, bool is_signed)
1990 {
1991 if (ast)
1992 {
1993 if (is_signed)
1994 {
1995 if (bit_size == ast->getTypeSize(ast->SignedCharTy))
1996 return ClangASTType(ast, ast->SignedCharTy.getAsOpaquePtr());
1997
1998 if (bit_size == ast->getTypeSize(ast->ShortTy))
1999 return ClangASTType(ast, ast->ShortTy.getAsOpaquePtr());
2000
2001 if (bit_size == ast->getTypeSize(ast->IntTy))
2002 return ClangASTType(ast, ast->IntTy.getAsOpaquePtr());
2003
2004 if (bit_size == ast->getTypeSize(ast->LongTy))
2005 return ClangASTType(ast, ast->LongTy.getAsOpaquePtr());
2006
2007 if (bit_size == ast->getTypeSize(ast->LongLongTy))
2008 return ClangASTType(ast, ast->LongLongTy.getAsOpaquePtr());
2009
2010 if (bit_size == ast->getTypeSize(ast->Int128Ty))
2011 return ClangASTType(ast, ast->Int128Ty.getAsOpaquePtr());
2012 }
2013 else
2014 {
2015 if (bit_size == ast->getTypeSize(ast->UnsignedCharTy))
2016 return ClangASTType(ast, ast->UnsignedCharTy.getAsOpaquePtr());
2017
2018 if (bit_size == ast->getTypeSize(ast->UnsignedShortTy))
2019 return ClangASTType(ast, ast->UnsignedShortTy.getAsOpaquePtr());
2020
2021 if (bit_size == ast->getTypeSize(ast->UnsignedIntTy))
2022 return ClangASTType(ast, ast->UnsignedIntTy.getAsOpaquePtr());
2023
2024 if (bit_size == ast->getTypeSize(ast->UnsignedLongTy))
2025 return ClangASTType(ast, ast->UnsignedLongTy.getAsOpaquePtr());
2026
2027 if (bit_size == ast->getTypeSize(ast->UnsignedLongLongTy))
2028 return ClangASTType(ast, ast->UnsignedLongLongTy.getAsOpaquePtr());
2029
2030 if (bit_size == ast->getTypeSize(ast->UnsignedInt128Ty))
2031 return ClangASTType(ast, ast->UnsignedInt128Ty.getAsOpaquePtr());
2032 }
2033 }
2034 return ClangASTType();
2035 }
2036
2037 ClangASTType
GetPointerSizedIntType(clang::ASTContext * ast,bool is_signed)2038 ClangASTContext::GetPointerSizedIntType (clang::ASTContext *ast, bool is_signed)
2039 {
2040 if (ast)
2041 return GetIntTypeFromBitSize(ast, ast->getTypeSize(ast->VoidPtrTy), is_signed);
2042 return ClangASTType();
2043 }
2044
2045 ClangASTType
GetFloatTypeFromBitSize(clang::ASTContext * ast,size_t bit_size)2046 ClangASTContext::GetFloatTypeFromBitSize (clang::ASTContext *ast,
2047 size_t bit_size)
2048 {
2049 if (ast)
2050 {
2051 if (bit_size == ast->getTypeSize(ast->FloatTy))
2052 return ClangASTType(ast, ast->FloatTy.getAsOpaquePtr());
2053 else if (bit_size == ast->getTypeSize(ast->DoubleTy))
2054 return ClangASTType(ast, ast->DoubleTy.getAsOpaquePtr());
2055 else if (bit_size == ast->getTypeSize(ast->LongDoubleTy))
2056 return ClangASTType(ast, ast->LongDoubleTy.getAsOpaquePtr());
2057 else if (bit_size == ast->getTypeSize(ast->HalfTy))
2058 return ClangASTType(ast, ast->HalfTy.getAsOpaquePtr());
2059 }
2060 return ClangASTType();
2061 }
2062
2063 bool
GetCompleteDecl(clang::ASTContext * ast,clang::Decl * decl)2064 ClangASTContext::GetCompleteDecl (clang::ASTContext *ast,
2065 clang::Decl *decl)
2066 {
2067 if (!decl)
2068 return false;
2069
2070 ExternalASTSource *ast_source = ast->getExternalSource();
2071
2072 if (!ast_source)
2073 return false;
2074
2075 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
2076 {
2077 if (tag_decl->isCompleteDefinition())
2078 return true;
2079
2080 if (!tag_decl->hasExternalLexicalStorage())
2081 return false;
2082
2083 ast_source->CompleteType(tag_decl);
2084
2085 return !tag_decl->getTypeForDecl()->isIncompleteType();
2086 }
2087 else if (clang::ObjCInterfaceDecl *objc_interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
2088 {
2089 if (objc_interface_decl->getDefinition())
2090 return true;
2091
2092 if (!objc_interface_decl->hasExternalLexicalStorage())
2093 return false;
2094
2095 ast_source->CompleteType(objc_interface_decl);
2096
2097 return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
2098 }
2099 else
2100 {
2101 return false;
2102 }
2103 }
2104
2105 void
SetMetadataAsUserID(const void * object,user_id_t user_id)2106 ClangASTContext::SetMetadataAsUserID (const void *object,
2107 user_id_t user_id)
2108 {
2109 ClangASTMetadata meta_data;
2110 meta_data.SetUserID (user_id);
2111 SetMetadata (object, meta_data);
2112 }
2113
2114 void
SetMetadata(clang::ASTContext * ast,const void * object,ClangASTMetadata & metadata)2115 ClangASTContext::SetMetadata (clang::ASTContext *ast,
2116 const void *object,
2117 ClangASTMetadata &metadata)
2118 {
2119 ClangExternalASTSourceCommon *external_source =
2120 ClangExternalASTSourceCommon::Lookup(ast->getExternalSource());
2121
2122 if (external_source)
2123 external_source->SetMetadata(object, metadata);
2124 }
2125
2126 ClangASTMetadata *
GetMetadata(clang::ASTContext * ast,const void * object)2127 ClangASTContext::GetMetadata (clang::ASTContext *ast,
2128 const void *object)
2129 {
2130 ClangExternalASTSourceCommon *external_source =
2131 ClangExternalASTSourceCommon::Lookup(ast->getExternalSource());
2132
2133 if (external_source && external_source->HasMetadata(object))
2134 return external_source->GetMetadata(object);
2135 else
2136 return nullptr;
2137 }
2138
2139 clang::DeclContext *
GetAsDeclContext(clang::CXXMethodDecl * cxx_method_decl)2140 ClangASTContext::GetAsDeclContext (clang::CXXMethodDecl *cxx_method_decl)
2141 {
2142 return llvm::dyn_cast<clang::DeclContext>(cxx_method_decl);
2143 }
2144
2145 clang::DeclContext *
GetAsDeclContext(clang::ObjCMethodDecl * objc_method_decl)2146 ClangASTContext::GetAsDeclContext (clang::ObjCMethodDecl *objc_method_decl)
2147 {
2148 return llvm::dyn_cast<clang::DeclContext>(objc_method_decl);
2149 }
2150
2151
2152 bool
GetClassMethodInfoForDeclContext(clang::DeclContext * decl_ctx,lldb::LanguageType & language,bool & is_instance_method,ConstString & language_object_name)2153 ClangASTContext::GetClassMethodInfoForDeclContext (clang::DeclContext *decl_ctx,
2154 lldb::LanguageType &language,
2155 bool &is_instance_method,
2156 ConstString &language_object_name)
2157 {
2158 language_object_name.Clear();
2159 language = eLanguageTypeUnknown;
2160 is_instance_method = false;
2161
2162 if (decl_ctx)
2163 {
2164 if (clang::CXXMethodDecl *method_decl = llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx))
2165 {
2166 if (method_decl->isStatic())
2167 {
2168 is_instance_method = false;
2169 }
2170 else
2171 {
2172 language_object_name.SetCString("this");
2173 is_instance_method = true;
2174 }
2175 language = eLanguageTypeC_plus_plus;
2176 return true;
2177 }
2178 else if (clang::ObjCMethodDecl *method_decl = llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx))
2179 {
2180 // Both static and instance methods have a "self" object in objective C
2181 language_object_name.SetCString("self");
2182 if (method_decl->isInstanceMethod())
2183 {
2184 is_instance_method = true;
2185 }
2186 else
2187 {
2188 is_instance_method = false;
2189 }
2190 language = eLanguageTypeObjC;
2191 return true;
2192 }
2193 else if (clang::FunctionDecl *function_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_ctx))
2194 {
2195 ClangASTMetadata *metadata = GetMetadata (&decl_ctx->getParentASTContext(), function_decl);
2196 if (metadata && metadata->HasObjectPtr())
2197 {
2198 language_object_name.SetCString (metadata->GetObjectPtrName());
2199 language = eLanguageTypeObjC;
2200 is_instance_method = true;
2201 }
2202 return true;
2203 }
2204 }
2205 return false;
2206 }
2207
2208