Fix/unify the spelling of Objective-C.
[lldb.git] / lldb / source / Symbol / ClangASTContext.cpp
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 #include "llvm/Support/FormatAdapters.h"
13 #include "llvm/Support/FormatVariadic.h"
14
15 // C Includes
16 // C++ Includes
17 #include <mutex>
18 #include <string>
19 #include <vector>
20
21 // Other libraries and framework includes
22
23 // Clang headers like to use NDEBUG inside of them to enable/disable debug
24 // related features using "#ifndef NDEBUG" preprocessor blocks to do one thing
25 // or another. This is bad because it means that if clang was built in release
26 // mode, it assumes that you are building in release mode which is not always
27 // the case. You can end up with functions that are defined as empty in header
28 // files when NDEBUG is not defined, and this can cause link errors with the
29 // clang .a files that you have since you might be missing functions in the .a
30 // file. So we have to define NDEBUG when including clang headers to avoid any
31 // mismatches. This is covered by rdar://problem/8691220
32
33 #if !defined(NDEBUG) && !defined(LLVM_NDEBUG_OFF)
34 #define LLDB_DEFINED_NDEBUG_FOR_CLANG
35 #define NDEBUG
36 // Need to include assert.h so it is as clang would expect it to be (disabled)
37 #include <assert.h>
38 #endif
39
40 #include "clang/AST/ASTContext.h"
41 #include "clang/AST/ASTImporter.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/DeclObjC.h"
45 #include "clang/AST/DeclTemplate.h"
46 #include "clang/AST/Mangle.h"
47 #include "clang/AST/RecordLayout.h"
48 #include "clang/AST/Type.h"
49 #include "clang/AST/VTableBuilder.h"
50 #include "clang/Basic/Builtins.h"
51 #include "clang/Basic/Diagnostic.h"
52 #include "clang/Basic/FileManager.h"
53 #include "clang/Basic/FileSystemOptions.h"
54 #include "clang/Basic/SourceManager.h"
55 #include "clang/Basic/TargetInfo.h"
56 #include "clang/Basic/TargetOptions.h"
57 #include "clang/Frontend/FrontendOptions.h"
58 #include "clang/Frontend/LangStandard.h"
59
60 #ifdef LLDB_DEFINED_NDEBUG_FOR_CLANG
61 #undef NDEBUG
62 #undef LLDB_DEFINED_NDEBUG_FOR_CLANG
63 // Need to re-include assert.h so it is as _we_ would expect it to be (enabled)
64 #include <assert.h>
65 #endif
66
67 #include "llvm/Support/Signals.h"
68 #include "llvm/Support/Threading.h"
69
70 #include "Plugins/ExpressionParser/Clang/ClangFunctionCaller.h"
71 #include "Plugins/ExpressionParser/Clang/ClangUserExpression.h"
72 #include "Plugins/ExpressionParser/Clang/ClangUtilityFunction.h"
73 #include "lldb/Utility/ArchSpec.h"
74 #include "lldb/Utility/Flags.h"
75
76 #include "lldb/Core/DumpDataExtractor.h"
77 #include "lldb/Core/Module.h"
78 #include "lldb/Core/PluginManager.h"
79 #include "lldb/Core/Scalar.h"
80 #include "lldb/Core/StreamFile.h"
81 #include "lldb/Core/ThreadSafeDenseMap.h"
82 #include "lldb/Core/UniqueCStringMap.h"
83 #include "lldb/Symbol/ClangASTContext.h"
84 #include "lldb/Symbol/ClangASTImporter.h"
85 #include "lldb/Symbol/ClangExternalASTSourceCallbacks.h"
86 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
87 #include "lldb/Symbol/ClangUtil.h"
88 #include "lldb/Symbol/ObjectFile.h"
89 #include "lldb/Symbol/SymbolFile.h"
90 #include "lldb/Symbol/VerifyDecl.h"
91 #include "lldb/Target/ExecutionContext.h"
92 #include "lldb/Target/Language.h"
93 #include "lldb/Target/ObjCLanguageRuntime.h"
94 #include "lldb/Target/Process.h"
95 #include "lldb/Target/Target.h"
96 #include "lldb/Utility/DataExtractor.h"
97 #include "lldb/Utility/LLDBAssert.h"
98 #include "lldb/Utility/Log.h"
99 #include "lldb/Utility/RegularExpression.h"
100
101 #include "Plugins/SymbolFile/DWARF/DWARFASTParserClang.h"
102 #include "Plugins/SymbolFile/PDB/PDBASTParser.h"
103
104 #include <stdio.h>
105
106 #include <mutex>
107
108 using namespace lldb;
109 using namespace lldb_private;
110 using namespace llvm;
111 using namespace clang;
112
113 namespace {
114 static inline bool
115 ClangASTContextSupportsLanguage(lldb::LanguageType language) {
116   return language == eLanguageTypeUnknown || // Clang is the default type system
117          Language::LanguageIsC(language) ||
118          Language::LanguageIsCPlusPlus(language) ||
119          Language::LanguageIsObjC(language) ||
120          Language::LanguageIsPascal(language) ||
121          // Use Clang for Rust until there is a proper language plugin for it
122          language == eLanguageTypeRust ||
123          language == eLanguageTypeExtRenderScript ||
124          // Use Clang for D until there is a proper language plugin for it
125          language == eLanguageTypeD;
126 }
127 }
128
129 typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, ClangASTContext *>
130     ClangASTMap;
131
132 static ClangASTMap &GetASTMap() {
133   static ClangASTMap *g_map_ptr = nullptr;
134   static llvm::once_flag g_once_flag;
135   llvm::call_once(g_once_flag, []() {
136     g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins
137   });
138   return *g_map_ptr;
139 }
140
141 bool ClangASTContext::IsOperator(const char *name,
142                                  clang::OverloadedOperatorKind &op_kind) {
143   if (name == nullptr || name[0] == '\0')
144     return false;
145
146 #define OPERATOR_PREFIX "operator"
147 #define OPERATOR_PREFIX_LENGTH (sizeof(OPERATOR_PREFIX) - 1)
148
149   const char *post_op_name = nullptr;
150
151   bool no_space = true;
152
153   if (::strncmp(name, OPERATOR_PREFIX, OPERATOR_PREFIX_LENGTH))
154     return false;
155
156   post_op_name = name + OPERATOR_PREFIX_LENGTH;
157
158   if (post_op_name[0] == ' ') {
159     post_op_name++;
160     no_space = false;
161   }
162
163 #undef OPERATOR_PREFIX
164 #undef OPERATOR_PREFIX_LENGTH
165
166   // This is an operator, set the overloaded operator kind to invalid in case
167   // this is a conversion operator...
168   op_kind = clang::NUM_OVERLOADED_OPERATORS;
169
170   switch (post_op_name[0]) {
171   default:
172     if (no_space)
173       return false;
174     break;
175   case 'n':
176     if (no_space)
177       return false;
178     if (strcmp(post_op_name, "new") == 0)
179       op_kind = clang::OO_New;
180     else if (strcmp(post_op_name, "new[]") == 0)
181       op_kind = clang::OO_Array_New;
182     break;
183
184   case 'd':
185     if (no_space)
186       return false;
187     if (strcmp(post_op_name, "delete") == 0)
188       op_kind = clang::OO_Delete;
189     else if (strcmp(post_op_name, "delete[]") == 0)
190       op_kind = clang::OO_Array_Delete;
191     break;
192
193   case '+':
194     if (post_op_name[1] == '\0')
195       op_kind = clang::OO_Plus;
196     else if (post_op_name[2] == '\0') {
197       if (post_op_name[1] == '=')
198         op_kind = clang::OO_PlusEqual;
199       else if (post_op_name[1] == '+')
200         op_kind = clang::OO_PlusPlus;
201     }
202     break;
203
204   case '-':
205     if (post_op_name[1] == '\0')
206       op_kind = clang::OO_Minus;
207     else if (post_op_name[2] == '\0') {
208       switch (post_op_name[1]) {
209       case '=':
210         op_kind = clang::OO_MinusEqual;
211         break;
212       case '-':
213         op_kind = clang::OO_MinusMinus;
214         break;
215       case '>':
216         op_kind = clang::OO_Arrow;
217         break;
218       }
219     } else if (post_op_name[3] == '\0') {
220       if (post_op_name[2] == '*')
221         op_kind = clang::OO_ArrowStar;
222       break;
223     }
224     break;
225
226   case '*':
227     if (post_op_name[1] == '\0')
228       op_kind = clang::OO_Star;
229     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
230       op_kind = clang::OO_StarEqual;
231     break;
232
233   case '/':
234     if (post_op_name[1] == '\0')
235       op_kind = clang::OO_Slash;
236     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
237       op_kind = clang::OO_SlashEqual;
238     break;
239
240   case '%':
241     if (post_op_name[1] == '\0')
242       op_kind = clang::OO_Percent;
243     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
244       op_kind = clang::OO_PercentEqual;
245     break;
246
247   case '^':
248     if (post_op_name[1] == '\0')
249       op_kind = clang::OO_Caret;
250     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
251       op_kind = clang::OO_CaretEqual;
252     break;
253
254   case '&':
255     if (post_op_name[1] == '\0')
256       op_kind = clang::OO_Amp;
257     else if (post_op_name[2] == '\0') {
258       switch (post_op_name[1]) {
259       case '=':
260         op_kind = clang::OO_AmpEqual;
261         break;
262       case '&':
263         op_kind = clang::OO_AmpAmp;
264         break;
265       }
266     }
267     break;
268
269   case '|':
270     if (post_op_name[1] == '\0')
271       op_kind = clang::OO_Pipe;
272     else if (post_op_name[2] == '\0') {
273       switch (post_op_name[1]) {
274       case '=':
275         op_kind = clang::OO_PipeEqual;
276         break;
277       case '|':
278         op_kind = clang::OO_PipePipe;
279         break;
280       }
281     }
282     break;
283
284   case '~':
285     if (post_op_name[1] == '\0')
286       op_kind = clang::OO_Tilde;
287     break;
288
289   case '!':
290     if (post_op_name[1] == '\0')
291       op_kind = clang::OO_Exclaim;
292     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
293       op_kind = clang::OO_ExclaimEqual;
294     break;
295
296   case '=':
297     if (post_op_name[1] == '\0')
298       op_kind = clang::OO_Equal;
299     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
300       op_kind = clang::OO_EqualEqual;
301     break;
302
303   case '<':
304     if (post_op_name[1] == '\0')
305       op_kind = clang::OO_Less;
306     else if (post_op_name[2] == '\0') {
307       switch (post_op_name[1]) {
308       case '<':
309         op_kind = clang::OO_LessLess;
310         break;
311       case '=':
312         op_kind = clang::OO_LessEqual;
313         break;
314       }
315     } else if (post_op_name[3] == '\0') {
316       if (post_op_name[2] == '=')
317         op_kind = clang::OO_LessLessEqual;
318     }
319     break;
320
321   case '>':
322     if (post_op_name[1] == '\0')
323       op_kind = clang::OO_Greater;
324     else if (post_op_name[2] == '\0') {
325       switch (post_op_name[1]) {
326       case '>':
327         op_kind = clang::OO_GreaterGreater;
328         break;
329       case '=':
330         op_kind = clang::OO_GreaterEqual;
331         break;
332       }
333     } else if (post_op_name[1] == '>' && post_op_name[2] == '=' &&
334                post_op_name[3] == '\0') {
335       op_kind = clang::OO_GreaterGreaterEqual;
336     }
337     break;
338
339   case ',':
340     if (post_op_name[1] == '\0')
341       op_kind = clang::OO_Comma;
342     break;
343
344   case '(':
345     if (post_op_name[1] == ')' && post_op_name[2] == '\0')
346       op_kind = clang::OO_Call;
347     break;
348
349   case '[':
350     if (post_op_name[1] == ']' && post_op_name[2] == '\0')
351       op_kind = clang::OO_Subscript;
352     break;
353   }
354
355   return true;
356 }
357
358 clang::AccessSpecifier
359 ClangASTContext::ConvertAccessTypeToAccessSpecifier(AccessType access) {
360   switch (access) {
361   default:
362     break;
363   case eAccessNone:
364     return AS_none;
365   case eAccessPublic:
366     return AS_public;
367   case eAccessPrivate:
368     return AS_private;
369   case eAccessProtected:
370     return AS_protected;
371   }
372   return AS_none;
373 }
374
375 static void ParseLangArgs(LangOptions &Opts, InputKind IK, const char *triple) {
376   // FIXME: Cleanup per-file based stuff.
377
378   // Set some properties which depend solely on the input kind; it would be
379   // nice to move these to the language standard, and have the driver resolve
380   // the input kind + language standard.
381   if (IK.getLanguage() == InputKind::Asm) {
382     Opts.AsmPreprocessor = 1;
383   } else if (IK.isObjectiveC()) {
384     Opts.ObjC1 = Opts.ObjC2 = 1;
385   }
386
387   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
388
389   if (LangStd == LangStandard::lang_unspecified) {
390     // Based on the base language, pick one.
391     switch (IK.getLanguage()) {
392     case InputKind::Unknown:
393     case InputKind::LLVM_IR:
394     case InputKind::RenderScript:
395       llvm_unreachable("Invalid input kind!");
396     case InputKind::OpenCL:
397       LangStd = LangStandard::lang_opencl10;
398       break;
399     case InputKind::CUDA:
400       LangStd = LangStandard::lang_cuda;
401       break;
402     case InputKind::Asm:
403     case InputKind::C:
404     case InputKind::ObjC:
405       LangStd = LangStandard::lang_gnu99;
406       break;
407     case InputKind::CXX:
408     case InputKind::ObjCXX:
409       LangStd = LangStandard::lang_gnucxx98;
410       break;
411     case InputKind::HIP:
412       LangStd = LangStandard::lang_hip;
413       break;
414     }
415   }
416
417   const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
418   Opts.LineComment = Std.hasLineComments();
419   Opts.C99 = Std.isC99();
420   Opts.CPlusPlus = Std.isCPlusPlus();
421   Opts.CPlusPlus11 = Std.isCPlusPlus11();
422   Opts.Digraphs = Std.hasDigraphs();
423   Opts.GNUMode = Std.isGNUMode();
424   Opts.GNUInline = !Std.isC99();
425   Opts.HexFloats = Std.hasHexFloats();
426   Opts.ImplicitInt = Std.hasImplicitInt();
427
428   Opts.WChar = true;
429
430   // OpenCL has some additional defaults.
431   if (LangStd == LangStandard::lang_opencl10) {
432     Opts.OpenCL = 1;
433     Opts.AltiVec = 1;
434     Opts.CXXOperatorNames = 1;
435     Opts.LaxVectorConversions = 1;
436   }
437
438   // OpenCL and C++ both have bool, true, false keywords.
439   Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
440
441   Opts.setValueVisibilityMode(DefaultVisibility);
442
443   // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs is
444   // specified, or -std is set to a conforming mode.
445   Opts.Trigraphs = !Opts.GNUMode;
446   Opts.CharIsSigned = ArchSpec(triple).CharIsSignedByDefault();
447   Opts.OptimizeSize = 0;
448
449   // FIXME: Eliminate this dependency.
450   //    unsigned Opt =
451   //    Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
452   //    Opts.Optimize = Opt != 0;
453   unsigned Opt = 0;
454
455   // This is the __NO_INLINE__ define, which just depends on things like the
456   // optimization level and -fno-inline, not actually whether the backend has
457   // inlining enabled.
458   //
459   // FIXME: This is affected by other options (-fno-inline).
460   Opts.NoInlineDefine = !Opt;
461 }
462
463 ClangASTContext::ClangASTContext(const char *target_triple)
464     : TypeSystem(TypeSystem::eKindClang), m_target_triple(), m_ast_ap(),
465       m_language_options_ap(), m_source_manager_ap(), m_diagnostics_engine_ap(),
466       m_target_options_rp(), m_target_info_ap(), m_identifier_table_ap(),
467       m_selector_table_ap(), m_builtins_ap(), m_callback_tag_decl(nullptr),
468       m_callback_objc_decl(nullptr), m_callback_baton(nullptr),
469       m_pointer_byte_size(0), m_ast_owned(false) {
470   if (target_triple && target_triple[0])
471     SetTargetTriple(target_triple);
472 }
473
474 //----------------------------------------------------------------------
475 // Destructor
476 //----------------------------------------------------------------------
477 ClangASTContext::~ClangASTContext() { Finalize(); }
478
479 ConstString ClangASTContext::GetPluginNameStatic() {
480   return ConstString("clang");
481 }
482
483 ConstString ClangASTContext::GetPluginName() {
484   return ClangASTContext::GetPluginNameStatic();
485 }
486
487 uint32_t ClangASTContext::GetPluginVersion() { return 1; }
488
489 lldb::TypeSystemSP ClangASTContext::CreateInstance(lldb::LanguageType language,
490                                                    lldb_private::Module *module,
491                                                    Target *target) {
492   if (ClangASTContextSupportsLanguage(language)) {
493     ArchSpec arch;
494     if (module)
495       arch = module->GetArchitecture();
496     else if (target)
497       arch = target->GetArchitecture();
498
499     if (arch.IsValid()) {
500       ArchSpec fixed_arch = arch;
501       // LLVM wants this to be set to iOS or MacOSX; if we're working on
502       // a bare-boards type image, change the triple for llvm's benefit.
503       if (fixed_arch.GetTriple().getVendor() == llvm::Triple::Apple &&
504           fixed_arch.GetTriple().getOS() == llvm::Triple::UnknownOS) {
505         if (fixed_arch.GetTriple().getArch() == llvm::Triple::arm ||
506             fixed_arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
507             fixed_arch.GetTriple().getArch() == llvm::Triple::thumb) {
508           fixed_arch.GetTriple().setOS(llvm::Triple::IOS);
509         } else {
510           fixed_arch.GetTriple().setOS(llvm::Triple::MacOSX);
511         }
512       }
513
514       if (module) {
515         std::shared_ptr<ClangASTContext> ast_sp(new ClangASTContext);
516         if (ast_sp) {
517           ast_sp->SetArchitecture(fixed_arch);
518         }
519         return ast_sp;
520       } else if (target && target->IsValid()) {
521         std::shared_ptr<ClangASTContextForExpressions> ast_sp(
522             new ClangASTContextForExpressions(*target));
523         if (ast_sp) {
524           ast_sp->SetArchitecture(fixed_arch);
525           ast_sp->m_scratch_ast_source_ap.reset(
526               new ClangASTSource(target->shared_from_this()));
527           lldbassert(ast_sp->getFileManager());
528           ast_sp->m_scratch_ast_source_ap->InstallASTContext(
529               *ast_sp->getASTContext(), *ast_sp->getFileManager(), true);
530           llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
531               ast_sp->m_scratch_ast_source_ap->CreateProxy());
532           ast_sp->SetExternalSource(proxy_ast_source);
533           return ast_sp;
534         }
535       }
536     }
537   }
538   return lldb::TypeSystemSP();
539 }
540
541 void ClangASTContext::EnumerateSupportedLanguages(
542     std::set<lldb::LanguageType> &languages_for_types,
543     std::set<lldb::LanguageType> &languages_for_expressions) {
544   static std::vector<lldb::LanguageType> s_supported_languages_for_types(
545       {lldb::eLanguageTypeC89, lldb::eLanguageTypeC, lldb::eLanguageTypeC11,
546        lldb::eLanguageTypeC_plus_plus, lldb::eLanguageTypeC99,
547        lldb::eLanguageTypeObjC, lldb::eLanguageTypeObjC_plus_plus,
548        lldb::eLanguageTypeC_plus_plus_03, lldb::eLanguageTypeC_plus_plus_11,
549        lldb::eLanguageTypeC11, lldb::eLanguageTypeC_plus_plus_14});
550
551   static std::vector<lldb::LanguageType> s_supported_languages_for_expressions(
552       {lldb::eLanguageTypeC_plus_plus, lldb::eLanguageTypeObjC_plus_plus,
553        lldb::eLanguageTypeC_plus_plus_03, lldb::eLanguageTypeC_plus_plus_11,
554        lldb::eLanguageTypeC_plus_plus_14});
555
556   languages_for_types.insert(s_supported_languages_for_types.begin(),
557                              s_supported_languages_for_types.end());
558   languages_for_expressions.insert(
559       s_supported_languages_for_expressions.begin(),
560       s_supported_languages_for_expressions.end());
561 }
562
563 void ClangASTContext::Initialize() {
564   PluginManager::RegisterPlugin(GetPluginNameStatic(),
565                                 "clang base AST context plug-in",
566                                 CreateInstance, EnumerateSupportedLanguages);
567 }
568
569 void ClangASTContext::Terminate() {
570   PluginManager::UnregisterPlugin(CreateInstance);
571 }
572
573 void ClangASTContext::Finalize() {
574   if (m_ast_ap.get()) {
575     GetASTMap().Erase(m_ast_ap.get());
576     if (!m_ast_owned)
577       m_ast_ap.release();
578   }
579
580   m_builtins_ap.reset();
581   m_selector_table_ap.reset();
582   m_identifier_table_ap.reset();
583   m_target_info_ap.reset();
584   m_target_options_rp.reset();
585   m_diagnostics_engine_ap.reset();
586   m_source_manager_ap.reset();
587   m_language_options_ap.reset();
588   m_ast_ap.reset();
589   m_scratch_ast_source_ap.reset();
590 }
591
592 void ClangASTContext::Clear() {
593   m_ast_ap.reset();
594   m_language_options_ap.reset();
595   m_source_manager_ap.reset();
596   m_diagnostics_engine_ap.reset();
597   m_target_options_rp.reset();
598   m_target_info_ap.reset();
599   m_identifier_table_ap.reset();
600   m_selector_table_ap.reset();
601   m_builtins_ap.reset();
602   m_pointer_byte_size = 0;
603 }
604
605 const char *ClangASTContext::GetTargetTriple() {
606   return m_target_triple.c_str();
607 }
608
609 void ClangASTContext::SetTargetTriple(const char *target_triple) {
610   Clear();
611   m_target_triple.assign(target_triple);
612 }
613
614 void ClangASTContext::SetArchitecture(const ArchSpec &arch) {
615   SetTargetTriple(arch.GetTriple().str().c_str());
616 }
617
618 bool ClangASTContext::HasExternalSource() {
619   ASTContext *ast = getASTContext();
620   if (ast)
621     return ast->getExternalSource() != nullptr;
622   return false;
623 }
624
625 void ClangASTContext::SetExternalSource(
626     llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_ap) {
627   ASTContext *ast = getASTContext();
628   if (ast) {
629     ast->setExternalSource(ast_source_ap);
630     ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
631     // ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(true);
632   }
633 }
634
635 void ClangASTContext::RemoveExternalSource() {
636   ASTContext *ast = getASTContext();
637
638   if (ast) {
639     llvm::IntrusiveRefCntPtr<ExternalASTSource> empty_ast_source_ap;
640     ast->setExternalSource(empty_ast_source_ap);
641     ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(false);
642     // ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(false);
643   }
644 }
645
646 void ClangASTContext::setASTContext(clang::ASTContext *ast_ctx) {
647   if (!m_ast_owned) {
648     m_ast_ap.release();
649   }
650   m_ast_owned = false;
651   m_ast_ap.reset(ast_ctx);
652   GetASTMap().Insert(ast_ctx, this);
653 }
654
655 ASTContext *ClangASTContext::getASTContext() {
656   if (m_ast_ap.get() == nullptr) {
657     m_ast_owned = true;
658     m_ast_ap.reset(new ASTContext(*getLanguageOptions(), *getSourceManager(),
659                                   *getIdentifierTable(), *getSelectorTable(),
660                                   *getBuiltinContext()));
661
662     m_ast_ap->getDiagnostics().setClient(getDiagnosticConsumer(), false);
663
664     // This can be NULL if we don't know anything about the architecture or if
665     // the target for an architecture isn't enabled in the llvm/clang that we
666     // built
667     TargetInfo *target_info = getTargetInfo();
668     if (target_info)
669       m_ast_ap->InitBuiltinTypes(*target_info);
670
671     if ((m_callback_tag_decl || m_callback_objc_decl) && m_callback_baton) {
672       m_ast_ap->getTranslationUnitDecl()->setHasExternalLexicalStorage();
673       // m_ast_ap->getTranslationUnitDecl()->setHasExternalVisibleStorage();
674     }
675
676     GetASTMap().Insert(m_ast_ap.get(), this);
677
678     llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_ap(
679         new ClangExternalASTSourceCallbacks(
680             ClangASTContext::CompleteTagDecl,
681             ClangASTContext::CompleteObjCInterfaceDecl, nullptr,
682             ClangASTContext::LayoutRecordType, this));
683     SetExternalSource(ast_source_ap);
684   }
685   return m_ast_ap.get();
686 }
687
688 ClangASTContext *ClangASTContext::GetASTContext(clang::ASTContext *ast) {
689   ClangASTContext *clang_ast = GetASTMap().Lookup(ast);
690   return clang_ast;
691 }
692
693 Builtin::Context *ClangASTContext::getBuiltinContext() {
694   if (m_builtins_ap.get() == nullptr)
695     m_builtins_ap.reset(new Builtin::Context());
696   return m_builtins_ap.get();
697 }
698
699 IdentifierTable *ClangASTContext::getIdentifierTable() {
700   if (m_identifier_table_ap.get() == nullptr)
701     m_identifier_table_ap.reset(
702         new IdentifierTable(*ClangASTContext::getLanguageOptions(), nullptr));
703   return m_identifier_table_ap.get();
704 }
705
706 LangOptions *ClangASTContext::getLanguageOptions() {
707   if (m_language_options_ap.get() == nullptr) {
708     m_language_options_ap.reset(new LangOptions());
709     ParseLangArgs(*m_language_options_ap, InputKind::ObjCXX, GetTargetTriple());
710     //        InitializeLangOptions(*m_language_options_ap, InputKind::ObjCXX);
711   }
712   return m_language_options_ap.get();
713 }
714
715 SelectorTable *ClangASTContext::getSelectorTable() {
716   if (m_selector_table_ap.get() == nullptr)
717     m_selector_table_ap.reset(new SelectorTable());
718   return m_selector_table_ap.get();
719 }
720
721 clang::FileManager *ClangASTContext::getFileManager() {
722   if (m_file_manager_ap.get() == nullptr) {
723     clang::FileSystemOptions file_system_options;
724     m_file_manager_ap.reset(new clang::FileManager(file_system_options));
725   }
726   return m_file_manager_ap.get();
727 }
728
729 clang::SourceManager *ClangASTContext::getSourceManager() {
730   if (m_source_manager_ap.get() == nullptr)
731     m_source_manager_ap.reset(
732         new clang::SourceManager(*getDiagnosticsEngine(), *getFileManager()));
733   return m_source_manager_ap.get();
734 }
735
736 clang::DiagnosticsEngine *ClangASTContext::getDiagnosticsEngine() {
737   if (m_diagnostics_engine_ap.get() == nullptr) {
738     llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
739     m_diagnostics_engine_ap.reset(
740         new DiagnosticsEngine(diag_id_sp, new DiagnosticOptions()));
741   }
742   return m_diagnostics_engine_ap.get();
743 }
744
745 clang::MangleContext *ClangASTContext::getMangleContext() {
746   if (m_mangle_ctx_ap.get() == nullptr)
747     m_mangle_ctx_ap.reset(getASTContext()->createMangleContext());
748   return m_mangle_ctx_ap.get();
749 }
750
751 class NullDiagnosticConsumer : public DiagnosticConsumer {
752 public:
753   NullDiagnosticConsumer() {
754     m_log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
755   }
756
757   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
758                         const clang::Diagnostic &info) {
759     if (m_log) {
760       llvm::SmallVector<char, 32> diag_str(10);
761       info.FormatDiagnostic(diag_str);
762       diag_str.push_back('\0');
763       m_log->Printf("Compiler diagnostic: %s\n", diag_str.data());
764     }
765   }
766
767   DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
768     return new NullDiagnosticConsumer();
769   }
770
771 private:
772   Log *m_log;
773 };
774
775 DiagnosticConsumer *ClangASTContext::getDiagnosticConsumer() {
776   if (m_diagnostic_consumer_ap.get() == nullptr)
777     m_diagnostic_consumer_ap.reset(new NullDiagnosticConsumer);
778
779   return m_diagnostic_consumer_ap.get();
780 }
781
782 std::shared_ptr<clang::TargetOptions> &ClangASTContext::getTargetOptions() {
783   if (m_target_options_rp.get() == nullptr && !m_target_triple.empty()) {
784     m_target_options_rp = std::make_shared<clang::TargetOptions>();
785     if (m_target_options_rp.get() != nullptr)
786       m_target_options_rp->Triple = m_target_triple;
787   }
788   return m_target_options_rp;
789 }
790
791 TargetInfo *ClangASTContext::getTargetInfo() {
792   // target_triple should be something like "x86_64-apple-macosx"
793   if (m_target_info_ap.get() == nullptr && !m_target_triple.empty())
794     m_target_info_ap.reset(TargetInfo::CreateTargetInfo(*getDiagnosticsEngine(),
795                                                         getTargetOptions()));
796   return m_target_info_ap.get();
797 }
798
799 #pragma mark Basic Types
800
801 static inline bool QualTypeMatchesBitSize(const uint64_t bit_size,
802                                           ASTContext *ast, QualType qual_type) {
803   uint64_t qual_type_bit_size = ast->getTypeSize(qual_type);
804   if (qual_type_bit_size == bit_size)
805     return true;
806   return false;
807 }
808
809 CompilerType
810 ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(Encoding encoding,
811                                                      size_t bit_size) {
812   return ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(
813       getASTContext(), encoding, bit_size);
814 }
815
816 CompilerType ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(
817     ASTContext *ast, Encoding encoding, uint32_t bit_size) {
818   if (!ast)
819     return CompilerType();
820   switch (encoding) {
821   case eEncodingInvalid:
822     if (QualTypeMatchesBitSize(bit_size, ast, ast->VoidPtrTy))
823       return CompilerType(ast, ast->VoidPtrTy);
824     break;
825
826   case eEncodingUint:
827     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
828       return CompilerType(ast, ast->UnsignedCharTy);
829     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
830       return CompilerType(ast, ast->UnsignedShortTy);
831     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
832       return CompilerType(ast, ast->UnsignedIntTy);
833     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongTy))
834       return CompilerType(ast, ast->UnsignedLongTy);
835     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongLongTy))
836       return CompilerType(ast, ast->UnsignedLongLongTy);
837     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedInt128Ty))
838       return CompilerType(ast, ast->UnsignedInt128Ty);
839     break;
840
841   case eEncodingSint:
842     if (QualTypeMatchesBitSize(bit_size, ast, ast->SignedCharTy))
843       return CompilerType(ast, ast->SignedCharTy);
844     if (QualTypeMatchesBitSize(bit_size, ast, ast->ShortTy))
845       return CompilerType(ast, ast->ShortTy);
846     if (QualTypeMatchesBitSize(bit_size, ast, ast->IntTy))
847       return CompilerType(ast, ast->IntTy);
848     if (QualTypeMatchesBitSize(bit_size, ast, ast->LongTy))
849       return CompilerType(ast, ast->LongTy);
850     if (QualTypeMatchesBitSize(bit_size, ast, ast->LongLongTy))
851       return CompilerType(ast, ast->LongLongTy);
852     if (QualTypeMatchesBitSize(bit_size, ast, ast->Int128Ty))
853       return CompilerType(ast, ast->Int128Ty);
854     break;
855
856   case eEncodingIEEE754:
857     if (QualTypeMatchesBitSize(bit_size, ast, ast->FloatTy))
858       return CompilerType(ast, ast->FloatTy);
859     if (QualTypeMatchesBitSize(bit_size, ast, ast->DoubleTy))
860       return CompilerType(ast, ast->DoubleTy);
861     if (QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleTy))
862       return CompilerType(ast, ast->LongDoubleTy);
863     if (QualTypeMatchesBitSize(bit_size, ast, ast->HalfTy))
864       return CompilerType(ast, ast->HalfTy);
865     break;
866
867   case eEncodingVector:
868     // Sanity check that bit_size is a multiple of 8's.
869     if (bit_size && !(bit_size & 0x7u))
870       return CompilerType(
871           ast, ast->getExtVectorType(ast->UnsignedCharTy, bit_size / 8));
872     break;
873   }
874
875   return CompilerType();
876 }
877
878 lldb::BasicType
879 ClangASTContext::GetBasicTypeEnumeration(const ConstString &name) {
880   if (name) {
881     typedef UniqueCStringMap<lldb::BasicType> TypeNameToBasicTypeMap;
882     static TypeNameToBasicTypeMap g_type_map;
883     static llvm::once_flag g_once_flag;
884     llvm::call_once(g_once_flag, []() {
885       // "void"
886       g_type_map.Append(ConstString("void"), eBasicTypeVoid);
887
888       // "char"
889       g_type_map.Append(ConstString("char"), eBasicTypeChar);
890       g_type_map.Append(ConstString("signed char"), eBasicTypeSignedChar);
891       g_type_map.Append(ConstString("unsigned char"), eBasicTypeUnsignedChar);
892       g_type_map.Append(ConstString("wchar_t"), eBasicTypeWChar);
893       g_type_map.Append(ConstString("signed wchar_t"), eBasicTypeSignedWChar);
894       g_type_map.Append(ConstString("unsigned wchar_t"),
895                         eBasicTypeUnsignedWChar);
896       // "short"
897       g_type_map.Append(ConstString("short"), eBasicTypeShort);
898       g_type_map.Append(ConstString("short int"), eBasicTypeShort);
899       g_type_map.Append(ConstString("unsigned short"), eBasicTypeUnsignedShort);
900       g_type_map.Append(ConstString("unsigned short int"),
901                         eBasicTypeUnsignedShort);
902
903       // "int"
904       g_type_map.Append(ConstString("int"), eBasicTypeInt);
905       g_type_map.Append(ConstString("signed int"), eBasicTypeInt);
906       g_type_map.Append(ConstString("unsigned int"), eBasicTypeUnsignedInt);
907       g_type_map.Append(ConstString("unsigned"), eBasicTypeUnsignedInt);
908
909       // "long"
910       g_type_map.Append(ConstString("long"), eBasicTypeLong);
911       g_type_map.Append(ConstString("long int"), eBasicTypeLong);
912       g_type_map.Append(ConstString("unsigned long"), eBasicTypeUnsignedLong);
913       g_type_map.Append(ConstString("unsigned long int"),
914                         eBasicTypeUnsignedLong);
915
916       // "long long"
917       g_type_map.Append(ConstString("long long"), eBasicTypeLongLong);
918       g_type_map.Append(ConstString("long long int"), eBasicTypeLongLong);
919       g_type_map.Append(ConstString("unsigned long long"),
920                         eBasicTypeUnsignedLongLong);
921       g_type_map.Append(ConstString("unsigned long long int"),
922                         eBasicTypeUnsignedLongLong);
923
924       // "int128"
925       g_type_map.Append(ConstString("__int128_t"), eBasicTypeInt128);
926       g_type_map.Append(ConstString("__uint128_t"), eBasicTypeUnsignedInt128);
927
928       // Miscellaneous
929       g_type_map.Append(ConstString("bool"), eBasicTypeBool);
930       g_type_map.Append(ConstString("float"), eBasicTypeFloat);
931       g_type_map.Append(ConstString("double"), eBasicTypeDouble);
932       g_type_map.Append(ConstString("long double"), eBasicTypeLongDouble);
933       g_type_map.Append(ConstString("id"), eBasicTypeObjCID);
934       g_type_map.Append(ConstString("SEL"), eBasicTypeObjCSel);
935       g_type_map.Append(ConstString("nullptr"), eBasicTypeNullPtr);
936       g_type_map.Sort();
937     });
938
939     return g_type_map.Find(name, eBasicTypeInvalid);
940   }
941   return eBasicTypeInvalid;
942 }
943
944 CompilerType ClangASTContext::GetBasicType(ASTContext *ast,
945                                            const ConstString &name) {
946   if (ast) {
947     lldb::BasicType basic_type = ClangASTContext::GetBasicTypeEnumeration(name);
948     return ClangASTContext::GetBasicType(ast, basic_type);
949   }
950   return CompilerType();
951 }
952
953 uint32_t ClangASTContext::GetPointerByteSize() {
954   if (m_pointer_byte_size == 0)
955     m_pointer_byte_size = GetBasicType(lldb::eBasicTypeVoid)
956                               .GetPointerType()
957                               .GetByteSize(nullptr);
958   return m_pointer_byte_size;
959 }
960
961 CompilerType ClangASTContext::GetBasicType(lldb::BasicType basic_type) {
962   return GetBasicType(getASTContext(), basic_type);
963 }
964
965 CompilerType ClangASTContext::GetBasicType(ASTContext *ast,
966                                            lldb::BasicType basic_type) {
967   if (!ast)
968     return CompilerType();
969   lldb::opaque_compiler_type_t clang_type =
970       GetOpaqueCompilerType(ast, basic_type);
971
972   if (clang_type)
973     return CompilerType(GetASTContext(ast), clang_type);
974   return CompilerType();
975 }
976
977 CompilerType ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize(
978     const char *type_name, uint32_t dw_ate, uint32_t bit_size) {
979   ASTContext *ast = getASTContext();
980
981 #define streq(a, b) strcmp(a, b) == 0
982   assert(ast != nullptr);
983   if (ast) {
984     switch (dw_ate) {
985     default:
986       break;
987
988     case DW_ATE_address:
989       if (QualTypeMatchesBitSize(bit_size, ast, ast->VoidPtrTy))
990         return CompilerType(ast, ast->VoidPtrTy);
991       break;
992
993     case DW_ATE_boolean:
994       if (QualTypeMatchesBitSize(bit_size, ast, ast->BoolTy))
995         return CompilerType(ast, ast->BoolTy);
996       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
997         return CompilerType(ast, ast->UnsignedCharTy);
998       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
999         return CompilerType(ast, ast->UnsignedShortTy);
1000       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
1001         return CompilerType(ast, ast->UnsignedIntTy);
1002       break;
1003
1004     case DW_ATE_lo_user:
1005       // This has been seen to mean DW_AT_complex_integer
1006       if (type_name) {
1007         if (::strstr(type_name, "complex")) {
1008           CompilerType complex_int_clang_type =
1009               GetBuiltinTypeForDWARFEncodingAndBitSize("int", DW_ATE_signed,
1010                                                        bit_size / 2);
1011           return CompilerType(ast, ast->getComplexType(ClangUtil::GetQualType(
1012                                        complex_int_clang_type)));
1013         }
1014       }
1015       break;
1016
1017     case DW_ATE_complex_float:
1018       if (QualTypeMatchesBitSize(bit_size, ast, ast->FloatComplexTy))
1019         return CompilerType(ast, ast->FloatComplexTy);
1020       else if (QualTypeMatchesBitSize(bit_size, ast, ast->DoubleComplexTy))
1021         return CompilerType(ast, ast->DoubleComplexTy);
1022       else if (QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleComplexTy))
1023         return CompilerType(ast, ast->LongDoubleComplexTy);
1024       else {
1025         CompilerType complex_float_clang_type =
1026             GetBuiltinTypeForDWARFEncodingAndBitSize("float", DW_ATE_float,
1027                                                      bit_size / 2);
1028         return CompilerType(ast, ast->getComplexType(ClangUtil::GetQualType(
1029                                      complex_float_clang_type)));
1030       }
1031       break;
1032
1033     case DW_ATE_float:
1034       if (streq(type_name, "float") &&
1035           QualTypeMatchesBitSize(bit_size, ast, ast->FloatTy))
1036         return CompilerType(ast, ast->FloatTy);
1037       if (streq(type_name, "double") &&
1038           QualTypeMatchesBitSize(bit_size, ast, ast->DoubleTy))
1039         return CompilerType(ast, ast->DoubleTy);
1040       if (streq(type_name, "long double") &&
1041           QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleTy))
1042         return CompilerType(ast, ast->LongDoubleTy);
1043       // Fall back to not requiring a name match
1044       if (QualTypeMatchesBitSize(bit_size, ast, ast->FloatTy))
1045         return CompilerType(ast, ast->FloatTy);
1046       if (QualTypeMatchesBitSize(bit_size, ast, ast->DoubleTy))
1047         return CompilerType(ast, ast->DoubleTy);
1048       if (QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleTy))
1049         return CompilerType(ast, ast->LongDoubleTy);
1050       if (QualTypeMatchesBitSize(bit_size, ast, ast->HalfTy))
1051         return CompilerType(ast, ast->HalfTy);
1052       break;
1053
1054     case DW_ATE_signed:
1055       if (type_name) {
1056         if (streq(type_name, "wchar_t") &&
1057             QualTypeMatchesBitSize(bit_size, ast, ast->WCharTy) &&
1058             (getTargetInfo() &&
1059              TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1060           return CompilerType(ast, ast->WCharTy);
1061         if (streq(type_name, "void") &&
1062             QualTypeMatchesBitSize(bit_size, ast, ast->VoidTy))
1063           return CompilerType(ast, ast->VoidTy);
1064         if (strstr(type_name, "long long") &&
1065             QualTypeMatchesBitSize(bit_size, ast, ast->LongLongTy))
1066           return CompilerType(ast, ast->LongLongTy);
1067         if (strstr(type_name, "long") &&
1068             QualTypeMatchesBitSize(bit_size, ast, ast->LongTy))
1069           return CompilerType(ast, ast->LongTy);
1070         if (strstr(type_name, "short") &&
1071             QualTypeMatchesBitSize(bit_size, ast, ast->ShortTy))
1072           return CompilerType(ast, ast->ShortTy);
1073         if (strstr(type_name, "char")) {
1074           if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
1075             return CompilerType(ast, ast->CharTy);
1076           if (QualTypeMatchesBitSize(bit_size, ast, ast->SignedCharTy))
1077             return CompilerType(ast, ast->SignedCharTy);
1078         }
1079         if (strstr(type_name, "int")) {
1080           if (QualTypeMatchesBitSize(bit_size, ast, ast->IntTy))
1081             return CompilerType(ast, ast->IntTy);
1082           if (QualTypeMatchesBitSize(bit_size, ast, ast->Int128Ty))
1083             return CompilerType(ast, ast->Int128Ty);
1084         }
1085       }
1086       // We weren't able to match up a type name, just search by size
1087       if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
1088         return CompilerType(ast, ast->CharTy);
1089       if (QualTypeMatchesBitSize(bit_size, ast, ast->ShortTy))
1090         return CompilerType(ast, ast->ShortTy);
1091       if (QualTypeMatchesBitSize(bit_size, ast, ast->IntTy))
1092         return CompilerType(ast, ast->IntTy);
1093       if (QualTypeMatchesBitSize(bit_size, ast, ast->LongTy))
1094         return CompilerType(ast, ast->LongTy);
1095       if (QualTypeMatchesBitSize(bit_size, ast, ast->LongLongTy))
1096         return CompilerType(ast, ast->LongLongTy);
1097       if (QualTypeMatchesBitSize(bit_size, ast, ast->Int128Ty))
1098         return CompilerType(ast, ast->Int128Ty);
1099       break;
1100
1101     case DW_ATE_signed_char:
1102       if (ast->getLangOpts().CharIsSigned && type_name &&
1103           streq(type_name, "char")) {
1104         if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
1105           return CompilerType(ast, ast->CharTy);
1106       }
1107       if (QualTypeMatchesBitSize(bit_size, ast, ast->SignedCharTy))
1108         return CompilerType(ast, ast->SignedCharTy);
1109       break;
1110
1111     case DW_ATE_unsigned:
1112       if (type_name) {
1113         if (streq(type_name, "wchar_t")) {
1114           if (QualTypeMatchesBitSize(bit_size, ast, ast->WCharTy)) {
1115             if (!(getTargetInfo() &&
1116                   TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1117               return CompilerType(ast, ast->WCharTy);
1118           }
1119         }
1120         if (strstr(type_name, "long long")) {
1121           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongLongTy))
1122             return CompilerType(ast, ast->UnsignedLongLongTy);
1123         } else if (strstr(type_name, "long")) {
1124           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongTy))
1125             return CompilerType(ast, ast->UnsignedLongTy);
1126         } else if (strstr(type_name, "short")) {
1127           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
1128             return CompilerType(ast, ast->UnsignedShortTy);
1129         } else if (strstr(type_name, "char")) {
1130           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
1131             return CompilerType(ast, ast->UnsignedCharTy);
1132         } else if (strstr(type_name, "int")) {
1133           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
1134             return CompilerType(ast, ast->UnsignedIntTy);
1135           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedInt128Ty))
1136             return CompilerType(ast, ast->UnsignedInt128Ty);
1137         }
1138       }
1139       // We weren't able to match up a type name, just search by size
1140       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
1141         return CompilerType(ast, ast->UnsignedCharTy);
1142       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
1143         return CompilerType(ast, ast->UnsignedShortTy);
1144       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
1145         return CompilerType(ast, ast->UnsignedIntTy);
1146       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongTy))
1147         return CompilerType(ast, ast->UnsignedLongTy);
1148       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongLongTy))
1149         return CompilerType(ast, ast->UnsignedLongLongTy);
1150       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedInt128Ty))
1151         return CompilerType(ast, ast->UnsignedInt128Ty);
1152       break;
1153
1154     case DW_ATE_unsigned_char:
1155       if (!ast->getLangOpts().CharIsSigned && type_name &&
1156           streq(type_name, "char")) {
1157         if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
1158           return CompilerType(ast, ast->CharTy);
1159       }
1160       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
1161         return CompilerType(ast, ast->UnsignedCharTy);
1162       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
1163         return CompilerType(ast, ast->UnsignedShortTy);
1164       break;
1165
1166     case DW_ATE_imaginary_float:
1167       break;
1168
1169     case DW_ATE_UTF:
1170       if (type_name) {
1171         if (streq(type_name, "char16_t")) {
1172           return CompilerType(ast, ast->Char16Ty);
1173         } else if (streq(type_name, "char32_t")) {
1174           return CompilerType(ast, ast->Char32Ty);
1175         }
1176       }
1177       break;
1178     }
1179   }
1180   // This assert should fire for anything that we don't catch above so we know
1181   // to fix any issues we run into.
1182   if (type_name) {
1183     Host::SystemLog(Host::eSystemLogError, "error: need to add support for "
1184                                            "DW_TAG_base_type '%s' encoded with "
1185                                            "DW_ATE = 0x%x, bit_size = %u\n",
1186                     type_name, dw_ate, bit_size);
1187   } else {
1188     Host::SystemLog(Host::eSystemLogError, "error: need to add support for "
1189                                            "DW_TAG_base_type encoded with "
1190                                            "DW_ATE = 0x%x, bit_size = %u\n",
1191                     dw_ate, bit_size);
1192   }
1193   return CompilerType();
1194 }
1195
1196 CompilerType ClangASTContext::GetUnknownAnyType(clang::ASTContext *ast) {
1197   if (ast)
1198     return CompilerType(ast, ast->UnknownAnyTy);
1199   return CompilerType();
1200 }
1201
1202 CompilerType ClangASTContext::GetCStringType(bool is_const) {
1203   ASTContext *ast = getASTContext();
1204   QualType char_type(ast->CharTy);
1205
1206   if (is_const)
1207     char_type.addConst();
1208
1209   return CompilerType(ast, ast->getPointerType(char_type));
1210 }
1211
1212 clang::DeclContext *
1213 ClangASTContext::GetTranslationUnitDecl(clang::ASTContext *ast) {
1214   return ast->getTranslationUnitDecl();
1215 }
1216
1217 clang::Decl *ClangASTContext::CopyDecl(ASTContext *dst_ast, ASTContext *src_ast,
1218                                        clang::Decl *source_decl) {
1219   FileSystemOptions file_system_options;
1220   FileManager file_manager(file_system_options);
1221   ASTImporter importer(*dst_ast, file_manager, *src_ast, file_manager, false);
1222
1223   return importer.Import(source_decl);
1224 }
1225
1226 bool ClangASTContext::AreTypesSame(CompilerType type1, CompilerType type2,
1227                                    bool ignore_qualifiers) {
1228   ClangASTContext *ast =
1229       llvm::dyn_cast_or_null<ClangASTContext>(type1.GetTypeSystem());
1230   if (!ast || ast != type2.GetTypeSystem())
1231     return false;
1232
1233   if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType())
1234     return true;
1235
1236   QualType type1_qual = ClangUtil::GetQualType(type1);
1237   QualType type2_qual = ClangUtil::GetQualType(type2);
1238
1239   if (ignore_qualifiers) {
1240     type1_qual = type1_qual.getUnqualifiedType();
1241     type2_qual = type2_qual.getUnqualifiedType();
1242   }
1243
1244   return ast->getASTContext()->hasSameType(type1_qual, type2_qual);
1245 }
1246
1247 CompilerType ClangASTContext::GetTypeForDecl(clang::NamedDecl *decl) {
1248   if (clang::ObjCInterfaceDecl *interface_decl =
1249           llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
1250     return GetTypeForDecl(interface_decl);
1251   if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
1252     return GetTypeForDecl(tag_decl);
1253   return CompilerType();
1254 }
1255
1256 CompilerType ClangASTContext::GetTypeForDecl(TagDecl *decl) {
1257   // No need to call the getASTContext() accessor (which can create the AST if
1258   // it isn't created yet, because we can't have created a decl in this
1259   // AST if our AST didn't already exist...
1260   ASTContext *ast = &decl->getASTContext();
1261   if (ast)
1262     return CompilerType(ast, ast->getTagDeclType(decl));
1263   return CompilerType();
1264 }
1265
1266 CompilerType ClangASTContext::GetTypeForDecl(ObjCInterfaceDecl *decl) {
1267   // No need to call the getASTContext() accessor (which can create the AST if
1268   // it isn't created yet, because we can't have created a decl in this
1269   // AST if our AST didn't already exist...
1270   ASTContext *ast = &decl->getASTContext();
1271   if (ast)
1272     return CompilerType(ast, ast->getObjCInterfaceType(decl));
1273   return CompilerType();
1274 }
1275
1276 #pragma mark Structure, Unions, Classes
1277
1278 CompilerType ClangASTContext::CreateRecordType(DeclContext *decl_ctx,
1279                                                AccessType access_type,
1280                                                const char *name, int kind,
1281                                                LanguageType language,
1282                                                ClangASTMetadata *metadata) {
1283   ASTContext *ast = getASTContext();
1284   assert(ast != nullptr);
1285
1286   if (decl_ctx == nullptr)
1287     decl_ctx = ast->getTranslationUnitDecl();
1288
1289   if (language == eLanguageTypeObjC ||
1290       language == eLanguageTypeObjC_plus_plus) {
1291     bool isForwardDecl = true;
1292     bool isInternal = false;
1293     return CreateObjCClass(name, decl_ctx, isForwardDecl, isInternal, metadata);
1294   }
1295
1296   // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1297   // we will need to update this code. I was told to currently always use the
1298   // CXXRecordDecl class since we often don't know from debug information if
1299   // something is struct or a class, so we default to always use the more
1300   // complete definition just in case.
1301
1302   bool is_anonymous = (!name) || (!name[0]);
1303
1304   CXXRecordDecl *decl = CXXRecordDecl::Create(
1305       *ast, (TagDecl::TagKind)kind, decl_ctx, SourceLocation(),
1306       SourceLocation(), is_anonymous ? nullptr : &ast->Idents.get(name));
1307
1308   if (is_anonymous)
1309     decl->setAnonymousStructOrUnion(true);
1310
1311   if (decl) {
1312     if (metadata)
1313       SetMetadata(ast, decl, *metadata);
1314
1315     if (access_type != eAccessNone)
1316       decl->setAccess(ConvertAccessTypeToAccessSpecifier(access_type));
1317
1318     if (decl_ctx)
1319       decl_ctx->addDecl(decl);
1320
1321     return CompilerType(ast, ast->getTagDeclType(decl));
1322   }
1323   return CompilerType();
1324 }
1325
1326 namespace {
1327   bool IsValueParam(const clang::TemplateArgument &argument) {
1328     return argument.getKind() == TemplateArgument::Integral;
1329   }
1330 }
1331
1332 static TemplateParameterList *CreateTemplateParameterList(
1333     ASTContext *ast,
1334     const ClangASTContext::TemplateParameterInfos &template_param_infos,
1335     llvm::SmallVector<NamedDecl *, 8> &template_param_decls) {
1336   const bool parameter_pack = false;
1337   const bool is_typename = false;
1338   const unsigned depth = 0;
1339   const size_t num_template_params = template_param_infos.args.size();
1340   DeclContext *const decl_context =
1341       ast->getTranslationUnitDecl(); // Is this the right decl context?,
1342   for (size_t i = 0; i < num_template_params; ++i) {
1343     const char *name = template_param_infos.names[i];
1344
1345     IdentifierInfo *identifier_info = nullptr;
1346     if (name && name[0])
1347       identifier_info = &ast->Idents.get(name);
1348     if (IsValueParam(template_param_infos.args[i])) {
1349       template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1350           *ast, decl_context,
1351           SourceLocation(), SourceLocation(), depth, i, identifier_info,
1352           template_param_infos.args[i].getIntegralType(), parameter_pack,
1353           nullptr));
1354
1355     } else {
1356       template_param_decls.push_back(TemplateTypeParmDecl::Create(
1357           *ast, decl_context,
1358           SourceLocation(), SourceLocation(), depth, i, identifier_info,
1359           is_typename, parameter_pack));
1360     }
1361   }
1362
1363   if (template_param_infos.packed_args &&
1364       template_param_infos.packed_args->args.size()) {
1365     IdentifierInfo *identifier_info = nullptr;
1366     if (template_param_infos.pack_name && template_param_infos.pack_name[0])
1367       identifier_info = &ast->Idents.get(template_param_infos.pack_name);
1368     const bool parameter_pack_true = true;
1369     if (IsValueParam(template_param_infos.packed_args->args[0])) {
1370       template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1371           *ast, decl_context,
1372           SourceLocation(), SourceLocation(), depth, num_template_params,
1373           identifier_info,
1374           template_param_infos.packed_args->args[0].getIntegralType(),
1375           parameter_pack_true, nullptr));
1376     } else {
1377       template_param_decls.push_back(TemplateTypeParmDecl::Create(
1378           *ast, decl_context,
1379           SourceLocation(), SourceLocation(), depth, num_template_params,
1380           identifier_info,
1381           is_typename, parameter_pack_true));
1382     }
1383   }
1384   clang::Expr *const requires_clause = nullptr; // TODO: Concepts
1385   TemplateParameterList *template_param_list = TemplateParameterList::Create(
1386       *ast, SourceLocation(), SourceLocation(), template_param_decls,
1387       SourceLocation(), requires_clause);
1388   return template_param_list;
1389 }
1390
1391 clang::FunctionTemplateDecl *ClangASTContext::CreateFunctionTemplateDecl(
1392     clang::DeclContext *decl_ctx, clang::FunctionDecl *func_decl,
1393     const char *name, const TemplateParameterInfos &template_param_infos) {
1394   //    /// Create a function template node.
1395   ASTContext *ast = getASTContext();
1396
1397   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1398
1399   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1400       ast, template_param_infos, template_param_decls);
1401   FunctionTemplateDecl *func_tmpl_decl = FunctionTemplateDecl::Create(
1402       *ast, decl_ctx, func_decl->getLocation(), func_decl->getDeclName(),
1403       template_param_list, func_decl);
1404
1405   for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1406        i < template_param_decl_count; ++i) {
1407     // TODO: verify which decl context we should put template_param_decls into..
1408     template_param_decls[i]->setDeclContext(func_decl);
1409   }
1410
1411   return func_tmpl_decl;
1412 }
1413
1414 void ClangASTContext::CreateFunctionTemplateSpecializationInfo(
1415     FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl,
1416     const TemplateParameterInfos &infos) {
1417   TemplateArgumentList template_args(TemplateArgumentList::OnStack, infos.args);
1418
1419   func_decl->setFunctionTemplateSpecialization(func_tmpl_decl, &template_args,
1420                                                nullptr);
1421 }
1422
1423 ClassTemplateDecl *ClangASTContext::CreateClassTemplateDecl(
1424     DeclContext *decl_ctx, lldb::AccessType access_type, const char *class_name,
1425     int kind, const TemplateParameterInfos &template_param_infos) {
1426   ASTContext *ast = getASTContext();
1427
1428   ClassTemplateDecl *class_template_decl = nullptr;
1429   if (decl_ctx == nullptr)
1430     decl_ctx = ast->getTranslationUnitDecl();
1431
1432   IdentifierInfo &identifier_info = ast->Idents.get(class_name);
1433   DeclarationName decl_name(&identifier_info);
1434
1435   clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1436
1437   for (NamedDecl *decl : result) {
1438     class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1439     if (class_template_decl)
1440       return class_template_decl;
1441   }
1442
1443   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1444
1445   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1446       ast, template_param_infos, template_param_decls);
1447
1448   CXXRecordDecl *template_cxx_decl = CXXRecordDecl::Create(
1449       *ast, (TagDecl::TagKind)kind,
1450       decl_ctx, // What decl context do we use here? TU? The actual decl
1451                 // context?
1452       SourceLocation(), SourceLocation(), &identifier_info);
1453
1454   for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1455        i < template_param_decl_count; ++i) {
1456     template_param_decls[i]->setDeclContext(template_cxx_decl);
1457   }
1458
1459   // With templated classes, we say that a class is templated with
1460   // specializations, but that the bare class has no functions.
1461   // template_cxx_decl->startDefinition();
1462   // template_cxx_decl->completeDefinition();
1463
1464   class_template_decl = ClassTemplateDecl::Create(
1465       *ast,
1466       decl_ctx, // What decl context do we use here? TU? The actual decl
1467                 // context?
1468       SourceLocation(), decl_name, template_param_list, template_cxx_decl);
1469
1470   if (class_template_decl) {
1471     if (access_type != eAccessNone)
1472       class_template_decl->setAccess(
1473           ConvertAccessTypeToAccessSpecifier(access_type));
1474
1475     // if (TagDecl *ctx_tag_decl = dyn_cast<TagDecl>(decl_ctx))
1476     //    CompleteTagDeclarationDefinition(GetTypeForDecl(ctx_tag_decl));
1477
1478     decl_ctx->addDecl(class_template_decl);
1479
1480 #ifdef LLDB_CONFIGURATION_DEBUG
1481     VerifyDecl(class_template_decl);
1482 #endif
1483   }
1484
1485   return class_template_decl;
1486 }
1487
1488 TemplateTemplateParmDecl *
1489 ClangASTContext::CreateTemplateTemplateParmDecl(const char *template_name) {
1490   ASTContext *ast = getASTContext();
1491
1492   auto *decl_ctx = ast->getTranslationUnitDecl();
1493
1494   IdentifierInfo &identifier_info = ast->Idents.get(template_name);
1495   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1496
1497   ClangASTContext::TemplateParameterInfos template_param_infos;
1498   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1499       ast, template_param_infos, template_param_decls);
1500
1501   // LLDB needs to create those decls only to be able to display a
1502   // type that includes a template template argument. Only the name matters for
1503   // this purpose, so we use dummy values for the other characterisitcs of the
1504   // type.
1505   return TemplateTemplateParmDecl::Create(
1506       *ast, decl_ctx, SourceLocation(),
1507       /*Depth*/ 0, /*Position*/ 0,
1508       /*IsParameterPack*/ false, &identifier_info, template_param_list);
1509 }
1510
1511 ClassTemplateSpecializationDecl *
1512 ClangASTContext::CreateClassTemplateSpecializationDecl(
1513     DeclContext *decl_ctx, ClassTemplateDecl *class_template_decl, int kind,
1514     const TemplateParameterInfos &template_param_infos) {
1515   ASTContext *ast = getASTContext();
1516   llvm::SmallVector<clang::TemplateArgument, 2> args(
1517       template_param_infos.args.size() +
1518       (template_param_infos.packed_args ? 1 : 0));
1519   std::copy(template_param_infos.args.begin(), template_param_infos.args.end(),
1520             args.begin());
1521   if (template_param_infos.packed_args) {
1522     args[args.size() - 1] = TemplateArgument::CreatePackCopy(
1523         *ast, template_param_infos.packed_args->args);
1524   }
1525   ClassTemplateSpecializationDecl *class_template_specialization_decl =
1526       ClassTemplateSpecializationDecl::Create(
1527           *ast, (TagDecl::TagKind)kind, decl_ctx, SourceLocation(),
1528           SourceLocation(), class_template_decl, args,
1529           nullptr);
1530
1531   class_template_specialization_decl->setSpecializationKind(
1532       TSK_ExplicitSpecialization);
1533
1534   return class_template_specialization_decl;
1535 }
1536
1537 CompilerType ClangASTContext::CreateClassTemplateSpecializationType(
1538     ClassTemplateSpecializationDecl *class_template_specialization_decl) {
1539   if (class_template_specialization_decl) {
1540     ASTContext *ast = getASTContext();
1541     if (ast)
1542       return CompilerType(
1543           ast, ast->getTagDeclType(class_template_specialization_decl));
1544   }
1545   return CompilerType();
1546 }
1547
1548 static inline bool check_op_param(bool is_method,
1549                                   clang::OverloadedOperatorKind op_kind,
1550                                   bool unary, bool binary,
1551                                   uint32_t num_params) {
1552   // Special-case call since it can take any number of operands
1553   if (op_kind == OO_Call)
1554     return true;
1555
1556   // The parameter count doesn't include "this"
1557   if (is_method)
1558     ++num_params;
1559   if (num_params == 1)
1560     return unary;
1561   if (num_params == 2)
1562     return binary;
1563   else
1564     return false;
1565 }
1566
1567 bool ClangASTContext::CheckOverloadedOperatorKindParameterCount(
1568     bool is_method, clang::OverloadedOperatorKind op_kind,
1569     uint32_t num_params) {
1570   switch (op_kind) {
1571   default:
1572     break;
1573   // C++ standard allows any number of arguments to new/delete
1574   case OO_New:
1575   case OO_Array_New:
1576   case OO_Delete:
1577   case OO_Array_Delete:
1578     return true;
1579   }
1580
1581 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
1582   case OO_##Name:                                                              \
1583     return check_op_param(is_method, op_kind, Unary, Binary, num_params);
1584   switch (op_kind) {
1585 #include "clang/Basic/OperatorKinds.def"
1586   default:
1587     break;
1588   }
1589   return false;
1590 }
1591
1592 clang::AccessSpecifier
1593 ClangASTContext::UnifyAccessSpecifiers(clang::AccessSpecifier lhs,
1594                                        clang::AccessSpecifier rhs) {
1595   // Make the access equal to the stricter of the field and the nested field's
1596   // access
1597   if (lhs == AS_none || rhs == AS_none)
1598     return AS_none;
1599   if (lhs == AS_private || rhs == AS_private)
1600     return AS_private;
1601   if (lhs == AS_protected || rhs == AS_protected)
1602     return AS_protected;
1603   return AS_public;
1604 }
1605
1606 bool ClangASTContext::FieldIsBitfield(FieldDecl *field,
1607                                       uint32_t &bitfield_bit_size) {
1608   return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
1609 }
1610
1611 bool ClangASTContext::FieldIsBitfield(ASTContext *ast, FieldDecl *field,
1612                                       uint32_t &bitfield_bit_size) {
1613   if (ast == nullptr || field == nullptr)
1614     return false;
1615
1616   if (field->isBitField()) {
1617     Expr *bit_width_expr = field->getBitWidth();
1618     if (bit_width_expr) {
1619       llvm::APSInt bit_width_apsint;
1620       if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast)) {
1621         bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
1622         return true;
1623       }
1624     }
1625   }
1626   return false;
1627 }
1628
1629 bool ClangASTContext::RecordHasFields(const RecordDecl *record_decl) {
1630   if (record_decl == nullptr)
1631     return false;
1632
1633   if (!record_decl->field_empty())
1634     return true;
1635
1636   // No fields, lets check this is a CXX record and check the base classes
1637   const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1638   if (cxx_record_decl) {
1639     CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1640     for (base_class = cxx_record_decl->bases_begin(),
1641         base_class_end = cxx_record_decl->bases_end();
1642          base_class != base_class_end; ++base_class) {
1643       const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(
1644           base_class->getType()->getAs<RecordType>()->getDecl());
1645       if (RecordHasFields(base_class_decl))
1646         return true;
1647     }
1648   }
1649   return false;
1650 }
1651
1652 #pragma mark Objective-C Classes
1653
1654 CompilerType ClangASTContext::CreateObjCClass(const char *name,
1655                                               DeclContext *decl_ctx,
1656                                               bool isForwardDecl,
1657                                               bool isInternal,
1658                                               ClangASTMetadata *metadata) {
1659   ASTContext *ast = getASTContext();
1660   assert(ast != nullptr);
1661   assert(name && name[0]);
1662   if (decl_ctx == nullptr)
1663     decl_ctx = ast->getTranslationUnitDecl();
1664
1665   ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create(
1666       *ast, decl_ctx, SourceLocation(), &ast->Idents.get(name), nullptr,
1667       nullptr, SourceLocation(),
1668       /*isForwardDecl,*/
1669       isInternal);
1670
1671   if (decl && metadata)
1672     SetMetadata(ast, decl, *metadata);
1673
1674   return CompilerType(ast, ast->getObjCInterfaceType(decl));
1675 }
1676
1677 static inline bool BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) {
1678   return ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl()) ==
1679          false;
1680 }
1681
1682 uint32_t
1683 ClangASTContext::GetNumBaseClasses(const CXXRecordDecl *cxx_record_decl,
1684                                    bool omit_empty_base_classes) {
1685   uint32_t num_bases = 0;
1686   if (cxx_record_decl) {
1687     if (omit_empty_base_classes) {
1688       CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1689       for (base_class = cxx_record_decl->bases_begin(),
1690           base_class_end = cxx_record_decl->bases_end();
1691            base_class != base_class_end; ++base_class) {
1692         // Skip empty base classes
1693         if (omit_empty_base_classes) {
1694           if (BaseSpecifierIsEmpty(base_class))
1695             continue;
1696         }
1697         ++num_bases;
1698       }
1699     } else
1700       num_bases = cxx_record_decl->getNumBases();
1701   }
1702   return num_bases;
1703 }
1704
1705 #pragma mark Namespace Declarations
1706
1707 NamespaceDecl *
1708 ClangASTContext::GetUniqueNamespaceDeclaration(const char *name,
1709                                                DeclContext *decl_ctx) {
1710   NamespaceDecl *namespace_decl = nullptr;
1711   ASTContext *ast = getASTContext();
1712   TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl();
1713   if (decl_ctx == nullptr)
1714     decl_ctx = translation_unit_decl;
1715
1716   if (name) {
1717     IdentifierInfo &identifier_info = ast->Idents.get(name);
1718     DeclarationName decl_name(&identifier_info);
1719     clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1720     for (NamedDecl *decl : result) {
1721       namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
1722       if (namespace_decl)
1723         return namespace_decl;
1724     }
1725
1726     namespace_decl =
1727         NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(),
1728                               SourceLocation(), &identifier_info, nullptr);
1729
1730     decl_ctx->addDecl(namespace_decl);
1731   } else {
1732     if (decl_ctx == translation_unit_decl) {
1733       namespace_decl = translation_unit_decl->getAnonymousNamespace();
1734       if (namespace_decl)
1735         return namespace_decl;
1736
1737       namespace_decl =
1738           NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(),
1739                                 SourceLocation(), nullptr, nullptr);
1740       translation_unit_decl->setAnonymousNamespace(namespace_decl);
1741       translation_unit_decl->addDecl(namespace_decl);
1742       assert(namespace_decl == translation_unit_decl->getAnonymousNamespace());
1743     } else {
1744       NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
1745       if (parent_namespace_decl) {
1746         namespace_decl = parent_namespace_decl->getAnonymousNamespace();
1747         if (namespace_decl)
1748           return namespace_decl;
1749         namespace_decl =
1750             NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(),
1751                                   SourceLocation(), nullptr, nullptr);
1752         parent_namespace_decl->setAnonymousNamespace(namespace_decl);
1753         parent_namespace_decl->addDecl(namespace_decl);
1754         assert(namespace_decl ==
1755                parent_namespace_decl->getAnonymousNamespace());
1756       } else {
1757         // BAD!!!
1758       }
1759     }
1760   }
1761 #ifdef LLDB_CONFIGURATION_DEBUG
1762   VerifyDecl(namespace_decl);
1763 #endif
1764   return namespace_decl;
1765 }
1766
1767 NamespaceDecl *ClangASTContext::GetUniqueNamespaceDeclaration(
1768     clang::ASTContext *ast, const char *name, clang::DeclContext *decl_ctx) {
1769   ClangASTContext *ast_ctx = ClangASTContext::GetASTContext(ast);
1770   if (ast_ctx == nullptr)
1771     return nullptr;
1772
1773   return ast_ctx->GetUniqueNamespaceDeclaration(name, decl_ctx);
1774 }
1775
1776 clang::BlockDecl *
1777 ClangASTContext::CreateBlockDeclaration(clang::DeclContext *ctx) {
1778   if (ctx != nullptr) {
1779     clang::BlockDecl *decl = clang::BlockDecl::Create(*getASTContext(), ctx,
1780                                                       clang::SourceLocation());
1781     ctx->addDecl(decl);
1782     return decl;
1783   }
1784   return nullptr;
1785 }
1786
1787 clang::DeclContext *FindLCABetweenDecls(clang::DeclContext *left,
1788                                         clang::DeclContext *right,
1789                                         clang::DeclContext *root) {
1790   if (root == nullptr)
1791     return nullptr;
1792
1793   std::set<clang::DeclContext *> path_left;
1794   for (clang::DeclContext *d = left; d != nullptr; d = d->getParent())
1795     path_left.insert(d);
1796
1797   for (clang::DeclContext *d = right; d != nullptr; d = d->getParent())
1798     if (path_left.find(d) != path_left.end())
1799       return d;
1800
1801   return nullptr;
1802 }
1803
1804 clang::UsingDirectiveDecl *ClangASTContext::CreateUsingDirectiveDeclaration(
1805     clang::DeclContext *decl_ctx, clang::NamespaceDecl *ns_decl) {
1806   if (decl_ctx != nullptr && ns_decl != nullptr) {
1807     clang::TranslationUnitDecl *translation_unit =
1808         (clang::TranslationUnitDecl *)GetTranslationUnitDecl(getASTContext());
1809     clang::UsingDirectiveDecl *using_decl = clang::UsingDirectiveDecl::Create(
1810         *getASTContext(), decl_ctx, clang::SourceLocation(),
1811         clang::SourceLocation(), clang::NestedNameSpecifierLoc(),
1812         clang::SourceLocation(), ns_decl,
1813         FindLCABetweenDecls(decl_ctx, ns_decl, translation_unit));
1814     decl_ctx->addDecl(using_decl);
1815     return using_decl;
1816   }
1817   return nullptr;
1818 }
1819
1820 clang::UsingDecl *
1821 ClangASTContext::CreateUsingDeclaration(clang::DeclContext *current_decl_ctx,
1822                                         clang::NamedDecl *target) {
1823   if (current_decl_ctx != nullptr && target != nullptr) {
1824     clang::UsingDecl *using_decl = clang::UsingDecl::Create(
1825         *getASTContext(), current_decl_ctx, clang::SourceLocation(),
1826         clang::NestedNameSpecifierLoc(), clang::DeclarationNameInfo(), false);
1827     clang::UsingShadowDecl *shadow_decl = clang::UsingShadowDecl::Create(
1828         *getASTContext(), current_decl_ctx, clang::SourceLocation(), using_decl,
1829         target);
1830     using_decl->addShadowDecl(shadow_decl);
1831     current_decl_ctx->addDecl(using_decl);
1832     return using_decl;
1833   }
1834   return nullptr;
1835 }
1836
1837 clang::VarDecl *ClangASTContext::CreateVariableDeclaration(
1838     clang::DeclContext *decl_context, const char *name, clang::QualType type) {
1839   if (decl_context != nullptr) {
1840     clang::VarDecl *var_decl = clang::VarDecl::Create(
1841         *getASTContext(), decl_context, clang::SourceLocation(),
1842         clang::SourceLocation(),
1843         name && name[0] ? &getASTContext()->Idents.getOwn(name) : nullptr, type,
1844         nullptr, clang::SC_None);
1845     var_decl->setAccess(clang::AS_public);
1846     decl_context->addDecl(var_decl);
1847     return var_decl;
1848   }
1849   return nullptr;
1850 }
1851
1852 lldb::opaque_compiler_type_t
1853 ClangASTContext::GetOpaqueCompilerType(clang::ASTContext *ast,
1854                                        lldb::BasicType basic_type) {
1855   switch (basic_type) {
1856   case eBasicTypeVoid:
1857     return ast->VoidTy.getAsOpaquePtr();
1858   case eBasicTypeChar:
1859     return ast->CharTy.getAsOpaquePtr();
1860   case eBasicTypeSignedChar:
1861     return ast->SignedCharTy.getAsOpaquePtr();
1862   case eBasicTypeUnsignedChar:
1863     return ast->UnsignedCharTy.getAsOpaquePtr();
1864   case eBasicTypeWChar:
1865     return ast->getWCharType().getAsOpaquePtr();
1866   case eBasicTypeSignedWChar:
1867     return ast->getSignedWCharType().getAsOpaquePtr();
1868   case eBasicTypeUnsignedWChar:
1869     return ast->getUnsignedWCharType().getAsOpaquePtr();
1870   case eBasicTypeChar16:
1871     return ast->Char16Ty.getAsOpaquePtr();
1872   case eBasicTypeChar32:
1873     return ast->Char32Ty.getAsOpaquePtr();
1874   case eBasicTypeShort:
1875     return ast->ShortTy.getAsOpaquePtr();
1876   case eBasicTypeUnsignedShort:
1877     return ast->UnsignedShortTy.getAsOpaquePtr();
1878   case eBasicTypeInt:
1879     return ast->IntTy.getAsOpaquePtr();
1880   case eBasicTypeUnsignedInt:
1881     return ast->UnsignedIntTy.getAsOpaquePtr();
1882   case eBasicTypeLong:
1883     return ast->LongTy.getAsOpaquePtr();
1884   case eBasicTypeUnsignedLong:
1885     return ast->UnsignedLongTy.getAsOpaquePtr();
1886   case eBasicTypeLongLong:
1887     return ast->LongLongTy.getAsOpaquePtr();
1888   case eBasicTypeUnsignedLongLong:
1889     return ast->UnsignedLongLongTy.getAsOpaquePtr();
1890   case eBasicTypeInt128:
1891     return ast->Int128Ty.getAsOpaquePtr();
1892   case eBasicTypeUnsignedInt128:
1893     return ast->UnsignedInt128Ty.getAsOpaquePtr();
1894   case eBasicTypeBool:
1895     return ast->BoolTy.getAsOpaquePtr();
1896   case eBasicTypeHalf:
1897     return ast->HalfTy.getAsOpaquePtr();
1898   case eBasicTypeFloat:
1899     return ast->FloatTy.getAsOpaquePtr();
1900   case eBasicTypeDouble:
1901     return ast->DoubleTy.getAsOpaquePtr();
1902   case eBasicTypeLongDouble:
1903     return ast->LongDoubleTy.getAsOpaquePtr();
1904   case eBasicTypeFloatComplex:
1905     return ast->FloatComplexTy.getAsOpaquePtr();
1906   case eBasicTypeDoubleComplex:
1907     return ast->DoubleComplexTy.getAsOpaquePtr();
1908   case eBasicTypeLongDoubleComplex:
1909     return ast->LongDoubleComplexTy.getAsOpaquePtr();
1910   case eBasicTypeObjCID:
1911     return ast->getObjCIdType().getAsOpaquePtr();
1912   case eBasicTypeObjCClass:
1913     return ast->getObjCClassType().getAsOpaquePtr();
1914   case eBasicTypeObjCSel:
1915     return ast->getObjCSelType().getAsOpaquePtr();
1916   case eBasicTypeNullPtr:
1917     return ast->NullPtrTy.getAsOpaquePtr();
1918   default:
1919     return nullptr;
1920   }
1921 }
1922
1923 #pragma mark Function Types
1924
1925 clang::DeclarationName
1926 ClangASTContext::GetDeclarationName(const char *name,
1927                                     const CompilerType &function_clang_type) {
1928   if (!name || !name[0])
1929     return clang::DeclarationName();
1930
1931   clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
1932   if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS)
1933     return DeclarationName(&getASTContext()->Idents.get(
1934         name)); // Not operator, but a regular function.
1935
1936   // Check the number of operator parameters. Sometimes we have seen bad DWARF
1937   // that doesn't correctly describe operators and if we try to create a method
1938   // and add it to the class, clang will assert and crash, so we need to make
1939   // sure things are acceptable.
1940   clang::QualType method_qual_type(ClangUtil::GetQualType(function_clang_type));
1941   const clang::FunctionProtoType *function_type =
1942       llvm::dyn_cast<clang::FunctionProtoType>(method_qual_type.getTypePtr());
1943   if (function_type == nullptr)
1944     return clang::DeclarationName();
1945
1946   const bool is_method = false;
1947   const unsigned int num_params = function_type->getNumParams();
1948   if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount(
1949           is_method, op_kind, num_params))
1950     return clang::DeclarationName();
1951
1952   return getASTContext()->DeclarationNames.getCXXOperatorName(op_kind);
1953 }
1954
1955 FunctionDecl *ClangASTContext::CreateFunctionDeclaration(
1956     DeclContext *decl_ctx, const char *name,
1957     const CompilerType &function_clang_type, int storage, bool is_inline) {
1958   FunctionDecl *func_decl = nullptr;
1959   ASTContext *ast = getASTContext();
1960   if (decl_ctx == nullptr)
1961     decl_ctx = ast->getTranslationUnitDecl();
1962
1963   const bool hasWrittenPrototype = true;
1964   const bool isConstexprSpecified = false;
1965
1966   clang::DeclarationName declarationName =
1967       GetDeclarationName(name, function_clang_type);
1968   func_decl = FunctionDecl::Create(
1969       *ast, decl_ctx, SourceLocation(), SourceLocation(), declarationName,
1970       ClangUtil::GetQualType(function_clang_type), nullptr,
1971       (clang::StorageClass)storage, is_inline, hasWrittenPrototype,
1972       isConstexprSpecified);
1973   if (func_decl)
1974     decl_ctx->addDecl(func_decl);
1975
1976 #ifdef LLDB_CONFIGURATION_DEBUG
1977   VerifyDecl(func_decl);
1978 #endif
1979
1980   return func_decl;
1981 }
1982
1983 CompilerType ClangASTContext::CreateFunctionType(
1984     ASTContext *ast, const CompilerType &result_type, const CompilerType *args,
1985     unsigned num_args, bool is_variadic, unsigned type_quals) {
1986   if (ast == nullptr)
1987     return CompilerType(); // invalid AST
1988
1989   if (!result_type || !ClangUtil::IsClangType(result_type))
1990     return CompilerType(); // invalid return type
1991
1992   std::vector<QualType> qual_type_args;
1993   if (num_args > 0 && args == nullptr)
1994     return CompilerType(); // invalid argument array passed in
1995
1996   // Verify that all arguments are valid and the right type
1997   for (unsigned i = 0; i < num_args; ++i) {
1998     if (args[i]) {
1999       // Make sure we have a clang type in args[i] and not a type from another
2000       // language whose name might match
2001       const bool is_clang_type = ClangUtil::IsClangType(args[i]);
2002       lldbassert(is_clang_type);
2003       if (is_clang_type)
2004         qual_type_args.push_back(ClangUtil::GetQualType(args[i]));
2005       else
2006         return CompilerType(); //  invalid argument type (must be a clang type)
2007     } else
2008       return CompilerType(); // invalid argument type (empty)
2009   }
2010
2011   // TODO: Detect calling convention in DWARF?
2012   FunctionProtoType::ExtProtoInfo proto_info;
2013   proto_info.Variadic = is_variadic;
2014   proto_info.ExceptionSpec = EST_None;
2015   proto_info.TypeQuals = type_quals;
2016   proto_info.RefQualifier = RQ_None;
2017
2018   return CompilerType(ast,
2019                       ast->getFunctionType(ClangUtil::GetQualType(result_type),
2020                                            qual_type_args, proto_info));
2021 }
2022
2023 ParmVarDecl *ClangASTContext::CreateParameterDeclaration(
2024     const char *name, const CompilerType &param_type, int storage) {
2025   ASTContext *ast = getASTContext();
2026   assert(ast != nullptr);
2027   return ParmVarDecl::Create(*ast, ast->getTranslationUnitDecl(),
2028                              SourceLocation(), SourceLocation(),
2029                              name && name[0] ? &ast->Idents.get(name) : nullptr,
2030                              ClangUtil::GetQualType(param_type), nullptr,
2031                              (clang::StorageClass)storage, nullptr);
2032 }
2033
2034 void ClangASTContext::SetFunctionParameters(FunctionDecl *function_decl,
2035                                             ParmVarDecl **params,
2036                                             unsigned num_params) {
2037   if (function_decl)
2038     function_decl->setParams(ArrayRef<ParmVarDecl *>(params, num_params));
2039 }
2040
2041 CompilerType
2042 ClangASTContext::CreateBlockPointerType(const CompilerType &function_type) {
2043   QualType block_type = m_ast_ap->getBlockPointerType(
2044       clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType()));
2045
2046   return CompilerType(this, block_type.getAsOpaquePtr());
2047 }
2048
2049 #pragma mark Array Types
2050
2051 CompilerType ClangASTContext::CreateArrayType(const CompilerType &element_type,
2052                                               size_t element_count,
2053                                               bool is_vector) {
2054   if (element_type.IsValid()) {
2055     ASTContext *ast = getASTContext();
2056     assert(ast != nullptr);
2057
2058     if (is_vector) {
2059       return CompilerType(
2060           ast, ast->getExtVectorType(ClangUtil::GetQualType(element_type),
2061                                      element_count));
2062     } else {
2063
2064       llvm::APInt ap_element_count(64, element_count);
2065       if (element_count == 0) {
2066         return CompilerType(ast, ast->getIncompleteArrayType(
2067                                      ClangUtil::GetQualType(element_type),
2068                                      clang::ArrayType::Normal, 0));
2069       } else {
2070         return CompilerType(
2071             ast, ast->getConstantArrayType(ClangUtil::GetQualType(element_type),
2072                                            ap_element_count,
2073                                            clang::ArrayType::Normal, 0));
2074       }
2075     }
2076   }
2077   return CompilerType();
2078 }
2079
2080 CompilerType ClangASTContext::CreateStructForIdentifier(
2081     const ConstString &type_name,
2082     const std::initializer_list<std::pair<const char *, CompilerType>>
2083         &type_fields,
2084     bool packed) {
2085   CompilerType type;
2086   if (!type_name.IsEmpty() &&
2087       (type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name))
2088           .IsValid()) {
2089     lldbassert(0 && "Trying to create a type for an existing name");
2090     return type;
2091   }
2092
2093   type = CreateRecordType(nullptr, lldb::eAccessPublic, type_name.GetCString(),
2094                           clang::TTK_Struct, lldb::eLanguageTypeC);
2095   StartTagDeclarationDefinition(type);
2096   for (const auto &field : type_fields)
2097     AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic,
2098                          0);
2099   if (packed)
2100     SetIsPacked(type);
2101   CompleteTagDeclarationDefinition(type);
2102   return type;
2103 }
2104
2105 CompilerType ClangASTContext::GetOrCreateStructForIdentifier(
2106     const ConstString &type_name,
2107     const std::initializer_list<std::pair<const char *, CompilerType>>
2108         &type_fields,
2109     bool packed) {
2110   CompilerType type;
2111   if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid())
2112     return type;
2113
2114   return CreateStructForIdentifier(type_name, type_fields, packed);
2115 }
2116
2117 #pragma mark Enumeration Types
2118
2119 CompilerType
2120 ClangASTContext::CreateEnumerationType(const char *name, DeclContext *decl_ctx,
2121                                        const Declaration &decl,
2122                                        const CompilerType &integer_clang_type,
2123                                        bool is_scoped) {
2124   // TODO: Do something intelligent with the Declaration object passed in
2125   // like maybe filling in the SourceLocation with it...
2126   ASTContext *ast = getASTContext();
2127
2128   // TODO: ask about these...
2129   //    const bool IsFixed = false;
2130
2131   EnumDecl *enum_decl = EnumDecl::Create(
2132       *ast, decl_ctx, SourceLocation(), SourceLocation(),
2133       name && name[0] ? &ast->Idents.get(name) : nullptr, nullptr,
2134       is_scoped, // IsScoped
2135       is_scoped, // IsScopedUsingClassTag
2136       false);    // IsFixed
2137
2138   if (enum_decl) {
2139     // TODO: check if we should be setting the promotion type too?
2140     enum_decl->setIntegerType(ClangUtil::GetQualType(integer_clang_type));
2141
2142     enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
2143
2144     return CompilerType(ast, ast->getTagDeclType(enum_decl));
2145   }
2146   return CompilerType();
2147 }
2148
2149 CompilerType ClangASTContext::GetIntTypeFromBitSize(clang::ASTContext *ast,
2150                                                     size_t bit_size,
2151                                                     bool is_signed) {
2152   if (ast) {
2153     if (is_signed) {
2154       if (bit_size == ast->getTypeSize(ast->SignedCharTy))
2155         return CompilerType(ast, ast->SignedCharTy);
2156
2157       if (bit_size == ast->getTypeSize(ast->ShortTy))
2158         return CompilerType(ast, ast->ShortTy);
2159
2160       if (bit_size == ast->getTypeSize(ast->IntTy))
2161         return CompilerType(ast, ast->IntTy);
2162
2163       if (bit_size == ast->getTypeSize(ast->LongTy))
2164         return CompilerType(ast, ast->LongTy);
2165
2166       if (bit_size == ast->getTypeSize(ast->LongLongTy))
2167         return CompilerType(ast, ast->LongLongTy);
2168
2169       if (bit_size == ast->getTypeSize(ast->Int128Ty))
2170         return CompilerType(ast, ast->Int128Ty);
2171     } else {
2172       if (bit_size == ast->getTypeSize(ast->UnsignedCharTy))
2173         return CompilerType(ast, ast->UnsignedCharTy);
2174
2175       if (bit_size == ast->getTypeSize(ast->UnsignedShortTy))
2176         return CompilerType(ast, ast->UnsignedShortTy);
2177
2178       if (bit_size == ast->getTypeSize(ast->UnsignedIntTy))
2179         return CompilerType(ast, ast->UnsignedIntTy);
2180
2181       if (bit_size == ast->getTypeSize(ast->UnsignedLongTy))
2182         return CompilerType(ast, ast->UnsignedLongTy);
2183
2184       if (bit_size == ast->getTypeSize(ast->UnsignedLongLongTy))
2185         return CompilerType(ast, ast->UnsignedLongLongTy);
2186
2187       if (bit_size == ast->getTypeSize(ast->UnsignedInt128Ty))
2188         return CompilerType(ast, ast->UnsignedInt128Ty);
2189     }
2190   }
2191   return CompilerType();
2192 }
2193
2194 CompilerType ClangASTContext::GetPointerSizedIntType(clang::ASTContext *ast,
2195                                                      bool is_signed) {
2196   if (ast)
2197     return GetIntTypeFromBitSize(ast, ast->getTypeSize(ast->VoidPtrTy),
2198                                  is_signed);
2199   return CompilerType();
2200 }
2201
2202 void ClangASTContext::DumpDeclContextHiearchy(clang::DeclContext *decl_ctx) {
2203   if (decl_ctx) {
2204     DumpDeclContextHiearchy(decl_ctx->getParent());
2205
2206     clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl_ctx);
2207     if (named_decl) {
2208       printf("%20s: %s\n", decl_ctx->getDeclKindName(),
2209              named_decl->getDeclName().getAsString().c_str());
2210     } else {
2211       printf("%20s\n", decl_ctx->getDeclKindName());
2212     }
2213   }
2214 }
2215
2216 void ClangASTContext::DumpDeclHiearchy(clang::Decl *decl) {
2217   if (decl == nullptr)
2218     return;
2219   DumpDeclContextHiearchy(decl->getDeclContext());
2220
2221   clang::RecordDecl *record_decl = llvm::dyn_cast<clang::RecordDecl>(decl);
2222   if (record_decl) {
2223     printf("%20s: %s%s\n", decl->getDeclKindName(),
2224            record_decl->getDeclName().getAsString().c_str(),
2225            record_decl->isInjectedClassName() ? " (injected class name)" : "");
2226
2227   } else {
2228     clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl);
2229     if (named_decl) {
2230       printf("%20s: %s\n", decl->getDeclKindName(),
2231              named_decl->getDeclName().getAsString().c_str());
2232     } else {
2233       printf("%20s\n", decl->getDeclKindName());
2234     }
2235   }
2236 }
2237
2238 bool ClangASTContext::DeclsAreEquivalent(clang::Decl *lhs_decl,
2239                                          clang::Decl *rhs_decl) {
2240   if (lhs_decl && rhs_decl) {
2241     //----------------------------------------------------------------------
2242     // Make sure the decl kinds match first
2243     //----------------------------------------------------------------------
2244     const clang::Decl::Kind lhs_decl_kind = lhs_decl->getKind();
2245     const clang::Decl::Kind rhs_decl_kind = rhs_decl->getKind();
2246
2247     if (lhs_decl_kind == rhs_decl_kind) {
2248       //------------------------------------------------------------------
2249       // Now check that the decl contexts kinds are all equivalent before we
2250       // have to check any names of the decl contexts...
2251       //------------------------------------------------------------------
2252       clang::DeclContext *lhs_decl_ctx = lhs_decl->getDeclContext();
2253       clang::DeclContext *rhs_decl_ctx = rhs_decl->getDeclContext();
2254       if (lhs_decl_ctx && rhs_decl_ctx) {
2255         while (1) {
2256           if (lhs_decl_ctx && rhs_decl_ctx) {
2257             const clang::Decl::Kind lhs_decl_ctx_kind =
2258                 lhs_decl_ctx->getDeclKind();
2259             const clang::Decl::Kind rhs_decl_ctx_kind =
2260                 rhs_decl_ctx->getDeclKind();
2261             if (lhs_decl_ctx_kind == rhs_decl_ctx_kind) {
2262               lhs_decl_ctx = lhs_decl_ctx->getParent();
2263               rhs_decl_ctx = rhs_decl_ctx->getParent();
2264
2265               if (lhs_decl_ctx == nullptr && rhs_decl_ctx == nullptr)
2266                 break;
2267             } else
2268               return false;
2269           } else
2270             return false;
2271         }
2272
2273         //--------------------------------------------------------------
2274         // Now make sure the name of the decls match
2275         //--------------------------------------------------------------
2276         clang::NamedDecl *lhs_named_decl =
2277             llvm::dyn_cast<clang::NamedDecl>(lhs_decl);
2278         clang::NamedDecl *rhs_named_decl =
2279             llvm::dyn_cast<clang::NamedDecl>(rhs_decl);
2280         if (lhs_named_decl && rhs_named_decl) {
2281           clang::DeclarationName lhs_decl_name = lhs_named_decl->getDeclName();
2282           clang::DeclarationName rhs_decl_name = rhs_named_decl->getDeclName();
2283           if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2284             if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2285               return false;
2286           } else
2287             return false;
2288         } else
2289           return false;
2290
2291         //--------------------------------------------------------------
2292         // We know that the decl context kinds all match, so now we need to
2293         // make sure the names match as well
2294         //--------------------------------------------------------------
2295         lhs_decl_ctx = lhs_decl->getDeclContext();
2296         rhs_decl_ctx = rhs_decl->getDeclContext();
2297         while (1) {
2298           switch (lhs_decl_ctx->getDeclKind()) {
2299           case clang::Decl::TranslationUnit:
2300             // We don't care about the translation unit names
2301             return true;
2302           default: {
2303             clang::NamedDecl *lhs_named_decl =
2304                 llvm::dyn_cast<clang::NamedDecl>(lhs_decl_ctx);
2305             clang::NamedDecl *rhs_named_decl =
2306                 llvm::dyn_cast<clang::NamedDecl>(rhs_decl_ctx);
2307             if (lhs_named_decl && rhs_named_decl) {
2308               clang::DeclarationName lhs_decl_name =
2309                   lhs_named_decl->getDeclName();
2310               clang::DeclarationName rhs_decl_name =
2311                   rhs_named_decl->getDeclName();
2312               if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2313                 if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2314                   return false;
2315               } else
2316                 return false;
2317             } else
2318               return false;
2319           } break;
2320           }
2321           lhs_decl_ctx = lhs_decl_ctx->getParent();
2322           rhs_decl_ctx = rhs_decl_ctx->getParent();
2323         }
2324       }
2325     }
2326   }
2327   return false;
2328 }
2329 bool ClangASTContext::GetCompleteDecl(clang::ASTContext *ast,
2330                                       clang::Decl *decl) {
2331   if (!decl)
2332     return false;
2333
2334   ExternalASTSource *ast_source = ast->getExternalSource();
2335
2336   if (!ast_source)
2337     return false;
2338
2339   if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) {
2340     if (tag_decl->isCompleteDefinition())
2341       return true;
2342
2343     if (!tag_decl->hasExternalLexicalStorage())
2344       return false;
2345
2346     ast_source->CompleteType(tag_decl);
2347
2348     return !tag_decl->getTypeForDecl()->isIncompleteType();
2349   } else if (clang::ObjCInterfaceDecl *objc_interface_decl =
2350                  llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) {
2351     if (objc_interface_decl->getDefinition())
2352       return true;
2353
2354     if (!objc_interface_decl->hasExternalLexicalStorage())
2355       return false;
2356
2357     ast_source->CompleteType(objc_interface_decl);
2358
2359     return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
2360   } else {
2361     return false;
2362   }
2363 }
2364
2365 void ClangASTContext::SetMetadataAsUserID(const void *object,
2366                                           user_id_t user_id) {
2367   ClangASTMetadata meta_data;
2368   meta_data.SetUserID(user_id);
2369   SetMetadata(object, meta_data);
2370 }
2371
2372 void ClangASTContext::SetMetadata(clang::ASTContext *ast, const void *object,
2373                                   ClangASTMetadata &metadata) {
2374   ClangExternalASTSourceCommon *external_source =
2375       ClangExternalASTSourceCommon::Lookup(ast->getExternalSource());
2376
2377   if (external_source)
2378     external_source->SetMetadata(object, metadata);
2379 }
2380
2381 ClangASTMetadata *ClangASTContext::GetMetadata(clang::ASTContext *ast,
2382                                                const void *object) {
2383   ClangExternalASTSourceCommon *external_source =
2384       ClangExternalASTSourceCommon::Lookup(ast->getExternalSource());
2385
2386   if (external_source && external_source->HasMetadata(object))
2387     return external_source->GetMetadata(object);
2388   else
2389     return nullptr;
2390 }
2391
2392 clang::DeclContext *
2393 ClangASTContext::GetAsDeclContext(clang::CXXMethodDecl *cxx_method_decl) {
2394   return llvm::dyn_cast<clang::DeclContext>(cxx_method_decl);
2395 }
2396
2397 clang::DeclContext *
2398 ClangASTContext::GetAsDeclContext(clang::ObjCMethodDecl *objc_method_decl) {
2399   return llvm::dyn_cast<clang::DeclContext>(objc_method_decl);
2400 }
2401
2402 bool ClangASTContext::SetTagTypeKind(clang::QualType tag_qual_type,
2403                                      int kind) const {
2404   const clang::Type *clang_type = tag_qual_type.getTypePtr();
2405   if (clang_type) {
2406     const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(clang_type);
2407     if (tag_type) {
2408       clang::TagDecl *tag_decl =
2409           llvm::dyn_cast<clang::TagDecl>(tag_type->getDecl());
2410       if (tag_decl) {
2411         tag_decl->setTagKind((clang::TagDecl::TagKind)kind);
2412         return true;
2413       }
2414     }
2415   }
2416   return false;
2417 }
2418
2419 bool ClangASTContext::SetDefaultAccessForRecordFields(
2420     clang::RecordDecl *record_decl, int default_accessibility,
2421     int *assigned_accessibilities, size_t num_assigned_accessibilities) {
2422   if (record_decl) {
2423     uint32_t field_idx;
2424     clang::RecordDecl::field_iterator field, field_end;
2425     for (field = record_decl->field_begin(),
2426         field_end = record_decl->field_end(), field_idx = 0;
2427          field != field_end; ++field, ++field_idx) {
2428       // If no accessibility was assigned, assign the correct one
2429       if (field_idx < num_assigned_accessibilities &&
2430           assigned_accessibilities[field_idx] == clang::AS_none)
2431         field->setAccess((clang::AccessSpecifier)default_accessibility);
2432     }
2433     return true;
2434   }
2435   return false;
2436 }
2437
2438 clang::DeclContext *
2439 ClangASTContext::GetDeclContextForType(const CompilerType &type) {
2440   return GetDeclContextForType(ClangUtil::GetQualType(type));
2441 }
2442
2443 clang::DeclContext *
2444 ClangASTContext::GetDeclContextForType(clang::QualType type) {
2445   if (type.isNull())
2446     return nullptr;
2447
2448   clang::QualType qual_type = type.getCanonicalType();
2449   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2450   switch (type_class) {
2451   case clang::Type::ObjCInterface:
2452     return llvm::cast<clang::ObjCObjectType>(qual_type.getTypePtr())
2453         ->getInterface();
2454   case clang::Type::ObjCObjectPointer:
2455     return GetDeclContextForType(
2456         llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
2457             ->getPointeeType());
2458   case clang::Type::Record:
2459     return llvm::cast<clang::RecordType>(qual_type)->getDecl();
2460   case clang::Type::Enum:
2461     return llvm::cast<clang::EnumType>(qual_type)->getDecl();
2462   case clang::Type::Typedef:
2463     return GetDeclContextForType(llvm::cast<clang::TypedefType>(qual_type)
2464                                      ->getDecl()
2465                                      ->getUnderlyingType());
2466   case clang::Type::Auto:
2467     return GetDeclContextForType(
2468         llvm::cast<clang::AutoType>(qual_type)->getDeducedType());
2469   case clang::Type::Elaborated:
2470     return GetDeclContextForType(
2471         llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType());
2472   case clang::Type::Paren:
2473     return GetDeclContextForType(
2474         llvm::cast<clang::ParenType>(qual_type)->desugar());
2475   default:
2476     break;
2477   }
2478   // No DeclContext in this type...
2479   return nullptr;
2480 }
2481
2482 static bool GetCompleteQualType(clang::ASTContext *ast,
2483                                 clang::QualType qual_type,
2484                                 bool allow_completion = true) {
2485   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2486   switch (type_class) {
2487   case clang::Type::ConstantArray:
2488   case clang::Type::IncompleteArray:
2489   case clang::Type::VariableArray: {
2490     const clang::ArrayType *array_type =
2491         llvm::dyn_cast<clang::ArrayType>(qual_type.getTypePtr());
2492
2493     if (array_type)
2494       return GetCompleteQualType(ast, array_type->getElementType(),
2495                                  allow_completion);
2496   } break;
2497   case clang::Type::Record: {
2498     clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2499     if (cxx_record_decl) {
2500       if (cxx_record_decl->hasExternalLexicalStorage()) {
2501         const bool is_complete = cxx_record_decl->isCompleteDefinition();
2502         const bool fields_loaded =
2503             cxx_record_decl->hasLoadedFieldsFromExternalStorage();
2504         if (is_complete && fields_loaded)
2505           return true;
2506
2507         if (!allow_completion)
2508           return false;
2509
2510         // Call the field_begin() accessor to for it to use the external source
2511         // to load the fields...
2512         clang::ExternalASTSource *external_ast_source =
2513             ast->getExternalSource();
2514         if (external_ast_source) {
2515           external_ast_source->CompleteType(cxx_record_decl);
2516           if (cxx_record_decl->isCompleteDefinition()) {
2517             cxx_record_decl->field_begin();
2518             cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
2519           }
2520         }
2521       }
2522     }
2523     const clang::TagType *tag_type =
2524         llvm::cast<clang::TagType>(qual_type.getTypePtr());
2525     return !tag_type->isIncompleteType();
2526   } break;
2527
2528   case clang::Type::Enum: {
2529     const clang::TagType *tag_type =
2530         llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
2531     if (tag_type) {
2532       clang::TagDecl *tag_decl = tag_type->getDecl();
2533       if (tag_decl) {
2534         if (tag_decl->getDefinition())
2535           return true;
2536
2537         if (!allow_completion)
2538           return false;
2539
2540         if (tag_decl->hasExternalLexicalStorage()) {
2541           if (ast) {
2542             clang::ExternalASTSource *external_ast_source =
2543                 ast->getExternalSource();
2544             if (external_ast_source) {
2545               external_ast_source->CompleteType(tag_decl);
2546               return !tag_type->isIncompleteType();
2547             }
2548           }
2549         }
2550         return false;
2551       }
2552     }
2553
2554   } break;
2555   case clang::Type::ObjCObject:
2556   case clang::Type::ObjCInterface: {
2557     const clang::ObjCObjectType *objc_class_type =
2558         llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
2559     if (objc_class_type) {
2560       clang::ObjCInterfaceDecl *class_interface_decl =
2561           objc_class_type->getInterface();
2562       // We currently can't complete objective C types through the newly added
2563       // ASTContext because it only supports TagDecl objects right now...
2564       if (class_interface_decl) {
2565         if (class_interface_decl->getDefinition())
2566           return true;
2567
2568         if (!allow_completion)
2569           return false;
2570
2571         if (class_interface_decl->hasExternalLexicalStorage()) {
2572           if (ast) {
2573             clang::ExternalASTSource *external_ast_source =
2574                 ast->getExternalSource();
2575             if (external_ast_source) {
2576               external_ast_source->CompleteType(class_interface_decl);
2577               return !objc_class_type->isIncompleteType();
2578             }
2579           }
2580         }
2581         return false;
2582       }
2583     }
2584   } break;
2585
2586   case clang::Type::Typedef:
2587     return GetCompleteQualType(ast, llvm::cast<clang::TypedefType>(qual_type)
2588                                         ->getDecl()
2589                                         ->getUnderlyingType(),
2590                                allow_completion);
2591
2592   case clang::Type::Auto:
2593     return GetCompleteQualType(
2594         ast, llvm::cast<clang::AutoType>(qual_type)->getDeducedType(),
2595         allow_completion);
2596
2597   case clang::Type::Elaborated:
2598     return GetCompleteQualType(
2599         ast, llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType(),
2600         allow_completion);
2601
2602   case clang::Type::Paren:
2603     return GetCompleteQualType(
2604         ast, llvm::cast<clang::ParenType>(qual_type)->desugar(),
2605         allow_completion);
2606
2607   case clang::Type::Attributed:
2608     return GetCompleteQualType(
2609         ast, llvm::cast<clang::AttributedType>(qual_type)->getModifiedType(),
2610         allow_completion);
2611
2612   default:
2613     break;
2614   }
2615
2616   return true;
2617 }
2618
2619 static clang::ObjCIvarDecl::AccessControl
2620 ConvertAccessTypeToObjCIvarAccessControl(AccessType access) {
2621   switch (access) {
2622   case eAccessNone:
2623     return clang::ObjCIvarDecl::None;
2624   case eAccessPublic:
2625     return clang::ObjCIvarDecl::Public;
2626   case eAccessPrivate:
2627     return clang::ObjCIvarDecl::Private;
2628   case eAccessProtected:
2629     return clang::ObjCIvarDecl::Protected;
2630   case eAccessPackage:
2631     return clang::ObjCIvarDecl::Package;
2632   }
2633   return clang::ObjCIvarDecl::None;
2634 }
2635
2636 //----------------------------------------------------------------------
2637 // Tests
2638 //----------------------------------------------------------------------
2639
2640 bool ClangASTContext::IsAggregateType(lldb::opaque_compiler_type_t type) {
2641   clang::QualType qual_type(GetCanonicalQualType(type));
2642
2643   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2644   switch (type_class) {
2645   case clang::Type::IncompleteArray:
2646   case clang::Type::VariableArray:
2647   case clang::Type::ConstantArray:
2648   case clang::Type::ExtVector:
2649   case clang::Type::Vector:
2650   case clang::Type::Record:
2651   case clang::Type::ObjCObject:
2652   case clang::Type::ObjCInterface:
2653     return true;
2654   case clang::Type::Auto:
2655     return IsAggregateType(llvm::cast<clang::AutoType>(qual_type)
2656                                ->getDeducedType()
2657                                .getAsOpaquePtr());
2658   case clang::Type::Elaborated:
2659     return IsAggregateType(llvm::cast<clang::ElaboratedType>(qual_type)
2660                                ->getNamedType()
2661                                .getAsOpaquePtr());
2662   case clang::Type::Typedef:
2663     return IsAggregateType(llvm::cast<clang::TypedefType>(qual_type)
2664                                ->getDecl()
2665                                ->getUnderlyingType()
2666                                .getAsOpaquePtr());
2667   case clang::Type::Paren:
2668     return IsAggregateType(
2669         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
2670   default:
2671     break;
2672   }
2673   // The clang type does have a value
2674   return false;
2675 }
2676
2677 bool ClangASTContext::IsAnonymousType(lldb::opaque_compiler_type_t type) {
2678   clang::QualType qual_type(GetCanonicalQualType(type));
2679
2680   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2681   switch (type_class) {
2682   case clang::Type::Record: {
2683     if (const clang::RecordType *record_type =
2684             llvm::dyn_cast_or_null<clang::RecordType>(
2685                 qual_type.getTypePtrOrNull())) {
2686       if (const clang::RecordDecl *record_decl = record_type->getDecl()) {
2687         return record_decl->isAnonymousStructOrUnion();
2688       }
2689     }
2690     break;
2691   }
2692   case clang::Type::Auto:
2693     return IsAnonymousType(llvm::cast<clang::AutoType>(qual_type)
2694                                ->getDeducedType()
2695                                .getAsOpaquePtr());
2696   case clang::Type::Elaborated:
2697     return IsAnonymousType(llvm::cast<clang::ElaboratedType>(qual_type)
2698                                ->getNamedType()
2699                                .getAsOpaquePtr());
2700   case clang::Type::Typedef:
2701     return IsAnonymousType(llvm::cast<clang::TypedefType>(qual_type)
2702                                ->getDecl()
2703                                ->getUnderlyingType()
2704                                .getAsOpaquePtr());
2705   case clang::Type::Paren:
2706     return IsAnonymousType(
2707         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
2708   default:
2709     break;
2710   }
2711   // The clang type does have a value
2712   return false;
2713 }
2714
2715 bool ClangASTContext::IsArrayType(lldb::opaque_compiler_type_t type,
2716                                   CompilerType *element_type_ptr,
2717                                   uint64_t *size, bool *is_incomplete) {
2718   clang::QualType qual_type(GetCanonicalQualType(type));
2719
2720   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2721   switch (type_class) {
2722   default:
2723     break;
2724
2725   case clang::Type::ConstantArray:
2726     if (element_type_ptr)
2727       element_type_ptr->SetCompilerType(
2728           getASTContext(),
2729           llvm::cast<clang::ConstantArrayType>(qual_type)->getElementType());
2730     if (size)
2731       *size = llvm::cast<clang::ConstantArrayType>(qual_type)
2732                   ->getSize()
2733                   .getLimitedValue(ULLONG_MAX);
2734     if (is_incomplete)
2735       *is_incomplete = false;
2736     return true;
2737
2738   case clang::Type::IncompleteArray:
2739     if (element_type_ptr)
2740       element_type_ptr->SetCompilerType(
2741           getASTContext(),
2742           llvm::cast<clang::IncompleteArrayType>(qual_type)->getElementType());
2743     if (size)
2744       *size = 0;
2745     if (is_incomplete)
2746       *is_incomplete = true;
2747     return true;
2748
2749   case clang::Type::VariableArray:
2750     if (element_type_ptr)
2751       element_type_ptr->SetCompilerType(
2752           getASTContext(),
2753           llvm::cast<clang::VariableArrayType>(qual_type)->getElementType());
2754     if (size)
2755       *size = 0;
2756     if (is_incomplete)
2757       *is_incomplete = false;
2758     return true;
2759
2760   case clang::Type::DependentSizedArray:
2761     if (element_type_ptr)
2762       element_type_ptr->SetCompilerType(
2763           getASTContext(), llvm::cast<clang::DependentSizedArrayType>(qual_type)
2764                                ->getElementType());
2765     if (size)
2766       *size = 0;
2767     if (is_incomplete)
2768       *is_incomplete = false;
2769     return true;
2770
2771   case clang::Type::Typedef:
2772     return IsArrayType(llvm::cast<clang::TypedefType>(qual_type)
2773                            ->getDecl()
2774                            ->getUnderlyingType()
2775                            .getAsOpaquePtr(),
2776                        element_type_ptr, size, is_incomplete);
2777   case clang::Type::Auto:
2778     return IsArrayType(llvm::cast<clang::AutoType>(qual_type)
2779                            ->getDeducedType()
2780                            .getAsOpaquePtr(),
2781                        element_type_ptr, size, is_incomplete);
2782   case clang::Type::Elaborated:
2783     return IsArrayType(llvm::cast<clang::ElaboratedType>(qual_type)
2784                            ->getNamedType()
2785                            .getAsOpaquePtr(),
2786                        element_type_ptr, size, is_incomplete);
2787   case clang::Type::Paren:
2788     return IsArrayType(
2789         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
2790         element_type_ptr, size, is_incomplete);
2791   }
2792   if (element_type_ptr)
2793     element_type_ptr->Clear();
2794   if (size)
2795     *size = 0;
2796   if (is_incomplete)
2797     *is_incomplete = false;
2798   return false;
2799 }
2800
2801 bool ClangASTContext::IsVectorType(lldb::opaque_compiler_type_t type,
2802                                    CompilerType *element_type, uint64_t *size) {
2803   clang::QualType qual_type(GetCanonicalQualType(type));
2804
2805   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2806   switch (type_class) {
2807   case clang::Type::Vector: {
2808     const clang::VectorType *vector_type =
2809         qual_type->getAs<clang::VectorType>();
2810     if (vector_type) {
2811       if (size)
2812         *size = vector_type->getNumElements();
2813       if (element_type)
2814         *element_type =
2815             CompilerType(getASTContext(), vector_type->getElementType());
2816     }
2817     return true;
2818   } break;
2819   case clang::Type::ExtVector: {
2820     const clang::ExtVectorType *ext_vector_type =
2821         qual_type->getAs<clang::ExtVectorType>();
2822     if (ext_vector_type) {
2823       if (size)
2824         *size = ext_vector_type->getNumElements();
2825       if (element_type)
2826         *element_type =
2827             CompilerType(getASTContext(), ext_vector_type->getElementType());
2828     }
2829     return true;
2830   }
2831   default:
2832     break;
2833   }
2834   return false;
2835 }
2836
2837 bool ClangASTContext::IsRuntimeGeneratedType(
2838     lldb::opaque_compiler_type_t type) {
2839   clang::DeclContext *decl_ctx = ClangASTContext::GetASTContext(getASTContext())
2840                                      ->GetDeclContextForType(GetQualType(type));
2841   if (!decl_ctx)
2842     return false;
2843
2844   if (!llvm::isa<clang::ObjCInterfaceDecl>(decl_ctx))
2845     return false;
2846
2847   clang::ObjCInterfaceDecl *result_iface_decl =
2848       llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl_ctx);
2849
2850   ClangASTMetadata *ast_metadata =
2851       ClangASTContext::GetMetadata(getASTContext(), result_iface_decl);
2852   if (!ast_metadata)
2853     return false;
2854   return (ast_metadata->GetISAPtr() != 0);
2855 }
2856
2857 bool ClangASTContext::IsCharType(lldb::opaque_compiler_type_t type) {
2858   return GetQualType(type).getUnqualifiedType()->isCharType();
2859 }
2860
2861 bool ClangASTContext::IsCompleteType(lldb::opaque_compiler_type_t type) {
2862   const bool allow_completion = false;
2863   return GetCompleteQualType(getASTContext(), GetQualType(type),
2864                              allow_completion);
2865 }
2866
2867 bool ClangASTContext::IsConst(lldb::opaque_compiler_type_t type) {
2868   return GetQualType(type).isConstQualified();
2869 }
2870
2871 bool ClangASTContext::IsCStringType(lldb::opaque_compiler_type_t type,
2872                                     uint32_t &length) {
2873   CompilerType pointee_or_element_clang_type;
2874   length = 0;
2875   Flags type_flags(GetTypeInfo(type, &pointee_or_element_clang_type));
2876
2877   if (!pointee_or_element_clang_type.IsValid())
2878     return false;
2879
2880   if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer)) {
2881     if (pointee_or_element_clang_type.IsCharType()) {
2882       if (type_flags.Test(eTypeIsArray)) {
2883         // We know the size of the array and it could be a C string since it is
2884         // an array of characters
2885         length = llvm::cast<clang::ConstantArrayType>(
2886                      GetCanonicalQualType(type).getTypePtr())
2887                      ->getSize()
2888                      .getLimitedValue();
2889       }
2890       return true;
2891     }
2892   }
2893   return false;
2894 }
2895
2896 bool ClangASTContext::IsFunctionType(lldb::opaque_compiler_type_t type,
2897                                      bool *is_variadic_ptr) {
2898   if (type) {
2899     clang::QualType qual_type(GetCanonicalQualType(type));
2900
2901     if (qual_type->isFunctionType()) {
2902       if (is_variadic_ptr) {
2903         const clang::FunctionProtoType *function_proto_type =
2904             llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
2905         if (function_proto_type)
2906           *is_variadic_ptr = function_proto_type->isVariadic();
2907         else
2908           *is_variadic_ptr = false;
2909       }
2910       return true;
2911     }
2912
2913     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2914     switch (type_class) {
2915     default:
2916       break;
2917     case clang::Type::Typedef:
2918       return IsFunctionType(llvm::cast<clang::TypedefType>(qual_type)
2919                                 ->getDecl()
2920                                 ->getUnderlyingType()
2921                                 .getAsOpaquePtr(),
2922                             nullptr);
2923     case clang::Type::Auto:
2924       return IsFunctionType(llvm::cast<clang::AutoType>(qual_type)
2925                                 ->getDeducedType()
2926                                 .getAsOpaquePtr(),
2927                             nullptr);
2928     case clang::Type::Elaborated:
2929       return IsFunctionType(llvm::cast<clang::ElaboratedType>(qual_type)
2930                                 ->getNamedType()
2931                                 .getAsOpaquePtr(),
2932                             nullptr);
2933     case clang::Type::Paren:
2934       return IsFunctionType(
2935           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
2936           nullptr);
2937     case clang::Type::LValueReference:
2938     case clang::Type::RValueReference: {
2939       const clang::ReferenceType *reference_type =
2940           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
2941       if (reference_type)
2942         return IsFunctionType(reference_type->getPointeeType().getAsOpaquePtr(),
2943                               nullptr);
2944     } break;
2945     }
2946   }
2947   return false;
2948 }
2949
2950 // Used to detect "Homogeneous Floating-point Aggregates"
2951 uint32_t
2952 ClangASTContext::IsHomogeneousAggregate(lldb::opaque_compiler_type_t type,
2953                                         CompilerType *base_type_ptr) {
2954   if (!type)
2955     return 0;
2956
2957   clang::QualType qual_type(GetCanonicalQualType(type));
2958   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2959   switch (type_class) {
2960   case clang::Type::Record:
2961     if (GetCompleteType(type)) {
2962       const clang::CXXRecordDecl *cxx_record_decl =
2963           qual_type->getAsCXXRecordDecl();
2964       if (cxx_record_decl) {
2965         if (cxx_record_decl->getNumBases() || cxx_record_decl->isDynamicClass())
2966           return 0;
2967       }
2968       const clang::RecordType *record_type =
2969           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
2970       if (record_type) {
2971         const clang::RecordDecl *record_decl = record_type->getDecl();
2972         if (record_decl) {
2973           // We are looking for a structure that contains only floating point
2974           // types
2975           clang::RecordDecl::field_iterator field_pos,
2976               field_end = record_decl->field_end();
2977           uint32_t num_fields = 0;
2978           bool is_hva = false;
2979           bool is_hfa = false;
2980           clang::QualType base_qual_type;
2981           uint64_t base_bitwidth = 0;
2982           for (field_pos = record_decl->field_begin(); field_pos != field_end;
2983                ++field_pos) {
2984             clang::QualType field_qual_type = field_pos->getType();
2985             uint64_t field_bitwidth = getASTContext()->getTypeSize(qual_type);
2986             if (field_qual_type->isFloatingType()) {
2987               if (field_qual_type->isComplexType())
2988                 return 0;
2989               else {
2990                 if (num_fields == 0)
2991                   base_qual_type = field_qual_type;
2992                 else {
2993                   if (is_hva)
2994                     return 0;
2995                   is_hfa = true;
2996                   if (field_qual_type.getTypePtr() !=
2997                       base_qual_type.getTypePtr())
2998                     return 0;
2999                 }
3000               }
3001             } else if (field_qual_type->isVectorType() ||
3002                        field_qual_type->isExtVectorType()) {
3003               if (num_fields == 0) {
3004                 base_qual_type = field_qual_type;
3005                 base_bitwidth = field_bitwidth;
3006               } else {
3007                 if (is_hfa)
3008                   return 0;
3009                 is_hva = true;
3010                 if (base_bitwidth != field_bitwidth)
3011                   return 0;
3012                 if (field_qual_type.getTypePtr() != base_qual_type.getTypePtr())
3013                   return 0;
3014               }
3015             } else
3016               return 0;
3017             ++num_fields;
3018           }
3019           if (base_type_ptr)
3020             *base_type_ptr = CompilerType(getASTContext(), base_qual_type);
3021           return num_fields;
3022         }
3023       }
3024     }
3025     break;
3026
3027   case clang::Type::Typedef:
3028     return IsHomogeneousAggregate(llvm::cast<clang::TypedefType>(qual_type)
3029                                       ->getDecl()
3030                                       ->getUnderlyingType()
3031                                       .getAsOpaquePtr(),
3032                                   base_type_ptr);
3033
3034   case clang::Type::Auto:
3035     return IsHomogeneousAggregate(llvm::cast<clang::AutoType>(qual_type)
3036                                       ->getDeducedType()
3037                                       .getAsOpaquePtr(),
3038                                   base_type_ptr);
3039
3040   case clang::Type::Elaborated:
3041     return IsHomogeneousAggregate(llvm::cast<clang::ElaboratedType>(qual_type)
3042                                       ->getNamedType()
3043                                       .getAsOpaquePtr(),
3044                                   base_type_ptr);
3045   default:
3046     break;
3047   }
3048   return 0;
3049 }
3050
3051 size_t ClangASTContext::GetNumberOfFunctionArguments(
3052     lldb::opaque_compiler_type_t type) {
3053   if (type) {
3054     clang::QualType qual_type(GetCanonicalQualType(type));
3055     const clang::FunctionProtoType *func =
3056         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3057     if (func)
3058       return func->getNumParams();
3059   }
3060   return 0;
3061 }
3062
3063 CompilerType
3064 ClangASTContext::GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type,
3065                                             const size_t index) {
3066   if (type) {
3067     clang::QualType qual_type(GetQualType(type));
3068     const clang::FunctionProtoType *func =
3069         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3070     if (func) {
3071       if (index < func->getNumParams())
3072         return CompilerType(getASTContext(), func->getParamType(index));
3073     }
3074   }
3075   return CompilerType();
3076 }
3077
3078 bool ClangASTContext::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
3079   if (type) {
3080     clang::QualType qual_type(GetCanonicalQualType(type));
3081
3082     if (qual_type->isFunctionPointerType())
3083       return true;
3084
3085     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3086     switch (type_class) {
3087     default:
3088       break;
3089     case clang::Type::Typedef:
3090       return IsFunctionPointerType(llvm::cast<clang::TypedefType>(qual_type)
3091                                        ->getDecl()
3092                                        ->getUnderlyingType()
3093                                        .getAsOpaquePtr());
3094     case clang::Type::Auto:
3095       return IsFunctionPointerType(llvm::cast<clang::AutoType>(qual_type)
3096                                        ->getDeducedType()
3097                                        .getAsOpaquePtr());
3098     case clang::Type::Elaborated:
3099       return IsFunctionPointerType(llvm::cast<clang::ElaboratedType>(qual_type)
3100                                        ->getNamedType()
3101                                        .getAsOpaquePtr());
3102     case clang::Type::Paren:
3103       return IsFunctionPointerType(
3104           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
3105
3106     case clang::Type::LValueReference:
3107     case clang::Type::RValueReference: {
3108       const clang::ReferenceType *reference_type =
3109           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3110       if (reference_type)
3111         return IsFunctionPointerType(
3112             reference_type->getPointeeType().getAsOpaquePtr());
3113     } break;
3114     }
3115   }
3116   return false;
3117 }
3118
3119 bool ClangASTContext::IsBlockPointerType(
3120     lldb::opaque_compiler_type_t type,
3121     CompilerType *function_pointer_type_ptr) {
3122   if (type) {
3123     clang::QualType qual_type(GetCanonicalQualType(type));
3124
3125     if (qual_type->isBlockPointerType()) {
3126       if (function_pointer_type_ptr) {
3127         const clang::BlockPointerType *block_pointer_type =
3128             qual_type->getAs<clang::BlockPointerType>();
3129         QualType pointee_type = block_pointer_type->getPointeeType();
3130         QualType function_pointer_type = m_ast_ap->getPointerType(pointee_type);
3131         *function_pointer_type_ptr =
3132             CompilerType(getASTContext(), function_pointer_type);
3133       }
3134       return true;
3135     }
3136
3137     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3138     switch (type_class) {
3139     default:
3140       break;
3141     case clang::Type::Typedef:
3142       return IsBlockPointerType(llvm::cast<clang::TypedefType>(qual_type)
3143                                     ->getDecl()
3144                                     ->getUnderlyingType()
3145                                     .getAsOpaquePtr(),
3146                                 function_pointer_type_ptr);
3147     case clang::Type::Auto:
3148       return IsBlockPointerType(llvm::cast<clang::AutoType>(qual_type)
3149                                     ->getDeducedType()
3150                                     .getAsOpaquePtr(),
3151                                 function_pointer_type_ptr);
3152     case clang::Type::Elaborated:
3153       return IsBlockPointerType(llvm::cast<clang::ElaboratedType>(qual_type)
3154                                     ->getNamedType()
3155                                     .getAsOpaquePtr(),
3156                                 function_pointer_type_ptr);
3157     case clang::Type::Paren:
3158       return IsBlockPointerType(
3159           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3160           function_pointer_type_ptr);
3161
3162     case clang::Type::LValueReference:
3163     case clang::Type::RValueReference: {
3164       const clang::ReferenceType *reference_type =
3165           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3166       if (reference_type)
3167         return IsBlockPointerType(
3168             reference_type->getPointeeType().getAsOpaquePtr(),
3169             function_pointer_type_ptr);
3170     } break;
3171     }
3172   }
3173   return false;
3174 }
3175
3176 bool ClangASTContext::IsIntegerType(lldb::opaque_compiler_type_t type,
3177                                     bool &is_signed) {
3178   if (!type)
3179     return false;
3180
3181   clang::QualType qual_type(GetCanonicalQualType(type));
3182   const clang::BuiltinType *builtin_type =
3183       llvm::dyn_cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal());
3184
3185   if (builtin_type) {
3186     if (builtin_type->isInteger()) {
3187       is_signed = builtin_type->isSignedInteger();
3188       return true;
3189     }
3190   }
3191
3192   return false;
3193 }
3194
3195 bool ClangASTContext::IsEnumerationType(lldb::opaque_compiler_type_t type,
3196                                         bool &is_signed) {
3197   if (type) {
3198     const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3199         GetCanonicalQualType(type)->getCanonicalTypeInternal());
3200
3201     if (enum_type) {
3202       IsIntegerType(enum_type->getDecl()->getIntegerType().getAsOpaquePtr(),
3203                     is_signed);
3204       return true;
3205     }
3206   }
3207
3208   return false;
3209 }
3210
3211 bool ClangASTContext::IsPointerType(lldb::opaque_compiler_type_t type,
3212                                     CompilerType *pointee_type) {
3213   if (type) {
3214     clang::QualType qual_type(GetCanonicalQualType(type));
3215     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3216     switch (type_class) {
3217     case clang::Type::Builtin:
3218       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3219       default:
3220         break;
3221       case clang::BuiltinType::ObjCId:
3222       case clang::BuiltinType::ObjCClass:
3223         return true;
3224       }
3225       return false;
3226     case clang::Type::ObjCObjectPointer:
3227       if (pointee_type)
3228         pointee_type->SetCompilerType(
3229             getASTContext(), llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3230                                  ->getPointeeType());
3231       return true;
3232     case clang::Type::BlockPointer:
3233       if (pointee_type)
3234         pointee_type->SetCompilerType(
3235             getASTContext(),
3236             llvm::cast<clang::BlockPointerType>(qual_type)->getPointeeType());
3237       return true;
3238     case clang::Type::Pointer:
3239       if (pointee_type)
3240         pointee_type->SetCompilerType(
3241             getASTContext(),
3242             llvm::cast<clang::PointerType>(qual_type)->getPointeeType());
3243       return true;
3244     case clang::Type::MemberPointer:
3245       if (pointee_type)
3246         pointee_type->SetCompilerType(
3247             getASTContext(),
3248             llvm::cast<clang::MemberPointerType>(qual_type)->getPointeeType());
3249       return true;
3250     case clang::Type::Typedef:
3251       return IsPointerType(llvm::cast<clang::TypedefType>(qual_type)
3252                                ->getDecl()
3253                                ->getUnderlyingType()
3254                                .getAsOpaquePtr(),
3255                            pointee_type);
3256     case clang::Type::Auto:
3257       return IsPointerType(llvm::cast<clang::AutoType>(qual_type)
3258                                ->getDeducedType()
3259                                .getAsOpaquePtr(),
3260                            pointee_type);
3261     case clang::Type::Elaborated:
3262       return IsPointerType(llvm::cast<clang::ElaboratedType>(qual_type)
3263                                ->getNamedType()
3264                                .getAsOpaquePtr(),
3265                            pointee_type);
3266     case clang::Type::Paren:
3267       return IsPointerType(
3268           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3269           pointee_type);
3270     default:
3271       break;
3272     }
3273   }
3274   if (pointee_type)
3275     pointee_type->Clear();
3276   return false;
3277 }
3278
3279 bool ClangASTContext::IsPointerOrReferenceType(
3280     lldb::opaque_compiler_type_t type, CompilerType *pointee_type) {
3281   if (type) {
3282     clang::QualType qual_type(GetCanonicalQualType(type));
3283     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3284     switch (type_class) {
3285     case clang::Type::Builtin:
3286       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3287       default:
3288         break;
3289       case clang::BuiltinType::ObjCId:
3290       case clang::BuiltinType::ObjCClass:
3291         return true;
3292       }
3293       return false;
3294     case clang::Type::ObjCObjectPointer:
3295       if (pointee_type)
3296         pointee_type->SetCompilerType(
3297             getASTContext(), llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3298                                  ->getPointeeType());
3299       return true;
3300     case clang::Type::BlockPointer:
3301       if (pointee_type)
3302         pointee_type->SetCompilerType(
3303             getASTContext(),
3304             llvm::cast<clang::BlockPointerType>(qual_type)->getPointeeType());
3305       return true;
3306     case clang::Type::Pointer:
3307       if (pointee_type)
3308         pointee_type->SetCompilerType(
3309             getASTContext(),
3310             llvm::cast<clang::PointerType>(qual_type)->getPointeeType());
3311       return true;
3312     case clang::Type::MemberPointer:
3313       if (pointee_type)
3314         pointee_type->SetCompilerType(
3315             getASTContext(),
3316             llvm::cast<clang::MemberPointerType>(qual_type)->getPointeeType());
3317       return true;
3318     case clang::Type::LValueReference:
3319       if (pointee_type)
3320         pointee_type->SetCompilerType(
3321             getASTContext(),
3322             llvm::cast<clang::LValueReferenceType>(qual_type)->desugar());
3323       return true;
3324     case clang::Type::RValueReference:
3325       if (pointee_type)
3326         pointee_type->SetCompilerType(
3327             getASTContext(),
3328             llvm::cast<clang::RValueReferenceType>(qual_type)->desugar());
3329       return true;
3330     case clang::Type::Typedef:
3331       return IsPointerOrReferenceType(llvm::cast<clang::TypedefType>(qual_type)
3332                                           ->getDecl()
3333                                           ->getUnderlyingType()
3334                                           .getAsOpaquePtr(),
3335                                       pointee_type);
3336     case clang::Type::Auto:
3337       return IsPointerOrReferenceType(llvm::cast<clang::AutoType>(qual_type)
3338                                           ->getDeducedType()
3339                                           .getAsOpaquePtr(),
3340                                       pointee_type);
3341     case clang::Type::Elaborated:
3342       return IsPointerOrReferenceType(
3343           llvm::cast<clang::ElaboratedType>(qual_type)
3344               ->getNamedType()
3345               .getAsOpaquePtr(),
3346           pointee_type);
3347     case clang::Type::Paren:
3348       return IsPointerOrReferenceType(
3349           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3350           pointee_type);
3351     default:
3352       break;
3353     }
3354   }
3355   if (pointee_type)
3356     pointee_type->Clear();
3357   return false;
3358 }
3359
3360 bool ClangASTContext::IsReferenceType(lldb::opaque_compiler_type_t type,
3361                                       CompilerType *pointee_type,
3362                                       bool *is_rvalue) {
3363   if (type) {
3364     clang::QualType qual_type(GetCanonicalQualType(type));
3365     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3366
3367     switch (type_class) {
3368     case clang::Type::LValueReference:
3369       if (pointee_type)
3370         pointee_type->SetCompilerType(
3371             getASTContext(),
3372             llvm::cast<clang::LValueReferenceType>(qual_type)->desugar());
3373       if (is_rvalue)
3374         *is_rvalue = false;
3375       return true;
3376     case clang::Type::RValueReference:
3377       if (pointee_type)
3378         pointee_type->SetCompilerType(
3379             getASTContext(),
3380             llvm::cast<clang::RValueReferenceType>(qual_type)->desugar());
3381       if (is_rvalue)
3382         *is_rvalue = true;
3383       return true;
3384     case clang::Type::Typedef:
3385       return IsReferenceType(llvm::cast<clang::TypedefType>(qual_type)
3386                                  ->getDecl()
3387                                  ->getUnderlyingType()
3388                                  .getAsOpaquePtr(),
3389                              pointee_type, is_rvalue);
3390     case clang::Type::Auto:
3391       return IsReferenceType(llvm::cast<clang::AutoType>(qual_type)
3392                                  ->getDeducedType()
3393                                  .getAsOpaquePtr(),
3394                              pointee_type, is_rvalue);
3395     case clang::Type::Elaborated:
3396       return IsReferenceType(llvm::cast<clang::ElaboratedType>(qual_type)
3397                                  ->getNamedType()
3398                                  .getAsOpaquePtr(),
3399                              pointee_type, is_rvalue);
3400     case clang::Type::Paren:
3401       return IsReferenceType(
3402           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3403           pointee_type, is_rvalue);
3404
3405     default:
3406       break;
3407     }
3408   }
3409   if (pointee_type)
3410     pointee_type->Clear();
3411   return false;
3412 }
3413
3414 bool ClangASTContext::IsFloatingPointType(lldb::opaque_compiler_type_t type,
3415                                           uint32_t &count, bool &is_complex) {
3416   if (type) {
3417     clang::QualType qual_type(GetCanonicalQualType(type));
3418
3419     if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>(
3420             qual_type->getCanonicalTypeInternal())) {
3421       clang::BuiltinType::Kind kind = BT->getKind();
3422       if (kind >= clang::BuiltinType::Float &&
3423           kind <= clang::BuiltinType::LongDouble) {
3424         count = 1;
3425         is_complex = false;
3426         return true;
3427       }
3428     } else if (const clang::ComplexType *CT =
3429                    llvm::dyn_cast<clang::ComplexType>(
3430                        qual_type->getCanonicalTypeInternal())) {
3431       if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count,
3432                               is_complex)) {
3433         count = 2;
3434         is_complex = true;
3435         return true;
3436       }
3437     } else if (const clang::VectorType *VT = llvm::dyn_cast<clang::VectorType>(
3438                    qual_type->getCanonicalTypeInternal())) {
3439       if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count,
3440                               is_complex)) {
3441         count = VT->getNumElements();
3442         is_complex = false;
3443         return true;
3444       }
3445     }
3446   }
3447   count = 0;
3448   is_complex = false;
3449   return false;
3450 }
3451
3452 bool ClangASTContext::IsDefined(lldb::opaque_compiler_type_t type) {
3453   if (!type)
3454     return false;
3455
3456   clang::QualType qual_type(GetQualType(type));
3457   const clang::TagType *tag_type =
3458       llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
3459   if (tag_type) {
3460     clang::TagDecl *tag_decl = tag_type->getDecl();
3461     if (tag_decl)
3462       return tag_decl->isCompleteDefinition();
3463     return false;
3464   } else {
3465     const clang::ObjCObjectType *objc_class_type =
3466         llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
3467     if (objc_class_type) {
3468       clang::ObjCInterfaceDecl *class_interface_decl =
3469           objc_class_type->getInterface();
3470       if (class_interface_decl)
3471         return class_interface_decl->getDefinition() != nullptr;
3472       return false;
3473     }
3474   }
3475   return true;
3476 }
3477
3478 bool ClangASTContext::IsObjCClassType(const CompilerType &type) {
3479   if (type) {
3480     clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3481
3482     const clang::ObjCObjectPointerType *obj_pointer_type =
3483         llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3484
3485     if (obj_pointer_type)
3486       return obj_pointer_type->isObjCClassType();
3487   }
3488   return false;
3489 }
3490
3491 bool ClangASTContext::IsObjCObjectOrInterfaceType(const CompilerType &type) {
3492   if (ClangUtil::IsClangType(type))
3493     return ClangUtil::GetCanonicalQualType(type)->isObjCObjectOrInterfaceType();
3494   return false;
3495 }
3496
3497 bool ClangASTContext::IsClassType(lldb::opaque_compiler_type_t type) {
3498   if (!type)
3499     return false;
3500   clang::QualType qual_type(GetCanonicalQualType(type));
3501   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3502   return (type_class == clang::Type::Record);
3503 }
3504
3505 bool ClangASTContext::IsEnumType(lldb::opaque_compiler_type_t type) {
3506   if (!type)
3507     return false;
3508   clang::QualType qual_type(GetCanonicalQualType(type));
3509   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3510   return (type_class == clang::Type::Enum);
3511 }
3512
3513 bool ClangASTContext::IsPolymorphicClass(lldb::opaque_compiler_type_t type) {
3514   if (type) {
3515     clang::QualType qual_type(GetCanonicalQualType(type));
3516     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3517     switch (type_class) {
3518     case clang::Type::Record:
3519       if (GetCompleteType(type)) {
3520         const clang::RecordType *record_type =
3521             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3522         const clang::RecordDecl *record_decl = record_type->getDecl();
3523         if (record_decl) {
3524           const clang::CXXRecordDecl *cxx_record_decl =
3525               llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
3526           if (cxx_record_decl)
3527             return cxx_record_decl->isPolymorphic();
3528         }