]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp
Import tzdata 2018d
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Plugins / SymbolFile / DWARF / DWARFASTParserClang.cpp
1 //===-- DWARFASTParserClang.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 <stdlib.h>
11
12 #include "DWARFASTParserClang.h"
13 #include "DWARFCompileUnit.h"
14 #include "DWARFDIE.h"
15 #include "DWARFDIECollection.h"
16 #include "DWARFDebugInfo.h"
17 #include "DWARFDeclContext.h"
18 #include "DWARFDefines.h"
19 #include "SymbolFileDWARF.h"
20 #include "SymbolFileDWARFDebugMap.h"
21 #include "UniqueDWARFASTType.h"
22
23 #include "Plugins/Language/ObjC/ObjCLanguage.h"
24 #include "lldb/Core/Module.h"
25 #include "lldb/Core/Value.h"
26 #include "lldb/Host/Host.h"
27 #include "lldb/Interpreter/Args.h"
28 #include "lldb/Symbol/ClangASTImporter.h"
29 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
30 #include "lldb/Symbol/ClangUtil.h"
31 #include "lldb/Symbol/CompileUnit.h"
32 #include "lldb/Symbol/Function.h"
33 #include "lldb/Symbol/ObjectFile.h"
34 #include "lldb/Symbol/SymbolVendor.h"
35 #include "lldb/Symbol/TypeList.h"
36 #include "lldb/Symbol/TypeMap.h"
37 #include "lldb/Target/Language.h"
38 #include "lldb/Utility/LLDBAssert.h"
39 #include "lldb/Utility/Log.h"
40 #include "lldb/Utility/StreamString.h"
41
42 #include "clang/AST/DeclCXX.h"
43 #include "clang/AST/DeclObjC.h"
44
45 #include <map>
46 #include <vector>
47
48 //#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
49
50 #ifdef ENABLE_DEBUG_PRINTF
51 #include <stdio.h>
52 #define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
53 #else
54 #define DEBUG_PRINTF(fmt, ...)
55 #endif
56
57 using namespace lldb;
58 using namespace lldb_private;
59 DWARFASTParserClang::DWARFASTParserClang(ClangASTContext &ast)
60     : m_ast(ast), m_die_to_decl_ctx(), m_decl_ctx_to_die() {}
61
62 DWARFASTParserClang::~DWARFASTParserClang() {}
63
64 static AccessType DW_ACCESS_to_AccessType(uint32_t dwarf_accessibility) {
65   switch (dwarf_accessibility) {
66   case DW_ACCESS_public:
67     return eAccessPublic;
68   case DW_ACCESS_private:
69     return eAccessPrivate;
70   case DW_ACCESS_protected:
71     return eAccessProtected;
72   default:
73     break;
74   }
75   return eAccessNone;
76 }
77
78 static bool DeclKindIsCXXClass(clang::Decl::Kind decl_kind) {
79   switch (decl_kind) {
80   case clang::Decl::CXXRecord:
81   case clang::Decl::ClassTemplateSpecialization:
82     return true;
83   default:
84     break;
85   }
86   return false;
87 }
88
89 struct BitfieldInfo {
90   uint64_t bit_size;
91   uint64_t bit_offset;
92
93   BitfieldInfo()
94       : bit_size(LLDB_INVALID_ADDRESS), bit_offset(LLDB_INVALID_ADDRESS) {}
95
96   void Clear() {
97     bit_size = LLDB_INVALID_ADDRESS;
98     bit_offset = LLDB_INVALID_ADDRESS;
99   }
100
101   bool IsValid() const {
102     return (bit_size != LLDB_INVALID_ADDRESS) &&
103            (bit_offset != LLDB_INVALID_ADDRESS);
104   }
105
106   bool NextBitfieldOffsetIsValid(const uint64_t next_bit_offset) const {
107     if (IsValid()) {
108       // This bitfield info is valid, so any subsequent bitfields
109       // must not overlap and must be at a higher bit offset than
110       // any previous bitfield + size.
111       return (bit_size + bit_offset) <= next_bit_offset;
112     } else {
113       // If the this BitfieldInfo is not valid, then any offset isOK
114       return true;
115     }
116   }
117 };
118
119 ClangASTImporter &DWARFASTParserClang::GetClangASTImporter() {
120   if (!m_clang_ast_importer_ap) {
121     m_clang_ast_importer_ap.reset(new ClangASTImporter);
122   }
123   return *m_clang_ast_importer_ap;
124 }
125
126 TypeSP DWARFASTParserClang::ParseTypeFromDWO(const DWARFDIE &die, Log *log) {
127   ModuleSP dwo_module_sp = die.GetContainingDWOModule();
128   if (dwo_module_sp) {
129     // This type comes from an external DWO module
130     std::vector<CompilerContext> dwo_context;
131     die.GetDWOContext(dwo_context);
132     TypeMap dwo_types;
133     if (dwo_module_sp->GetSymbolVendor()->FindTypes(dwo_context, true,
134                                                     dwo_types)) {
135       const size_t num_dwo_types = dwo_types.GetSize();
136       if (num_dwo_types == 1) {
137         // We found a real definition for this type elsewhere
138         // so lets use it and cache the fact that we found
139         // a complete type for this die
140         TypeSP dwo_type_sp = dwo_types.GetTypeAtIndex(0);
141         if (dwo_type_sp) {
142           lldb_private::CompilerType dwo_type =
143               dwo_type_sp->GetForwardCompilerType();
144
145           lldb_private::CompilerType type =
146               GetClangASTImporter().CopyType(m_ast, dwo_type);
147
148           // printf ("copied_qual_type: ast = %p, clang_type = %p, name =
149           // '%s'\n", m_ast, copied_qual_type.getAsOpaquePtr(),
150           // external_type->GetName().GetCString());
151           if (type) {
152             SymbolFileDWARF *dwarf = die.GetDWARF();
153             TypeSP type_sp(new Type(die.GetID(), dwarf, dwo_type_sp->GetName(),
154                                     dwo_type_sp->GetByteSize(), NULL,
155                                     LLDB_INVALID_UID, Type::eEncodingInvalid,
156                                     &dwo_type_sp->GetDeclaration(), type,
157                                     Type::eResolveStateForward));
158
159             dwarf->GetTypeList()->Insert(type_sp);
160             dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
161             clang::TagDecl *tag_decl = ClangASTContext::GetAsTagDecl(type);
162             if (tag_decl)
163               LinkDeclContextToDIE(tag_decl, die);
164             else {
165               clang::DeclContext *defn_decl_ctx =
166                   GetCachedClangDeclContextForDIE(die);
167               if (defn_decl_ctx)
168                 LinkDeclContextToDIE(defn_decl_ctx, die);
169             }
170             return type_sp;
171           }
172         }
173       }
174     }
175   }
176   return TypeSP();
177 }
178
179 TypeSP DWARFASTParserClang::ParseTypeFromDWARF(const SymbolContext &sc,
180                                                const DWARFDIE &die, Log *log,
181                                                bool *type_is_new_ptr) {
182   TypeSP type_sp;
183
184   if (type_is_new_ptr)
185     *type_is_new_ptr = false;
186
187   AccessType accessibility = eAccessNone;
188   if (die) {
189     SymbolFileDWARF *dwarf = die.GetDWARF();
190     if (log) {
191       DWARFDIE context_die;
192       clang::DeclContext *context =
193           GetClangDeclContextContainingDIE(die, &context_die);
194
195       dwarf->GetObjectFile()->GetModule()->LogMessage(
196           log, "SymbolFileDWARF::ParseType (die = 0x%8.8x, decl_ctx = %p (die "
197                "0x%8.8x)) %s name = '%s')",
198           die.GetOffset(), static_cast<void *>(context),
199           context_die.GetOffset(), die.GetTagAsCString(), die.GetName());
200     }
201     //
202     //        Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
203     //        if (log && dwarf_cu)
204     //        {
205     //            StreamString s;
206     //            die->DumpLocation (this, dwarf_cu, s);
207     //            dwarf->GetObjectFile()->GetModule()->LogMessage (log,
208     //            "SymbolFileDwarf::%s %s", __FUNCTION__, s.GetData());
209     //
210     //        }
211
212     Type *type_ptr = dwarf->GetDIEToType().lookup(die.GetDIE());
213     TypeList *type_list = dwarf->GetTypeList();
214     if (type_ptr == NULL) {
215       if (type_is_new_ptr)
216         *type_is_new_ptr = true;
217
218       const dw_tag_t tag = die.Tag();
219
220       bool is_forward_declaration = false;
221       DWARFAttributes attributes;
222       const char *type_name_cstr = NULL;
223       ConstString type_name_const_str;
224       Type::ResolveState resolve_state = Type::eResolveStateUnresolved;
225       uint64_t byte_size = 0;
226       Declaration decl;
227
228       Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID;
229       CompilerType clang_type;
230       DWARFFormValue form_value;
231
232       dw_attr_t attr;
233
234       switch (tag) {
235       case DW_TAG_typedef:
236       case DW_TAG_base_type:
237       case DW_TAG_pointer_type:
238       case DW_TAG_reference_type:
239       case DW_TAG_rvalue_reference_type:
240       case DW_TAG_const_type:
241       case DW_TAG_restrict_type:
242       case DW_TAG_volatile_type:
243       case DW_TAG_unspecified_type: {
244         // Set a bit that lets us know that we are currently parsing this
245         dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
246
247         const size_t num_attributes = die.GetAttributes(attributes);
248         uint32_t encoding = 0;
249         DWARFFormValue encoding_uid;
250
251         if (num_attributes > 0) {
252           uint32_t i;
253           for (i = 0; i < num_attributes; ++i) {
254             attr = attributes.AttributeAtIndex(i);
255             if (attributes.ExtractFormValueAtIndex(i, form_value)) {
256               switch (attr) {
257               case DW_AT_decl_file:
258                 decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
259                     form_value.Unsigned()));
260                 break;
261               case DW_AT_decl_line:
262                 decl.SetLine(form_value.Unsigned());
263                 break;
264               case DW_AT_decl_column:
265                 decl.SetColumn(form_value.Unsigned());
266                 break;
267               case DW_AT_name:
268
269                 type_name_cstr = form_value.AsCString();
270                 // Work around a bug in llvm-gcc where they give a name to a
271                 // reference type which doesn't
272                 // include the "&"...
273                 if (tag == DW_TAG_reference_type) {
274                   if (strchr(type_name_cstr, '&') == NULL)
275                     type_name_cstr = NULL;
276                 }
277                 if (type_name_cstr)
278                   type_name_const_str.SetCString(type_name_cstr);
279                 break;
280               case DW_AT_byte_size:
281                 byte_size = form_value.Unsigned();
282                 break;
283               case DW_AT_encoding:
284                 encoding = form_value.Unsigned();
285                 break;
286               case DW_AT_type:
287                 encoding_uid = form_value;
288                 break;
289               default:
290               case DW_AT_sibling:
291                 break;
292               }
293             }
294           }
295         }
296
297         if (tag == DW_TAG_typedef && encoding_uid.IsValid()) {
298           // Try to parse a typedef from the DWO file first as modules
299           // can contain typedef'ed structures that have no names like:
300           //
301           //  typedef struct { int a; } Foo;
302           //
303           // In this case we will have a structure with no name and a
304           // typedef named "Foo" that points to this unnamed structure.
305           // The name in the typedef is the only identifier for the struct,
306           // so always try to get typedefs from DWO files if possible.
307           //
308           // The type_sp returned will be empty if the typedef doesn't exist
309           // in a DWO file, so it is cheap to call this function just to check.
310           //
311           // If we don't do this we end up creating a TypeSP that says this
312           // is a typedef to type 0x123 (the DW_AT_type value would be 0x123
313           // in the DW_TAG_typedef), and this is the unnamed structure type.
314           // We will have a hard time tracking down an unnammed structure
315           // type in the module DWO file, so we make sure we don't get into
316           // this situation by always resolving typedefs from the DWO file.
317           const DWARFDIE encoding_die = dwarf->GetDIE(DIERef(encoding_uid));
318
319           // First make sure that the die that this is typedef'ed to _is_
320           // just a declaration (DW_AT_declaration == 1), not a full definition
321           // since template types can't be represented in modules since only
322           // concrete instances of templates are ever emitted and modules
323           // won't contain those
324           if (encoding_die &&
325               encoding_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) ==
326                   1) {
327             type_sp = ParseTypeFromDWO(die, log);
328             if (type_sp)
329               return type_sp;
330           }
331         }
332
333         DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\") type => 0x%8.8lx\n",
334                      die.GetID(), DW_TAG_value_to_name(tag), type_name_cstr,
335                      encoding_uid.Reference());
336
337         switch (tag) {
338         default:
339           break;
340
341         case DW_TAG_unspecified_type:
342           if (strcmp(type_name_cstr, "nullptr_t") == 0 ||
343               strcmp(type_name_cstr, "decltype(nullptr)") == 0) {
344             resolve_state = Type::eResolveStateFull;
345             clang_type = m_ast.GetBasicType(eBasicTypeNullPtr);
346             break;
347           }
348           // Fall through to base type below in case we can handle the type
349           // there...
350           LLVM_FALLTHROUGH;
351
352         case DW_TAG_base_type:
353           resolve_state = Type::eResolveStateFull;
354           clang_type = m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize(
355               type_name_cstr, encoding, byte_size * 8);
356           break;
357
358         case DW_TAG_pointer_type:
359           encoding_data_type = Type::eEncodingIsPointerUID;
360           break;
361         case DW_TAG_reference_type:
362           encoding_data_type = Type::eEncodingIsLValueReferenceUID;
363           break;
364         case DW_TAG_rvalue_reference_type:
365           encoding_data_type = Type::eEncodingIsRValueReferenceUID;
366           break;
367         case DW_TAG_typedef:
368           encoding_data_type = Type::eEncodingIsTypedefUID;
369           break;
370         case DW_TAG_const_type:
371           encoding_data_type = Type::eEncodingIsConstUID;
372           break;
373         case DW_TAG_restrict_type:
374           encoding_data_type = Type::eEncodingIsRestrictUID;
375           break;
376         case DW_TAG_volatile_type:
377           encoding_data_type = Type::eEncodingIsVolatileUID;
378           break;
379         }
380
381         if (!clang_type &&
382             (encoding_data_type == Type::eEncodingIsPointerUID ||
383              encoding_data_type == Type::eEncodingIsTypedefUID) &&
384             sc.comp_unit != NULL) {
385           if (tag == DW_TAG_pointer_type) {
386             DWARFDIE target_die = die.GetReferencedDIE(DW_AT_type);
387
388             if (target_die.GetAttributeValueAsUnsigned(DW_AT_APPLE_block, 0)) {
389               // Blocks have a __FuncPtr inside them which is a pointer to a
390               // function of the proper type.
391
392               for (DWARFDIE child_die = target_die.GetFirstChild();
393                    child_die.IsValid(); child_die = child_die.GetSibling()) {
394                 if (!strcmp(child_die.GetAttributeValueAsString(DW_AT_name, ""),
395                             "__FuncPtr")) {
396                   DWARFDIE function_pointer_type =
397                       child_die.GetReferencedDIE(DW_AT_type);
398
399                   if (function_pointer_type) {
400                     DWARFDIE function_type =
401                         function_pointer_type.GetReferencedDIE(DW_AT_type);
402
403                     bool function_type_is_new_pointer;
404                     TypeSP lldb_function_type_sp = ParseTypeFromDWARF(
405                         sc, function_type, log, &function_type_is_new_pointer);
406
407                     if (lldb_function_type_sp) {
408                       clang_type = m_ast.CreateBlockPointerType(
409                           lldb_function_type_sp->GetForwardCompilerType());
410                       encoding_data_type = Type::eEncodingIsUID;
411                       encoding_uid.Clear();
412                       resolve_state = Type::eResolveStateFull;
413                     }
414                   }
415
416                   break;
417                 }
418               }
419             }
420           }
421
422           bool translation_unit_is_objc =
423               (sc.comp_unit->GetLanguage() == eLanguageTypeObjC ||
424                sc.comp_unit->GetLanguage() == eLanguageTypeObjC_plus_plus);
425
426           if (translation_unit_is_objc) {
427             if (type_name_cstr != NULL) {
428               static ConstString g_objc_type_name_id("id");
429               static ConstString g_objc_type_name_Class("Class");
430               static ConstString g_objc_type_name_selector("SEL");
431
432               if (type_name_const_str == g_objc_type_name_id) {
433                 if (log)
434                   dwarf->GetObjectFile()->GetModule()->LogMessage(
435                       log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' "
436                            "is Objective C 'id' built-in type.",
437                       die.GetOffset(), die.GetTagAsCString(), die.GetName());
438                 clang_type = m_ast.GetBasicType(eBasicTypeObjCID);
439                 encoding_data_type = Type::eEncodingIsUID;
440                 encoding_uid.Clear();
441                 resolve_state = Type::eResolveStateFull;
442
443               } else if (type_name_const_str == g_objc_type_name_Class) {
444                 if (log)
445                   dwarf->GetObjectFile()->GetModule()->LogMessage(
446                       log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' "
447                            "is Objective C 'Class' built-in type.",
448                       die.GetOffset(), die.GetTagAsCString(), die.GetName());
449                 clang_type = m_ast.GetBasicType(eBasicTypeObjCClass);
450                 encoding_data_type = Type::eEncodingIsUID;
451                 encoding_uid.Clear();
452                 resolve_state = Type::eResolveStateFull;
453               } else if (type_name_const_str == g_objc_type_name_selector) {
454                 if (log)
455                   dwarf->GetObjectFile()->GetModule()->LogMessage(
456                       log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' "
457                            "is Objective C 'selector' built-in type.",
458                       die.GetOffset(), die.GetTagAsCString(), die.GetName());
459                 clang_type = m_ast.GetBasicType(eBasicTypeObjCSel);
460                 encoding_data_type = Type::eEncodingIsUID;
461                 encoding_uid.Clear();
462                 resolve_state = Type::eResolveStateFull;
463               }
464             } else if (encoding_data_type == Type::eEncodingIsPointerUID &&
465                        encoding_uid.IsValid()) {
466               // Clang sometimes erroneously emits id as objc_object*.  In that
467               // case we fix up the type to "id".
468
469               const DWARFDIE encoding_die = dwarf->GetDIE(DIERef(encoding_uid));
470
471               if (encoding_die && encoding_die.Tag() == DW_TAG_structure_type) {
472                 if (const char *struct_name = encoding_die.GetName()) {
473                   if (!strcmp(struct_name, "objc_object")) {
474                     if (log)
475                       dwarf->GetObjectFile()->GetModule()->LogMessage(
476                           log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s "
477                                "'%s' is 'objc_object*', which we overrode to "
478                                "'id'.",
479                           die.GetOffset(), die.GetTagAsCString(),
480                           die.GetName());
481                     clang_type = m_ast.GetBasicType(eBasicTypeObjCID);
482                     encoding_data_type = Type::eEncodingIsUID;
483                     encoding_uid.Clear();
484                     resolve_state = Type::eResolveStateFull;
485                   }
486                 }
487               }
488             }
489           }
490         }
491
492         type_sp.reset(
493             new Type(die.GetID(), dwarf, type_name_const_str, byte_size, NULL,
494                      DIERef(encoding_uid).GetUID(dwarf), encoding_data_type,
495                      &decl, clang_type, resolve_state));
496
497         dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
498
499         //                  Type* encoding_type =
500         //                  GetUniquedTypeForDIEOffset(encoding_uid, type_sp,
501         //                  NULL, 0, 0, false);
502         //                  if (encoding_type != NULL)
503         //                  {
504         //                      if (encoding_type != DIE_IS_BEING_PARSED)
505         //                          type_sp->SetEncodingType(encoding_type);
506         //                      else
507         //                          m_indirect_fixups.push_back(type_sp.get());
508         //                  }
509       } break;
510
511       case DW_TAG_structure_type:
512       case DW_TAG_union_type:
513       case DW_TAG_class_type: {
514         // Set a bit that lets us know that we are currently parsing this
515         dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
516         bool byte_size_valid = false;
517
518         LanguageType class_language = eLanguageTypeUnknown;
519         bool is_complete_objc_class = false;
520         // bool struct_is_class = false;
521         const size_t num_attributes = die.GetAttributes(attributes);
522         if (num_attributes > 0) {
523           uint32_t i;
524           for (i = 0; i < num_attributes; ++i) {
525             attr = attributes.AttributeAtIndex(i);
526             if (attributes.ExtractFormValueAtIndex(i, form_value)) {
527               switch (attr) {
528               case DW_AT_decl_file:
529                 if (die.GetCU()->DW_AT_decl_file_attributes_are_invalid()) {
530                   // llvm-gcc outputs invalid DW_AT_decl_file attributes that
531                   // always
532                   // point to the compile unit file, so we clear this invalid
533                   // value
534                   // so that we can still unique types efficiently.
535                   decl.SetFile(FileSpec("<invalid>", false));
536                 } else
537                   decl.SetFile(
538                       sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
539                           form_value.Unsigned()));
540                 break;
541
542               case DW_AT_decl_line:
543                 decl.SetLine(form_value.Unsigned());
544                 break;
545
546               case DW_AT_decl_column:
547                 decl.SetColumn(form_value.Unsigned());
548                 break;
549
550               case DW_AT_name:
551                 type_name_cstr = form_value.AsCString();
552                 type_name_const_str.SetCString(type_name_cstr);
553                 break;
554
555               case DW_AT_byte_size:
556                 byte_size = form_value.Unsigned();
557                 byte_size_valid = true;
558                 break;
559
560               case DW_AT_accessibility:
561                 accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
562                 break;
563
564               case DW_AT_declaration:
565                 is_forward_declaration = form_value.Boolean();
566                 break;
567
568               case DW_AT_APPLE_runtime_class:
569                 class_language = (LanguageType)form_value.Signed();
570                 break;
571
572               case DW_AT_APPLE_objc_complete_type:
573                 is_complete_objc_class = form_value.Signed();
574                 break;
575
576               case DW_AT_allocated:
577               case DW_AT_associated:
578               case DW_AT_data_location:
579               case DW_AT_description:
580               case DW_AT_start_scope:
581               case DW_AT_visibility:
582               default:
583               case DW_AT_sibling:
584                 break;
585               }
586             }
587           }
588         }
589
590         // UniqueDWARFASTType is large, so don't create a local variables on the
591         // stack, put it on the heap. This function is often called recursively
592         // and clang isn't good and sharing the stack space for variables in
593         // different blocks.
594         std::unique_ptr<UniqueDWARFASTType> unique_ast_entry_ap(
595             new UniqueDWARFASTType());
596
597         ConstString unique_typename(type_name_const_str);
598         Declaration unique_decl(decl);
599
600         if (type_name_const_str) {
601           LanguageType die_language = die.GetLanguage();
602           if (Language::LanguageIsCPlusPlus(die_language)) {
603             // For C++, we rely solely upon the one definition rule that says
604             // only
605             // one thing can exist at a given decl context. We ignore the file
606             // and
607             // line that things are declared on.
608             std::string qualified_name;
609             if (die.GetQualifiedName(qualified_name))
610               unique_typename = ConstString(qualified_name);
611             unique_decl.Clear();
612           }
613
614           if (dwarf->GetUniqueDWARFASTTypeMap().Find(
615                   unique_typename, die, unique_decl,
616                   byte_size_valid ? byte_size : -1, *unique_ast_entry_ap)) {
617             type_sp = unique_ast_entry_ap->m_type_sp;
618             if (type_sp) {
619               dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
620               return type_sp;
621             }
622           }
623         }
624
625         DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
626                      DW_TAG_value_to_name(tag), type_name_cstr);
627
628         int tag_decl_kind = -1;
629         AccessType default_accessibility = eAccessNone;
630         if (tag == DW_TAG_structure_type) {
631           tag_decl_kind = clang::TTK_Struct;
632           default_accessibility = eAccessPublic;
633         } else if (tag == DW_TAG_union_type) {
634           tag_decl_kind = clang::TTK_Union;
635           default_accessibility = eAccessPublic;
636         } else if (tag == DW_TAG_class_type) {
637           tag_decl_kind = clang::TTK_Class;
638           default_accessibility = eAccessPrivate;
639         }
640
641         if (byte_size_valid && byte_size == 0 && type_name_cstr &&
642             die.HasChildren() == false &&
643             sc.comp_unit->GetLanguage() == eLanguageTypeObjC) {
644           // Work around an issue with clang at the moment where
645           // forward declarations for objective C classes are emitted
646           // as:
647           //  DW_TAG_structure_type [2]
648           //  DW_AT_name( "ForwardObjcClass" )
649           //  DW_AT_byte_size( 0x00 )
650           //  DW_AT_decl_file( "..." )
651           //  DW_AT_decl_line( 1 )
652           //
653           // Note that there is no DW_AT_declaration and there are
654           // no children, and the byte size is zero.
655           is_forward_declaration = true;
656         }
657
658         if (class_language == eLanguageTypeObjC ||
659             class_language == eLanguageTypeObjC_plus_plus) {
660           if (!is_complete_objc_class &&
661               die.Supports_DW_AT_APPLE_objc_complete_type()) {
662             // We have a valid eSymbolTypeObjCClass class symbol whose
663             // name matches the current objective C class that we
664             // are trying to find and this DIE isn't the complete
665             // definition (we checked is_complete_objc_class above and
666             // know it is false), so the real definition is in here somewhere
667             type_sp = dwarf->FindCompleteObjCDefinitionTypeForDIE(
668                 die, type_name_const_str, true);
669
670             if (!type_sp) {
671               SymbolFileDWARFDebugMap *debug_map_symfile =
672                   dwarf->GetDebugMapSymfile();
673               if (debug_map_symfile) {
674                 // We weren't able to find a full declaration in
675                 // this DWARF, see if we have a declaration anywhere
676                 // else...
677                 type_sp =
678                     debug_map_symfile->FindCompleteObjCDefinitionTypeForDIE(
679                         die, type_name_const_str, true);
680               }
681             }
682
683             if (type_sp) {
684               if (log) {
685                 dwarf->GetObjectFile()->GetModule()->LogMessage(
686                     log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is an "
687                          "incomplete objc type, complete type is 0x%8.8" PRIx64,
688                     static_cast<void *>(this), die.GetOffset(),
689                     DW_TAG_value_to_name(tag), type_name_cstr,
690                     type_sp->GetID());
691               }
692
693               // We found a real definition for this type elsewhere
694               // so lets use it and cache the fact that we found
695               // a complete type for this die
696               dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
697               return type_sp;
698             }
699           }
700         }
701
702         if (is_forward_declaration) {
703           // We have a forward declaration to a type and we need
704           // to try and find a full declaration. We look in the
705           // current type index just in case we have a forward
706           // declaration followed by an actual declarations in the
707           // DWARF. If this fails, we need to look elsewhere...
708           if (log) {
709             dwarf->GetObjectFile()->GetModule()->LogMessage(
710                 log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a "
711                      "forward declaration, trying to find complete type",
712                 static_cast<void *>(this), die.GetOffset(),
713                 DW_TAG_value_to_name(tag), type_name_cstr);
714           }
715
716           // See if the type comes from a DWO module and if so, track down that
717           // type.
718           type_sp = ParseTypeFromDWO(die, log);
719           if (type_sp)
720             return type_sp;
721
722           DWARFDeclContext die_decl_ctx;
723           die.GetDWARFDeclContext(die_decl_ctx);
724
725           // type_sp = FindDefinitionTypeForDIE (dwarf_cu, die,
726           // type_name_const_str);
727           type_sp = dwarf->FindDefinitionTypeForDWARFDeclContext(die_decl_ctx);
728
729           if (!type_sp) {
730             SymbolFileDWARFDebugMap *debug_map_symfile =
731                 dwarf->GetDebugMapSymfile();
732             if (debug_map_symfile) {
733               // We weren't able to find a full declaration in
734               // this DWARF, see if we have a declaration anywhere
735               // else...
736               type_sp =
737                   debug_map_symfile->FindDefinitionTypeForDWARFDeclContext(
738                       die_decl_ctx);
739             }
740           }
741
742           if (type_sp) {
743             if (log) {
744               dwarf->GetObjectFile()->GetModule()->LogMessage(
745                   log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a "
746                        "forward declaration, complete type is 0x%8.8" PRIx64,
747                   static_cast<void *>(this), die.GetOffset(),
748                   DW_TAG_value_to_name(tag), type_name_cstr, type_sp->GetID());
749             }
750
751             // We found a real definition for this type elsewhere
752             // so lets use it and cache the fact that we found
753             // a complete type for this die
754             dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
755             clang::DeclContext *defn_decl_ctx = GetCachedClangDeclContextForDIE(
756                 dwarf->DebugInfo()->GetDIE(DIERef(type_sp->GetID(), dwarf)));
757             if (defn_decl_ctx)
758               LinkDeclContextToDIE(defn_decl_ctx, die);
759             return type_sp;
760           }
761         }
762         assert(tag_decl_kind != -1);
763         bool clang_type_was_created = false;
764         clang_type.SetCompilerType(
765             &m_ast, dwarf->GetForwardDeclDieToClangType().lookup(die.GetDIE()));
766         if (!clang_type) {
767           clang::DeclContext *decl_ctx =
768               GetClangDeclContextContainingDIE(die, nullptr);
769           if (accessibility == eAccessNone && decl_ctx) {
770             // Check the decl context that contains this class/struct/union.
771             // If it is a class we must give it an accessibility.
772             const clang::Decl::Kind containing_decl_kind =
773                 decl_ctx->getDeclKind();
774             if (DeclKindIsCXXClass(containing_decl_kind))
775               accessibility = default_accessibility;
776           }
777
778           ClangASTMetadata metadata;
779           metadata.SetUserID(die.GetID());
780           metadata.SetIsDynamicCXXType(dwarf->ClassOrStructIsVirtual(die));
781
782           if (type_name_cstr && strchr(type_name_cstr, '<')) {
783             ClangASTContext::TemplateParameterInfos template_param_infos;
784             if (ParseTemplateParameterInfos(die, template_param_infos)) {
785               clang::ClassTemplateDecl *class_template_decl =
786                   m_ast.ParseClassTemplateDecl(decl_ctx, accessibility,
787                                                type_name_cstr, tag_decl_kind,
788                                                template_param_infos);
789               if (!class_template_decl) {
790                 if (log) {
791                   dwarf->GetObjectFile()->GetModule()->LogMessage(
792                     log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" "
793                          "clang::ClassTemplateDecl failed to return a decl.",
794                     static_cast<void *>(this), die.GetOffset(),
795                     DW_TAG_value_to_name(tag), type_name_cstr);
796                 }
797                 return TypeSP();
798               }
799                 
800               clang::ClassTemplateSpecializationDecl
801                   *class_specialization_decl =
802                       m_ast.CreateClassTemplateSpecializationDecl(
803                           decl_ctx, class_template_decl, tag_decl_kind,
804                           template_param_infos);
805               clang_type = m_ast.CreateClassTemplateSpecializationType(
806                   class_specialization_decl);
807               clang_type_was_created = true;
808
809               m_ast.SetMetadata(class_template_decl, metadata);
810               m_ast.SetMetadata(class_specialization_decl, metadata);
811             }
812           }
813
814           if (!clang_type_was_created) {
815             clang_type_was_created = true;
816             clang_type = m_ast.CreateRecordType(decl_ctx, accessibility,
817                                                 type_name_cstr, tag_decl_kind,
818                                                 class_language, &metadata);
819           }
820         }
821
822         // Store a forward declaration to this class type in case any
823         // parameters in any class methods need it for the clang
824         // types for function prototypes.
825         LinkDeclContextToDIE(m_ast.GetDeclContextForType(clang_type), die);
826         type_sp.reset(new Type(die.GetID(), dwarf, type_name_const_str,
827                                byte_size, NULL, LLDB_INVALID_UID,
828                                Type::eEncodingIsUID, &decl, clang_type,
829                                Type::eResolveStateForward));
830
831         type_sp->SetIsCompleteObjCClass(is_complete_objc_class);
832
833         // Add our type to the unique type map so we don't
834         // end up creating many copies of the same type over
835         // and over in the ASTContext for our module
836         unique_ast_entry_ap->m_type_sp = type_sp;
837         unique_ast_entry_ap->m_die = die;
838         unique_ast_entry_ap->m_declaration = unique_decl;
839         unique_ast_entry_ap->m_byte_size = byte_size;
840         dwarf->GetUniqueDWARFASTTypeMap().Insert(unique_typename,
841                                                  *unique_ast_entry_ap);
842
843         if (is_forward_declaration && die.HasChildren()) {
844           // Check to see if the DIE actually has a definition, some version of
845           // GCC will
846           // emit DIEs with DW_AT_declaration set to true, but yet still have
847           // subprogram,
848           // members, or inheritance, so we can't trust it
849           DWARFDIE child_die = die.GetFirstChild();
850           while (child_die) {
851             switch (child_die.Tag()) {
852             case DW_TAG_inheritance:
853             case DW_TAG_subprogram:
854             case DW_TAG_member:
855             case DW_TAG_APPLE_property:
856             case DW_TAG_class_type:
857             case DW_TAG_structure_type:
858             case DW_TAG_enumeration_type:
859             case DW_TAG_typedef:
860             case DW_TAG_union_type:
861               child_die.Clear();
862               is_forward_declaration = false;
863               break;
864             default:
865               child_die = child_die.GetSibling();
866               break;
867             }
868           }
869         }
870
871         if (!is_forward_declaration) {
872           // Always start the definition for a class type so that
873           // if the class has child classes or types that require
874           // the class to be created for use as their decl contexts
875           // the class will be ready to accept these child definitions.
876           if (die.HasChildren() == false) {
877             // No children for this struct/union/class, lets finish it
878             if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) {
879               ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
880             } else {
881               dwarf->GetObjectFile()->GetModule()->ReportError(
882                   "DWARF DIE at 0x%8.8x named \"%s\" was not able to start its "
883                   "definition.\nPlease file a bug and attach the file at the "
884                   "start of this error message",
885                   die.GetOffset(), type_name_cstr);
886             }
887
888             if (tag == DW_TAG_structure_type) // this only applies in C
889             {
890               clang::RecordDecl *record_decl =
891                   ClangASTContext::GetAsRecordDecl(clang_type);
892
893               if (record_decl) {
894                 GetClangASTImporter().InsertRecordDecl(
895                     record_decl, ClangASTImporter::LayoutInfo());
896               }
897             }
898           } else if (clang_type_was_created) {
899             // Start the definition if the class is not objective C since
900             // the underlying decls respond to isCompleteDefinition(). Objective
901             // C decls don't respond to isCompleteDefinition() so we can't
902             // start the declaration definition right away. For C++
903             // class/union/structs
904             // we want to start the definition in case the class is needed as
905             // the
906             // declaration context for a contained class or type without the
907             // need
908             // to complete that type..
909
910             if (class_language != eLanguageTypeObjC &&
911                 class_language != eLanguageTypeObjC_plus_plus)
912               ClangASTContext::StartTagDeclarationDefinition(clang_type);
913
914             // Leave this as a forward declaration until we need
915             // to know the details of the type. lldb_private::Type
916             // will automatically call the SymbolFile virtual function
917             // "SymbolFileDWARF::CompleteType(Type *)"
918             // When the definition needs to be defined.
919             assert(!dwarf->GetForwardDeclClangTypeToDie().count(
920                        ClangUtil::RemoveFastQualifiers(clang_type)
921                            .GetOpaqueQualType()) &&
922                    "Type already in the forward declaration map!");
923             // Can't assume m_ast.GetSymbolFile() is actually a SymbolFileDWARF,
924             // it can be a
925             // SymbolFileDWARFDebugMap for Apple binaries.
926             dwarf->GetForwardDeclDieToClangType()[die.GetDIE()] =
927                 clang_type.GetOpaqueQualType();
928             dwarf->GetForwardDeclClangTypeToDie()
929                 [ClangUtil::RemoveFastQualifiers(clang_type)
930                      .GetOpaqueQualType()] = die.GetDIERef();
931             m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), true);
932           }
933         }
934       } break;
935
936       case DW_TAG_enumeration_type: {
937         // Set a bit that lets us know that we are currently parsing this
938         dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
939
940         bool is_scoped = false;
941         DWARFFormValue encoding_form;
942
943         const size_t num_attributes = die.GetAttributes(attributes);
944         if (num_attributes > 0) {
945           uint32_t i;
946
947           for (i = 0; i < num_attributes; ++i) {
948             attr = attributes.AttributeAtIndex(i);
949             if (attributes.ExtractFormValueAtIndex(i, form_value)) {
950               switch (attr) {
951               case DW_AT_decl_file:
952                 decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
953                     form_value.Unsigned()));
954                 break;
955               case DW_AT_decl_line:
956                 decl.SetLine(form_value.Unsigned());
957                 break;
958               case DW_AT_decl_column:
959                 decl.SetColumn(form_value.Unsigned());
960                 break;
961               case DW_AT_name:
962                 type_name_cstr = form_value.AsCString();
963                 type_name_const_str.SetCString(type_name_cstr);
964                 break;
965               case DW_AT_type:
966                 encoding_form = form_value;
967                 break;
968               case DW_AT_byte_size:
969                 byte_size = form_value.Unsigned();
970                 break;
971               case DW_AT_accessibility:
972                 break; // accessibility =
973                        // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
974               case DW_AT_declaration:
975                 is_forward_declaration = form_value.Boolean();
976                 break;
977               case DW_AT_enum_class:
978                 is_scoped = form_value.Boolean();
979                 break;
980               case DW_AT_allocated:
981               case DW_AT_associated:
982               case DW_AT_bit_stride:
983               case DW_AT_byte_stride:
984               case DW_AT_data_location:
985               case DW_AT_description:
986               case DW_AT_start_scope:
987               case DW_AT_visibility:
988               case DW_AT_specification:
989               case DW_AT_abstract_origin:
990               case DW_AT_sibling:
991                 break;
992               }
993             }
994           }
995
996           if (is_forward_declaration) {
997             type_sp = ParseTypeFromDWO(die, log);
998             if (type_sp)
999               return type_sp;
1000
1001             DWARFDeclContext die_decl_ctx;
1002             die.GetDWARFDeclContext(die_decl_ctx);
1003
1004             type_sp =
1005                 dwarf->FindDefinitionTypeForDWARFDeclContext(die_decl_ctx);
1006
1007             if (!type_sp) {
1008               SymbolFileDWARFDebugMap *debug_map_symfile =
1009                   dwarf->GetDebugMapSymfile();
1010               if (debug_map_symfile) {
1011                 // We weren't able to find a full declaration in
1012                 // this DWARF, see if we have a declaration anywhere
1013                 // else...
1014                 type_sp =
1015                     debug_map_symfile->FindDefinitionTypeForDWARFDeclContext(
1016                         die_decl_ctx);
1017               }
1018             }
1019
1020             if (type_sp) {
1021               if (log) {
1022                 dwarf->GetObjectFile()->GetModule()->LogMessage(
1023                     log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a "
1024                          "forward declaration, complete type is 0x%8.8" PRIx64,
1025                     static_cast<void *>(this), die.GetOffset(),
1026                     DW_TAG_value_to_name(tag), type_name_cstr,
1027                     type_sp->GetID());
1028               }
1029
1030               // We found a real definition for this type elsewhere
1031               // so lets use it and cache the fact that we found
1032               // a complete type for this die
1033               dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
1034               clang::DeclContext *defn_decl_ctx =
1035                   GetCachedClangDeclContextForDIE(dwarf->DebugInfo()->GetDIE(
1036                       DIERef(type_sp->GetID(), dwarf)));
1037               if (defn_decl_ctx)
1038                 LinkDeclContextToDIE(defn_decl_ctx, die);
1039               return type_sp;
1040             }
1041           }
1042           DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
1043                        DW_TAG_value_to_name(tag), type_name_cstr);
1044
1045           CompilerType enumerator_clang_type;
1046           clang_type.SetCompilerType(
1047               &m_ast,
1048               dwarf->GetForwardDeclDieToClangType().lookup(die.GetDIE()));
1049           if (!clang_type) {
1050             if (encoding_form.IsValid()) {
1051               Type *enumerator_type =
1052                   dwarf->ResolveTypeUID(DIERef(encoding_form));
1053               if (enumerator_type)
1054                 enumerator_clang_type = enumerator_type->GetFullCompilerType();
1055             }
1056
1057             if (!enumerator_clang_type) {
1058               if (byte_size > 0) {
1059                 enumerator_clang_type =
1060                     m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize(
1061                         NULL, DW_ATE_signed, byte_size * 8);
1062               } else {
1063                 enumerator_clang_type = m_ast.GetBasicType(eBasicTypeInt);
1064               }
1065             }
1066
1067             clang_type = m_ast.CreateEnumerationType(
1068                 type_name_cstr, GetClangDeclContextContainingDIE(die, nullptr),
1069                 decl, enumerator_clang_type, is_scoped);
1070           } else {
1071             enumerator_clang_type =
1072                 m_ast.GetEnumerationIntegerType(clang_type.GetOpaqueQualType());
1073           }
1074
1075           LinkDeclContextToDIE(
1076               ClangASTContext::GetDeclContextForType(clang_type), die);
1077
1078           type_sp.reset(new Type(
1079               die.GetID(), dwarf, type_name_const_str, byte_size, NULL,
1080               DIERef(encoding_form).GetUID(dwarf), Type::eEncodingIsUID, &decl,
1081               clang_type, Type::eResolveStateForward));
1082
1083           if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) {
1084             if (die.HasChildren()) {
1085               SymbolContext cu_sc(die.GetLLDBCompileUnit());
1086               bool is_signed = false;
1087               enumerator_clang_type.IsIntegerType(is_signed);
1088               ParseChildEnumerators(cu_sc, clang_type, is_signed,
1089                                     type_sp->GetByteSize(), die);
1090             }
1091             ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
1092           } else {
1093             dwarf->GetObjectFile()->GetModule()->ReportError(
1094                 "DWARF DIE at 0x%8.8x named \"%s\" was not able to start its "
1095                 "definition.\nPlease file a bug and attach the file at the "
1096                 "start of this error message",
1097                 die.GetOffset(), type_name_cstr);
1098           }
1099         }
1100       } break;
1101
1102       case DW_TAG_inlined_subroutine:
1103       case DW_TAG_subprogram:
1104       case DW_TAG_subroutine_type: {
1105         // Set a bit that lets us know that we are currently parsing this
1106         dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
1107
1108         DWARFFormValue type_die_form;
1109         bool is_variadic = false;
1110         bool is_inline = false;
1111         bool is_static = false;
1112         bool is_virtual = false;
1113         bool is_explicit = false;
1114         bool is_artificial = false;
1115         bool has_template_params = false;
1116         DWARFFormValue specification_die_form;
1117         DWARFFormValue abstract_origin_die_form;
1118         dw_offset_t object_pointer_die_offset = DW_INVALID_OFFSET;
1119
1120         unsigned type_quals = 0;
1121         clang::StorageClass storage =
1122             clang::SC_None; //, Extern, Static, PrivateExtern
1123
1124         const size_t num_attributes = die.GetAttributes(attributes);
1125         if (num_attributes > 0) {
1126           uint32_t i;
1127           for (i = 0; i < num_attributes; ++i) {
1128             attr = attributes.AttributeAtIndex(i);
1129             if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1130               switch (attr) {
1131               case DW_AT_decl_file:
1132                 decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
1133                     form_value.Unsigned()));
1134                 break;
1135               case DW_AT_decl_line:
1136                 decl.SetLine(form_value.Unsigned());
1137                 break;
1138               case DW_AT_decl_column:
1139                 decl.SetColumn(form_value.Unsigned());
1140                 break;
1141               case DW_AT_name:
1142                 type_name_cstr = form_value.AsCString();
1143                 type_name_const_str.SetCString(type_name_cstr);
1144                 break;
1145
1146               case DW_AT_linkage_name:
1147               case DW_AT_MIPS_linkage_name:
1148                 break; // mangled =
1149                        // form_value.AsCString(&dwarf->get_debug_str_data());
1150                        // break;
1151               case DW_AT_type:
1152                 type_die_form = form_value;
1153                 break;
1154               case DW_AT_accessibility:
1155                 accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
1156                 break;
1157               case DW_AT_declaration:
1158                 break; // is_forward_declaration = form_value.Boolean(); break;
1159               case DW_AT_inline:
1160                 is_inline = form_value.Boolean();
1161                 break;
1162               case DW_AT_virtuality:
1163                 is_virtual = form_value.Boolean();
1164                 break;
1165               case DW_AT_explicit:
1166                 is_explicit = form_value.Boolean();
1167                 break;
1168               case DW_AT_artificial:
1169                 is_artificial = form_value.Boolean();
1170                 break;
1171
1172               case DW_AT_external:
1173                 if (form_value.Unsigned()) {
1174                   if (storage == clang::SC_None)
1175                     storage = clang::SC_Extern;
1176                   else
1177                     storage = clang::SC_PrivateExtern;
1178                 }
1179                 break;
1180
1181               case DW_AT_specification:
1182                 specification_die_form = form_value;
1183                 break;
1184
1185               case DW_AT_abstract_origin:
1186                 abstract_origin_die_form = form_value;
1187                 break;
1188
1189               case DW_AT_object_pointer:
1190                 object_pointer_die_offset = form_value.Reference();
1191                 break;
1192
1193               case DW_AT_allocated:
1194               case DW_AT_associated:
1195               case DW_AT_address_class:
1196               case DW_AT_calling_convention:
1197               case DW_AT_data_location:
1198               case DW_AT_elemental:
1199               case DW_AT_entry_pc:
1200               case DW_AT_frame_base:
1201               case DW_AT_high_pc:
1202               case DW_AT_low_pc:
1203               case DW_AT_prototyped:
1204               case DW_AT_pure:
1205               case DW_AT_ranges:
1206               case DW_AT_recursive:
1207               case DW_AT_return_addr:
1208               case DW_AT_segment:
1209               case DW_AT_start_scope:
1210               case DW_AT_static_link:
1211               case DW_AT_trampoline:
1212               case DW_AT_visibility:
1213               case DW_AT_vtable_elem_location:
1214               case DW_AT_description:
1215               case DW_AT_sibling:
1216                 break;
1217               }
1218             }
1219           }
1220         }
1221
1222         std::string object_pointer_name;
1223         if (object_pointer_die_offset != DW_INVALID_OFFSET) {
1224           DWARFDIE object_pointer_die = die.GetDIE(object_pointer_die_offset);
1225           if (object_pointer_die) {
1226             const char *object_pointer_name_cstr = object_pointer_die.GetName();
1227             if (object_pointer_name_cstr)
1228               object_pointer_name = object_pointer_name_cstr;
1229           }
1230         }
1231
1232         DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
1233                      DW_TAG_value_to_name(tag), type_name_cstr);
1234
1235         CompilerType return_clang_type;
1236         Type *func_type = NULL;
1237
1238         if (type_die_form.IsValid())
1239           func_type = dwarf->ResolveTypeUID(DIERef(type_die_form));
1240
1241         if (func_type)
1242           return_clang_type = func_type->GetForwardCompilerType();
1243         else
1244           return_clang_type = m_ast.GetBasicType(eBasicTypeVoid);
1245
1246         std::vector<CompilerType> function_param_types;
1247         std::vector<clang::ParmVarDecl *> function_param_decls;
1248
1249         // Parse the function children for the parameters
1250
1251         DWARFDIE decl_ctx_die;
1252         clang::DeclContext *containing_decl_ctx =
1253             GetClangDeclContextContainingDIE(die, &decl_ctx_die);
1254         const clang::Decl::Kind containing_decl_kind =
1255             containing_decl_ctx->getDeclKind();
1256
1257         bool is_cxx_method = DeclKindIsCXXClass(containing_decl_kind);
1258         // Start off static. This will be set to false in
1259         // ParseChildParameters(...)
1260         // if we find a "this" parameters as the first parameter
1261         if (is_cxx_method) {
1262           is_static = true;
1263         }
1264
1265         if (die.HasChildren()) {
1266           bool skip_artificial = true;
1267           ParseChildParameters(sc, containing_decl_ctx, die, skip_artificial,
1268                                is_static, is_variadic, has_template_params,
1269                                function_param_types, function_param_decls,
1270                                type_quals);
1271         }
1272
1273         bool ignore_containing_context = false;
1274         // Check for templatized class member functions. If we had any
1275         // DW_TAG_template_type_parameter
1276         // or DW_TAG_template_value_parameter the DW_TAG_subprogram DIE, then we
1277         // can't let this become
1278         // a method in a class. Why? Because templatized functions are only
1279         // emitted if one of the
1280         // templatized methods is used in the current compile unit and we will
1281         // end up with classes
1282         // that may or may not include these member functions and this means one
1283         // class won't match another
1284         // class definition and it affects our ability to use a class in the
1285         // clang expression parser. So
1286         // for the greater good, we currently must not allow any template member
1287         // functions in a class definition.
1288         if (is_cxx_method && has_template_params) {
1289           ignore_containing_context = true;
1290           is_cxx_method = false;
1291         }
1292
1293         // clang_type will get the function prototype clang type after this call
1294         clang_type = m_ast.CreateFunctionType(
1295             return_clang_type, function_param_types.data(),
1296             function_param_types.size(), is_variadic, type_quals);
1297
1298         if (type_name_cstr) {
1299           bool type_handled = false;
1300           if (tag == DW_TAG_subprogram || tag == DW_TAG_inlined_subroutine) {
1301             ObjCLanguage::MethodName objc_method(type_name_cstr, true);
1302             if (objc_method.IsValid(true)) {
1303               CompilerType class_opaque_type;
1304               ConstString class_name(objc_method.GetClassName());
1305               if (class_name) {
1306                 TypeSP complete_objc_class_type_sp(
1307                     dwarf->FindCompleteObjCDefinitionTypeForDIE(
1308                         DWARFDIE(), class_name, false));
1309
1310                 if (complete_objc_class_type_sp) {
1311                   CompilerType type_clang_forward_type =
1312                       complete_objc_class_type_sp->GetForwardCompilerType();
1313                   if (ClangASTContext::IsObjCObjectOrInterfaceType(
1314                           type_clang_forward_type))
1315                     class_opaque_type = type_clang_forward_type;
1316                 }
1317               }
1318
1319               if (class_opaque_type) {
1320                 // If accessibility isn't set to anything valid, assume public
1321                 // for
1322                 // now...
1323                 if (accessibility == eAccessNone)
1324                   accessibility = eAccessPublic;
1325
1326                 clang::ObjCMethodDecl *objc_method_decl =
1327                     m_ast.AddMethodToObjCObjectType(
1328                         class_opaque_type, type_name_cstr, clang_type,
1329                         accessibility, is_artificial, is_variadic);
1330                 type_handled = objc_method_decl != NULL;
1331                 if (type_handled) {
1332                   LinkDeclContextToDIE(
1333                       ClangASTContext::GetAsDeclContext(objc_method_decl), die);
1334                   m_ast.SetMetadataAsUserID(objc_method_decl, die.GetID());
1335                 } else {
1336                   dwarf->GetObjectFile()->GetModule()->ReportError(
1337                       "{0x%8.8x}: invalid Objective-C method 0x%4.4x (%s), "
1338                       "please file a bug and attach the file at the start of "
1339                       "this error message",
1340                       die.GetOffset(), tag, DW_TAG_value_to_name(tag));
1341                 }
1342               }
1343             } else if (is_cxx_method) {
1344               // Look at the parent of this DIE and see if is is
1345               // a class or struct and see if this is actually a
1346               // C++ method
1347               Type *class_type = dwarf->ResolveType(decl_ctx_die);
1348               if (class_type) {
1349                 bool alternate_defn = false;
1350                 if (class_type->GetID() != decl_ctx_die.GetID() ||
1351                     decl_ctx_die.GetContainingDWOModuleDIE()) {
1352                   alternate_defn = true;
1353
1354                   // We uniqued the parent class of this function to another
1355                   // class
1356                   // so we now need to associate all dies under "decl_ctx_die"
1357                   // to
1358                   // DIEs in the DIE for "class_type"...
1359                   SymbolFileDWARF *class_symfile = NULL;
1360                   DWARFDIE class_type_die;
1361
1362                   SymbolFileDWARFDebugMap *debug_map_symfile =
1363                       dwarf->GetDebugMapSymfile();
1364                   if (debug_map_symfile) {
1365                     class_symfile = debug_map_symfile->GetSymbolFileByOSOIndex(
1366                         SymbolFileDWARFDebugMap::GetOSOIndexFromUserID(
1367                             class_type->GetID()));
1368                     class_type_die = class_symfile->DebugInfo()->GetDIE(
1369                         DIERef(class_type->GetID(), dwarf));
1370                   } else {
1371                     class_symfile = dwarf;
1372                     class_type_die = dwarf->DebugInfo()->GetDIE(
1373                         DIERef(class_type->GetID(), dwarf));
1374                   }
1375                   if (class_type_die) {
1376                     DWARFDIECollection failures;
1377
1378                     CopyUniqueClassMethodTypes(decl_ctx_die, class_type_die,
1379                                                class_type, failures);
1380
1381                     // FIXME do something with these failures that's smarter
1382                     // than
1383                     // just dropping them on the ground.  Unfortunately classes
1384                     // don't
1385                     // like having stuff added to them after their definitions
1386                     // are
1387                     // complete...
1388
1389                     type_ptr = dwarf->GetDIEToType()[die.GetDIE()];
1390                     if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) {
1391                       type_sp = type_ptr->shared_from_this();
1392                       break;
1393                     }
1394                   }
1395                 }
1396
1397                 if (specification_die_form.IsValid()) {
1398                   // We have a specification which we are going to base our
1399                   // function
1400                   // prototype off of, so we need this type to be completed so
1401                   // that the
1402                   // m_die_to_decl_ctx for the method in the specification has a
1403                   // valid
1404                   // clang decl context.
1405                   class_type->GetForwardCompilerType();
1406                   // If we have a specification, then the function type should
1407                   // have been
1408                   // made with the specification and not with this die.
1409                   DWARFDIE spec_die = dwarf->DebugInfo()->GetDIE(
1410                       DIERef(specification_die_form));
1411                   clang::DeclContext *spec_clang_decl_ctx =
1412                       GetClangDeclContextForDIE(spec_die);
1413                   if (spec_clang_decl_ctx) {
1414                     LinkDeclContextToDIE(spec_clang_decl_ctx, die);
1415                   } else {
1416                     dwarf->GetObjectFile()->GetModule()->ReportWarning(
1417                         "0x%8.8" PRIx64 ": DW_AT_specification(0x%8.8" PRIx64
1418                         ") has no decl\n",
1419                         die.GetID(), specification_die_form.Reference());
1420                   }
1421                   type_handled = true;
1422                 } else if (abstract_origin_die_form.IsValid()) {
1423                   // We have a specification which we are going to base our
1424                   // function
1425                   // prototype off of, so we need this type to be completed so
1426                   // that the
1427                   // m_die_to_decl_ctx for the method in the abstract origin has
1428                   // a valid
1429                   // clang decl context.
1430                   class_type->GetForwardCompilerType();
1431
1432                   DWARFDIE abs_die = dwarf->DebugInfo()->GetDIE(
1433                       DIERef(abstract_origin_die_form));
1434                   clang::DeclContext *abs_clang_decl_ctx =
1435                       GetClangDeclContextForDIE(abs_die);
1436                   if (abs_clang_decl_ctx) {
1437                     LinkDeclContextToDIE(abs_clang_decl_ctx, die);
1438                   } else {
1439                     dwarf->GetObjectFile()->GetModule()->ReportWarning(
1440                         "0x%8.8" PRIx64 ": DW_AT_abstract_origin(0x%8.8" PRIx64
1441                         ") has no decl\n",
1442                         die.GetID(), abstract_origin_die_form.Reference());
1443                   }
1444                   type_handled = true;
1445                 } else {
1446                   CompilerType class_opaque_type =
1447                       class_type->GetForwardCompilerType();
1448                   if (ClangASTContext::IsCXXClassType(class_opaque_type)) {
1449                     if (class_opaque_type.IsBeingDefined() || alternate_defn) {
1450                       if (!is_static && !die.HasChildren()) {
1451                         // We have a C++ member function with no children (this
1452                         // pointer!)
1453                         // and clang will get mad if we try and make a function
1454                         // that isn't
1455                         // well formed in the DWARF, so we will just skip it...
1456                         type_handled = true;
1457                       } else {
1458                         bool add_method = true;
1459                         if (alternate_defn) {
1460                           // If an alternate definition for the class exists,
1461                           // then add the method only if an
1462                           // equivalent is not already present.
1463                           clang::CXXRecordDecl *record_decl =
1464                               m_ast.GetAsCXXRecordDecl(
1465                                   class_opaque_type.GetOpaqueQualType());
1466                           if (record_decl) {
1467                             for (auto method_iter = record_decl->method_begin();
1468                                  method_iter != record_decl->method_end();
1469                                  method_iter++) {
1470                               clang::CXXMethodDecl *method_decl = *method_iter;
1471                               if (method_decl->getNameInfo().getAsString() ==
1472                                   std::string(type_name_cstr)) {
1473                                 if (method_decl->getType() ==
1474                                     ClangUtil::GetQualType(clang_type)) {
1475                                   add_method = false;
1476                                   LinkDeclContextToDIE(
1477                                       ClangASTContext::GetAsDeclContext(
1478                                           method_decl),
1479                                       die);
1480                                   type_handled = true;
1481
1482                                   break;
1483                                 }
1484                               }
1485                             }
1486                           }
1487                         }
1488
1489                         if (add_method) {
1490                           llvm::PrettyStackTraceFormat stack_trace(
1491                               "SymbolFileDWARF::ParseType() is adding a method "
1492                               "%s to class %s in DIE 0x%8.8" PRIx64 " from %s",
1493                               type_name_cstr,
1494                               class_type->GetName().GetCString(), die.GetID(),
1495                               dwarf->GetObjectFile()
1496                                   ->GetFileSpec()
1497                                   .GetPath()
1498                                   .c_str());
1499
1500                           const bool is_attr_used = false;
1501                           // Neither GCC 4.2 nor clang++ currently set a valid
1502                           // accessibility
1503                           // in the DWARF for C++ methods... Default to public
1504                           // for now...
1505                           if (accessibility == eAccessNone)
1506                             accessibility = eAccessPublic;
1507
1508                           clang::CXXMethodDecl *cxx_method_decl =
1509                               m_ast.AddMethodToCXXRecordType(
1510                                   class_opaque_type.GetOpaqueQualType(),
1511                                   type_name_cstr, clang_type, accessibility,
1512                                   is_virtual, is_static, is_inline, is_explicit,
1513                                   is_attr_used, is_artificial);
1514
1515                           type_handled = cxx_method_decl != NULL;
1516
1517                           if (type_handled) {
1518                             LinkDeclContextToDIE(
1519                                 ClangASTContext::GetAsDeclContext(
1520                                     cxx_method_decl),
1521                                 die);
1522
1523                             ClangASTMetadata metadata;
1524                             metadata.SetUserID(die.GetID());
1525
1526                             if (!object_pointer_name.empty()) {
1527                               metadata.SetObjectPtrName(
1528                                   object_pointer_name.c_str());
1529                               if (log)
1530                                 log->Printf(
1531                                     "Setting object pointer name: %s on method "
1532                                     "object %p.\n",
1533                                     object_pointer_name.c_str(),
1534                                     static_cast<void *>(cxx_method_decl));
1535                             }
1536                             m_ast.SetMetadata(cxx_method_decl, metadata);
1537                           } else {
1538                             ignore_containing_context = true;
1539                           }
1540                         }
1541                       }
1542                     } else {
1543                       // We were asked to parse the type for a method in a
1544                       // class, yet the
1545                       // class hasn't been asked to complete itself through the
1546                       // clang::ExternalASTSource protocol, so we need to just
1547                       // have the
1548                       // class complete itself and do things the right way, then
1549                       // our
1550                       // DIE should then have an entry in the
1551                       // dwarf->GetDIEToType() map. First
1552                       // we need to modify the dwarf->GetDIEToType() so it
1553                       // doesn't think we are
1554                       // trying to parse this DIE anymore...
1555                       dwarf->GetDIEToType()[die.GetDIE()] = NULL;
1556
1557                       // Now we get the full type to force our class type to
1558                       // complete itself
1559                       // using the clang::ExternalASTSource protocol which will
1560                       // parse all
1561                       // base classes and all methods (including the method for
1562                       // this DIE).
1563                       class_type->GetFullCompilerType();
1564
1565                       // The type for this DIE should have been filled in the
1566                       // function call above
1567                       type_ptr = dwarf->GetDIEToType()[die.GetDIE()];
1568                       if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) {
1569                         type_sp = type_ptr->shared_from_this();
1570                         break;
1571                       }
1572
1573                       // FIXME This is fixing some even uglier behavior but we
1574                       // really need to
1575                       // uniq the methods of each class as well as the class
1576                       // itself.
1577                       // <rdar://problem/11240464>
1578                       type_handled = true;
1579                     }
1580                   }
1581                 }
1582               }
1583             }
1584           }
1585
1586           if (!type_handled) {
1587             clang::FunctionDecl *function_decl = nullptr;
1588
1589             if (abstract_origin_die_form.IsValid()) {
1590               DWARFDIE abs_die =
1591                   dwarf->DebugInfo()->GetDIE(DIERef(abstract_origin_die_form));
1592
1593               SymbolContext sc;
1594
1595               if (dwarf->ResolveType(abs_die)) {
1596                 function_decl = llvm::dyn_cast_or_null<clang::FunctionDecl>(
1597                     GetCachedClangDeclContextForDIE(abs_die));
1598
1599                 if (function_decl) {
1600                   LinkDeclContextToDIE(function_decl, die);
1601                 }
1602               }
1603             }
1604
1605             if (!function_decl) {
1606               // We just have a function that isn't part of a class
1607               function_decl = m_ast.CreateFunctionDeclaration(
1608                   ignore_containing_context ? m_ast.GetTranslationUnitDecl()
1609                                             : containing_decl_ctx,
1610                   type_name_cstr, clang_type, storage, is_inline);
1611
1612               if (has_template_params) {
1613                 ClangASTContext::TemplateParameterInfos template_param_infos;
1614                 ParseTemplateParameterInfos(die, template_param_infos);
1615                 clang::FunctionTemplateDecl *func_template_decl =
1616                     m_ast.CreateFunctionTemplateDecl(
1617                         containing_decl_ctx, function_decl, type_name_cstr,
1618                         template_param_infos);
1619                 m_ast.CreateFunctionTemplateSpecializationInfo(
1620                     function_decl, func_template_decl, template_param_infos);
1621               }
1622               
1623               lldbassert(function_decl);
1624
1625               if (function_decl) {
1626                 LinkDeclContextToDIE(function_decl, die);
1627
1628                 if (!function_param_decls.empty())
1629                   m_ast.SetFunctionParameters(function_decl,
1630                                               &function_param_decls.front(),
1631                                               function_param_decls.size());
1632
1633                 ClangASTMetadata metadata;
1634                 metadata.SetUserID(die.GetID());
1635
1636                 if (!object_pointer_name.empty()) {
1637                   metadata.SetObjectPtrName(object_pointer_name.c_str());
1638                   if (log)
1639                     log->Printf("Setting object pointer name: %s on function "
1640                                 "object %p.",
1641                                 object_pointer_name.c_str(),
1642                                 static_cast<void *>(function_decl));
1643                 }
1644                 m_ast.SetMetadata(function_decl, metadata);
1645               }
1646             }
1647           }
1648         }
1649         type_sp.reset(new Type(die.GetID(), dwarf, type_name_const_str, 0, NULL,
1650                                LLDB_INVALID_UID, Type::eEncodingIsUID, &decl,
1651                                clang_type, Type::eResolveStateFull));
1652         assert(type_sp.get());
1653       } break;
1654
1655       case DW_TAG_array_type: {
1656         // Set a bit that lets us know that we are currently parsing this
1657         dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
1658
1659         DWARFFormValue type_die_form;
1660         int64_t first_index = 0;
1661         uint32_t byte_stride = 0;
1662         uint32_t bit_stride = 0;
1663         bool is_vector = false;
1664         const size_t num_attributes = die.GetAttributes(attributes);
1665
1666         if (num_attributes > 0) {
1667           uint32_t i;
1668           for (i = 0; i < num_attributes; ++i) {
1669             attr = attributes.AttributeAtIndex(i);
1670             if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1671               switch (attr) {
1672               case DW_AT_decl_file:
1673                 decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
1674                     form_value.Unsigned()));
1675                 break;
1676               case DW_AT_decl_line:
1677                 decl.SetLine(form_value.Unsigned());
1678                 break;
1679               case DW_AT_decl_column:
1680                 decl.SetColumn(form_value.Unsigned());
1681                 break;
1682               case DW_AT_name:
1683                 type_name_cstr = form_value.AsCString();
1684                 type_name_const_str.SetCString(type_name_cstr);
1685                 break;
1686
1687               case DW_AT_type:
1688                 type_die_form = form_value;
1689                 break;
1690               case DW_AT_byte_size:
1691                 break; // byte_size = form_value.Unsigned(); break;
1692               case DW_AT_byte_stride:
1693                 byte_stride = form_value.Unsigned();
1694                 break;
1695               case DW_AT_bit_stride:
1696                 bit_stride = form_value.Unsigned();
1697                 break;
1698               case DW_AT_GNU_vector:
1699                 is_vector = form_value.Boolean();
1700                 break;
1701               case DW_AT_accessibility:
1702                 break; // accessibility =
1703                        // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
1704               case DW_AT_declaration:
1705                 break; // is_forward_declaration = form_value.Boolean(); break;
1706               case DW_AT_allocated:
1707               case DW_AT_associated:
1708               case DW_AT_data_location:
1709               case DW_AT_description:
1710               case DW_AT_ordering:
1711               case DW_AT_start_scope:
1712               case DW_AT_visibility:
1713               case DW_AT_specification:
1714               case DW_AT_abstract_origin:
1715               case DW_AT_sibling:
1716                 break;
1717               }
1718             }
1719           }
1720
1721           DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
1722                        DW_TAG_value_to_name(tag), type_name_cstr);
1723
1724           DIERef type_die_ref(type_die_form);
1725           Type *element_type = dwarf->ResolveTypeUID(type_die_ref);
1726
1727           if (element_type) {
1728             std::vector<uint64_t> element_orders;
1729             ParseChildArrayInfo(sc, die, first_index, element_orders,
1730                                 byte_stride, bit_stride);
1731             if (byte_stride == 0 && bit_stride == 0)
1732               byte_stride = element_type->GetByteSize();
1733             CompilerType array_element_type =
1734                 element_type->GetForwardCompilerType();
1735
1736             if (ClangASTContext::IsCXXClassType(array_element_type) &&
1737                 array_element_type.GetCompleteType() == false) {
1738               ModuleSP module_sp = die.GetModule();
1739               if (module_sp) {
1740                 if (die.GetCU()->GetProducer() ==
1741                     DWARFCompileUnit::eProducerClang)
1742                   module_sp->ReportError(
1743                       "DWARF DW_TAG_array_type DIE at 0x%8.8x has a "
1744                       "class/union/struct element type DIE 0x%8.8x that is a "
1745                       "forward declaration, not a complete definition.\nTry "
1746                       "compiling the source file with -fstandalone-debug or "
1747                       "disable -gmodules",
1748                       die.GetOffset(), type_die_ref.die_offset);
1749                 else
1750                   module_sp->ReportError(
1751                       "DWARF DW_TAG_array_type DIE at 0x%8.8x has a "
1752                       "class/union/struct element type DIE 0x%8.8x that is a "
1753                       "forward declaration, not a complete definition.\nPlease "
1754                       "file a bug against the compiler and include the "
1755                       "preprocessed output for %s",
1756                       die.GetOffset(), type_die_ref.die_offset,
1757                       die.GetLLDBCompileUnit()
1758                           ? die.GetLLDBCompileUnit()->GetPath().c_str()
1759                           : "the source file");
1760               }
1761
1762               // We have no choice other than to pretend that the element class
1763               // type
1764               // is complete. If we don't do this, clang will crash when trying
1765               // to layout the class. Since we provide layout assistance, all
1766               // ivars in this class and other classes will be fine, this is
1767               // the best we can do short of crashing.
1768               if (ClangASTContext::StartTagDeclarationDefinition(
1769                       array_element_type)) {
1770                 ClangASTContext::CompleteTagDeclarationDefinition(
1771                     array_element_type);
1772               } else {
1773                 module_sp->ReportError("DWARF DIE at 0x%8.8x was not able to "
1774                                        "start its definition.\nPlease file a "
1775                                        "bug and attach the file at the start "
1776                                        "of this error message",
1777                                        type_die_ref.die_offset);
1778               }
1779             }
1780
1781             uint64_t array_element_bit_stride = byte_stride * 8 + bit_stride;
1782             if (element_orders.size() > 0) {
1783               uint64_t num_elements = 0;
1784               std::vector<uint64_t>::const_reverse_iterator pos;
1785               std::vector<uint64_t>::const_reverse_iterator end =
1786                   element_orders.rend();
1787               for (pos = element_orders.rbegin(); pos != end; ++pos) {
1788                 num_elements = *pos;
1789                 clang_type = m_ast.CreateArrayType(array_element_type,
1790                                                    num_elements, is_vector);
1791                 array_element_type = clang_type;
1792                 array_element_bit_stride =
1793                     num_elements ? array_element_bit_stride * num_elements
1794                                  : array_element_bit_stride;
1795               }
1796             } else {
1797               clang_type =
1798                   m_ast.CreateArrayType(array_element_type, 0, is_vector);
1799             }
1800             ConstString empty_name;
1801             type_sp.reset(new Type(
1802                 die.GetID(), dwarf, empty_name, array_element_bit_stride / 8,
1803                 NULL, DIERef(type_die_form).GetUID(dwarf), Type::eEncodingIsUID,
1804                 &decl, clang_type, Type::eResolveStateFull));
1805             type_sp->SetEncodingType(element_type);
1806           }
1807         }
1808       } break;
1809
1810       case DW_TAG_ptr_to_member_type: {
1811         DWARFFormValue type_die_form;
1812         DWARFFormValue containing_type_die_form;
1813
1814         const size_t num_attributes = die.GetAttributes(attributes);
1815
1816         if (num_attributes > 0) {
1817           uint32_t i;
1818           for (i = 0; i < num_attributes; ++i) {
1819             attr = attributes.AttributeAtIndex(i);
1820             if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1821               switch (attr) {
1822               case DW_AT_type:
1823                 type_die_form = form_value;
1824                 break;
1825               case DW_AT_containing_type:
1826                 containing_type_die_form = form_value;
1827                 break;
1828               }
1829             }
1830           }
1831
1832           Type *pointee_type = dwarf->ResolveTypeUID(DIERef(type_die_form));
1833           Type *class_type =
1834               dwarf->ResolveTypeUID(DIERef(containing_type_die_form));
1835
1836           CompilerType pointee_clang_type =
1837               pointee_type->GetForwardCompilerType();
1838           CompilerType class_clang_type = class_type->GetLayoutCompilerType();
1839
1840           clang_type = ClangASTContext::CreateMemberPointerType(
1841               class_clang_type, pointee_clang_type);
1842
1843           byte_size = clang_type.GetByteSize(nullptr);
1844
1845           type_sp.reset(new Type(die.GetID(), dwarf, type_name_const_str,
1846                                  byte_size, NULL, LLDB_INVALID_UID,
1847                                  Type::eEncodingIsUID, NULL, clang_type,
1848                                  Type::eResolveStateForward));
1849         }
1850
1851         break;
1852       }
1853       default:
1854         dwarf->GetObjectFile()->GetModule()->ReportError(
1855             "{0x%8.8x}: unhandled type tag 0x%4.4x (%s), please file a bug and "
1856             "attach the file at the start of this error message",
1857             die.GetOffset(), tag, DW_TAG_value_to_name(tag));
1858         break;
1859       }
1860
1861       if (type_sp.get()) {
1862         DWARFDIE sc_parent_die =
1863             SymbolFileDWARF::GetParentSymbolContextDIE(die);
1864         dw_tag_t sc_parent_tag = sc_parent_die.Tag();
1865
1866         SymbolContextScope *symbol_context_scope = NULL;
1867         if (sc_parent_tag == DW_TAG_compile_unit) {
1868           symbol_context_scope = sc.comp_unit;
1869         } else if (sc.function != NULL && sc_parent_die) {
1870           symbol_context_scope =
1871               sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID());
1872           if (symbol_context_scope == NULL)
1873             symbol_context_scope = sc.function;
1874         }
1875
1876         if (symbol_context_scope != NULL) {
1877           type_sp->SetSymbolContextScope(symbol_context_scope);
1878         }
1879
1880         // We are ready to put this type into the uniqued list up at the module
1881         // level
1882         type_list->Insert(type_sp);
1883
1884         dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
1885       }
1886     } else if (type_ptr != DIE_IS_BEING_PARSED) {
1887       type_sp = type_ptr->shared_from_this();
1888     }
1889   }
1890   return type_sp;
1891 }
1892
1893 // DWARF parsing functions
1894
1895 class DWARFASTParserClang::DelayedAddObjCClassProperty {
1896 public:
1897   DelayedAddObjCClassProperty(
1898       const CompilerType &class_opaque_type, const char *property_name,
1899       const CompilerType &property_opaque_type, // The property type is only
1900                                                 // required if you don't have an
1901                                                 // ivar decl
1902       clang::ObjCIvarDecl *ivar_decl, const char *property_setter_name,
1903       const char *property_getter_name, uint32_t property_attributes,
1904       const ClangASTMetadata *metadata)
1905       : m_class_opaque_type(class_opaque_type), m_property_name(property_name),
1906         m_property_opaque_type(property_opaque_type), m_ivar_decl(ivar_decl),
1907         m_property_setter_name(property_setter_name),
1908         m_property_getter_name(property_getter_name),
1909         m_property_attributes(property_attributes) {
1910     if (metadata != NULL) {
1911       m_metadata_ap.reset(new ClangASTMetadata());
1912       *m_metadata_ap = *metadata;
1913     }
1914   }
1915
1916   DelayedAddObjCClassProperty(const DelayedAddObjCClassProperty &rhs) {
1917     *this = rhs;
1918   }
1919
1920   DelayedAddObjCClassProperty &
1921   operator=(const DelayedAddObjCClassProperty &rhs) {
1922     m_class_opaque_type = rhs.m_class_opaque_type;
1923     m_property_name = rhs.m_property_name;
1924     m_property_opaque_type = rhs.m_property_opaque_type;
1925     m_ivar_decl = rhs.m_ivar_decl;
1926     m_property_setter_name = rhs.m_property_setter_name;
1927     m_property_getter_name = rhs.m_property_getter_name;
1928     m_property_attributes = rhs.m_property_attributes;
1929
1930     if (rhs.m_metadata_ap.get()) {
1931       m_metadata_ap.reset(new ClangASTMetadata());
1932       *m_metadata_ap = *rhs.m_metadata_ap;
1933     }
1934     return *this;
1935   }
1936
1937   bool Finalize() {
1938     return ClangASTContext::AddObjCClassProperty(
1939         m_class_opaque_type, m_property_name, m_property_opaque_type,
1940         m_ivar_decl, m_property_setter_name, m_property_getter_name,
1941         m_property_attributes, m_metadata_ap.get());
1942   }
1943
1944 private:
1945   CompilerType m_class_opaque_type;
1946   const char *m_property_name;
1947   CompilerType m_property_opaque_type;
1948   clang::ObjCIvarDecl *m_ivar_decl;
1949   const char *m_property_setter_name;
1950   const char *m_property_getter_name;
1951   uint32_t m_property_attributes;
1952   std::unique_ptr<ClangASTMetadata> m_metadata_ap;
1953 };
1954
1955 bool DWARFASTParserClang::ParseTemplateDIE(
1956     const DWARFDIE &die,
1957     ClangASTContext::TemplateParameterInfos &template_param_infos) {
1958   const dw_tag_t tag = die.Tag();
1959
1960   switch (tag) {
1961   case DW_TAG_GNU_template_parameter_pack: {
1962     template_param_infos.packed_args.reset(
1963       new ClangASTContext::TemplateParameterInfos);
1964     for (DWARFDIE child_die = die.GetFirstChild(); child_die.IsValid();
1965          child_die = child_die.GetSibling()) {
1966       if (!ParseTemplateDIE(child_die, *template_param_infos.packed_args))
1967         return false;
1968     }
1969     if (const char *name = die.GetName()) {
1970       template_param_infos.pack_name = name;
1971     }
1972     return true;
1973   }
1974   case DW_TAG_template_type_parameter:
1975   case DW_TAG_template_value_parameter: {
1976     DWARFAttributes attributes;
1977     const size_t num_attributes = die.GetAttributes(attributes);
1978     const char *name = nullptr;
1979     CompilerType clang_type;
1980     uint64_t uval64 = 0;
1981     bool uval64_valid = false;
1982     if (num_attributes > 0) {
1983       DWARFFormValue form_value;
1984       for (size_t i = 0; i < num_attributes; ++i) {
1985         const dw_attr_t attr = attributes.AttributeAtIndex(i);
1986
1987         switch (attr) {
1988         case DW_AT_name:
1989           if (attributes.ExtractFormValueAtIndex(i, form_value))
1990             name = form_value.AsCString();
1991           break;
1992
1993         case DW_AT_type:
1994           if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1995             Type *lldb_type = die.ResolveTypeUID(DIERef(form_value));
1996             if (lldb_type)
1997               clang_type = lldb_type->GetForwardCompilerType();
1998           }
1999           break;
2000
2001         case DW_AT_const_value:
2002           if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2003             uval64_valid = true;
2004             uval64 = form_value.Unsigned();
2005           }
2006           break;
2007         default:
2008           break;
2009         }
2010       }
2011
2012       clang::ASTContext *ast = m_ast.getASTContext();
2013       if (!clang_type)
2014         clang_type = m_ast.GetBasicType(eBasicTypeVoid);
2015
2016       if (clang_type) {
2017         bool is_signed = false;
2018         if (name && name[0])
2019           template_param_infos.names.push_back(name);
2020         else
2021           template_param_infos.names.push_back(NULL);
2022
2023         // Get the signed value for any integer or enumeration if available
2024         clang_type.IsIntegerOrEnumerationType(is_signed);
2025
2026         if (tag == DW_TAG_template_value_parameter && uval64_valid) {
2027           llvm::APInt apint(clang_type.GetBitSize(nullptr), uval64, is_signed);
2028           template_param_infos.args.push_back(
2029               clang::TemplateArgument(*ast, llvm::APSInt(apint, !is_signed),
2030                                       ClangUtil::GetQualType(clang_type)));
2031         } else {
2032           template_param_infos.args.push_back(
2033               clang::TemplateArgument(ClangUtil::GetQualType(clang_type)));
2034         }
2035       } else {
2036         return false;
2037       }
2038     }
2039   }
2040     return true;
2041
2042   default:
2043     break;
2044   }
2045   return false;
2046 }
2047
2048 bool DWARFASTParserClang::ParseTemplateParameterInfos(
2049     const DWARFDIE &parent_die,
2050     ClangASTContext::TemplateParameterInfos &template_param_infos) {
2051
2052   if (!parent_die)
2053     return false;
2054
2055   Args template_parameter_names;
2056   for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
2057        die = die.GetSibling()) {
2058     const dw_tag_t tag = die.Tag();
2059
2060     switch (tag) {
2061     case DW_TAG_template_type_parameter:
2062     case DW_TAG_template_value_parameter:
2063     case DW_TAG_GNU_template_parameter_pack:
2064       ParseTemplateDIE(die, template_param_infos);
2065       break;
2066
2067     default:
2068       break;
2069     }
2070   }
2071   if (template_param_infos.args.empty())
2072     return false;
2073   return template_param_infos.args.size() == template_param_infos.names.size();
2074 }
2075
2076 bool DWARFASTParserClang::CompleteTypeFromDWARF(const DWARFDIE &die,
2077                                                 lldb_private::Type *type,
2078                                                 CompilerType &clang_type) {
2079   SymbolFileDWARF *dwarf = die.GetDWARF();
2080
2081   std::lock_guard<std::recursive_mutex> guard(
2082       dwarf->GetObjectFile()->GetModule()->GetMutex());
2083
2084   // Disable external storage for this type so we don't get anymore
2085   // clang::ExternalASTSource queries for this type.
2086   m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), false);
2087
2088   if (!die)
2089     return false;
2090
2091 #if defined LLDB_CONFIGURATION_DEBUG
2092   //----------------------------------------------------------------------
2093   // For debugging purposes, the LLDB_DWARF_DONT_COMPLETE_TYPENAMES
2094   // environment variable can be set with one or more typenames separated
2095   // by ';' characters. This will cause this function to not complete any
2096   // types whose names match.
2097   //
2098   // Examples of setting this environment variable:
2099   //
2100   // LLDB_DWARF_DONT_COMPLETE_TYPENAMES=Foo
2101   // LLDB_DWARF_DONT_COMPLETE_TYPENAMES=Foo;Bar;Baz
2102   //----------------------------------------------------------------------
2103   const char *dont_complete_typenames_cstr =
2104       getenv("LLDB_DWARF_DONT_COMPLETE_TYPENAMES");
2105   if (dont_complete_typenames_cstr && dont_complete_typenames_cstr[0]) {
2106     const char *die_name = die.GetName();
2107     if (die_name && die_name[0]) {
2108       const char *match = strstr(dont_complete_typenames_cstr, die_name);
2109       if (match) {
2110         size_t die_name_length = strlen(die_name);
2111         while (match) {
2112           const char separator_char = ';';
2113           const char next_char = match[die_name_length];
2114           if (next_char == '\0' || next_char == separator_char) {
2115             if (match == dont_complete_typenames_cstr ||
2116                 match[-1] == separator_char)
2117               return false;
2118           }
2119           match = strstr(match + 1, die_name);
2120         }
2121       }
2122     }
2123   }
2124 #endif
2125
2126   const dw_tag_t tag = die.Tag();
2127
2128   Log *log =
2129       nullptr; // (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO|DWARF_LOG_TYPE_COMPLETION));
2130   if (log)
2131     dwarf->GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
2132         log, "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
2133         die.GetID(), die.GetTagAsCString(), type->GetName().AsCString());
2134   assert(clang_type);
2135   DWARFAttributes attributes;
2136   switch (tag) {
2137   case DW_TAG_structure_type:
2138   case DW_TAG_union_type:
2139   case DW_TAG_class_type: {
2140     ClangASTImporter::LayoutInfo layout_info;
2141
2142     {
2143       if (die.HasChildren()) {
2144         LanguageType class_language = eLanguageTypeUnknown;
2145         if (ClangASTContext::IsObjCObjectOrInterfaceType(clang_type)) {
2146           class_language = eLanguageTypeObjC;
2147           // For objective C we don't start the definition when
2148           // the class is created.
2149           ClangASTContext::StartTagDeclarationDefinition(clang_type);
2150         }
2151
2152         int tag_decl_kind = -1;
2153         AccessType default_accessibility = eAccessNone;
2154         if (tag == DW_TAG_structure_type) {
2155           tag_decl_kind = clang::TTK_Struct;
2156           default_accessibility = eAccessPublic;
2157         } else if (tag == DW_TAG_union_type) {
2158           tag_decl_kind = clang::TTK_Union;
2159           default_accessibility = eAccessPublic;
2160         } else if (tag == DW_TAG_class_type) {
2161           tag_decl_kind = clang::TTK_Class;
2162           default_accessibility = eAccessPrivate;
2163         }
2164
2165         SymbolContext sc(die.GetLLDBCompileUnit());
2166         std::vector<clang::CXXBaseSpecifier *> base_classes;
2167         std::vector<int> member_accessibilities;
2168         bool is_a_class = false;
2169         // Parse members and base classes first
2170         DWARFDIECollection member_function_dies;
2171
2172         DelayedPropertyList delayed_properties;
2173         ParseChildMembers(sc, die, clang_type, class_language, base_classes,
2174                           member_accessibilities, member_function_dies,
2175                           delayed_properties, default_accessibility, is_a_class,
2176                           layout_info);
2177
2178         // Now parse any methods if there were any...
2179         size_t num_functions = member_function_dies.Size();
2180         if (num_functions > 0) {
2181           for (size_t i = 0; i < num_functions; ++i) {
2182             dwarf->ResolveType(member_function_dies.GetDIEAtIndex(i));
2183           }
2184         }
2185
2186         if (class_language == eLanguageTypeObjC) {
2187           ConstString class_name(clang_type.GetTypeName());
2188           if (class_name) {
2189             DIEArray method_die_offsets;
2190             dwarf->GetObjCMethodDIEOffsets(class_name, method_die_offsets);
2191
2192             if (!method_die_offsets.empty()) {
2193               DWARFDebugInfo *debug_info = dwarf->DebugInfo();
2194
2195               const size_t num_matches = method_die_offsets.size();
2196               for (size_t i = 0; i < num_matches; ++i) {
2197                 const DIERef &die_ref = method_die_offsets[i];
2198                 DWARFDIE method_die = debug_info->GetDIE(die_ref);
2199
2200                 if (method_die)
2201                   method_die.ResolveType();
2202               }
2203             }
2204
2205             for (DelayedPropertyList::iterator pi = delayed_properties.begin(),
2206                                                pe = delayed_properties.end();
2207                  pi != pe; ++pi)
2208               pi->Finalize();
2209           }
2210         }
2211
2212         // If we have a DW_TAG_structure_type instead of a DW_TAG_class_type we
2213         // need to tell the clang type it is actually a class.
2214         if (class_language != eLanguageTypeObjC) {
2215           if (is_a_class && tag_decl_kind != clang::TTK_Class)
2216             m_ast.SetTagTypeKind(ClangUtil::GetQualType(clang_type),
2217                                  clang::TTK_Class);
2218         }
2219
2220         // Since DW_TAG_structure_type gets used for both classes
2221         // and structures, we may need to set any DW_TAG_member
2222         // fields to have a "private" access if none was specified.
2223         // When we parsed the child members we tracked that actual
2224         // accessibility value for each DW_TAG_member in the
2225         // "member_accessibilities" array. If the value for the
2226         // member is zero, then it was set to the "default_accessibility"
2227         // which for structs was "public". Below we correct this
2228         // by setting any fields to "private" that weren't correctly
2229         // set.
2230         if (is_a_class && !member_accessibilities.empty()) {
2231           // This is a class and all members that didn't have
2232           // their access specified are private.
2233           m_ast.SetDefaultAccessForRecordFields(
2234               m_ast.GetAsRecordDecl(clang_type), eAccessPrivate,
2235               &member_accessibilities.front(), member_accessibilities.size());
2236         }
2237
2238         if (!base_classes.empty()) {
2239           // Make sure all base classes refer to complete types and not
2240           // forward declarations. If we don't do this, clang will crash
2241           // with an assertion in the call to
2242           // clang_type.SetBaseClassesForClassType()
2243           for (auto &base_class : base_classes) {
2244             clang::TypeSourceInfo *type_source_info =
2245                 base_class->getTypeSourceInfo();
2246             if (type_source_info) {
2247               CompilerType base_class_type(
2248                   &m_ast, type_source_info->getType().getAsOpaquePtr());
2249               if (base_class_type.GetCompleteType() == false) {
2250                 auto module = dwarf->GetObjectFile()->GetModule();
2251                 module->ReportError(":: Class '%s' has a base class '%s' which "
2252                                     "does not have a complete definition.",
2253                                     die.GetName(),
2254                                     base_class_type.GetTypeName().GetCString());
2255                 if (die.GetCU()->GetProducer() ==
2256                     DWARFCompileUnit::eProducerClang)
2257                   module->ReportError(":: Try compiling the source file with "
2258                                       "-fstandalone-debug.");
2259
2260                 // We have no choice other than to pretend that the base class
2261                 // is complete. If we don't do this, clang will crash when we
2262                 // call setBases() inside of
2263                 // "clang_type.SetBaseClassesForClassType()"
2264                 // below. Since we provide layout assistance, all ivars in this
2265                 // class and other classes will be fine, this is the best we can
2266                 // do
2267                 // short of crashing.
2268                 if (ClangASTContext::StartTagDeclarationDefinition(
2269                         base_class_type)) {
2270                   ClangASTContext::CompleteTagDeclarationDefinition(
2271                       base_class_type);
2272                 }
2273               }
2274             }
2275           }
2276           m_ast.SetBaseClassesForClassType(clang_type.GetOpaqueQualType(),
2277                                            &base_classes.front(),
2278                                            base_classes.size());
2279
2280           // Clang will copy each CXXBaseSpecifier in "base_classes"
2281           // so we have to free them all.
2282           ClangASTContext::DeleteBaseClassSpecifiers(&base_classes.front(),
2283                                                      base_classes.size());
2284         }
2285       }
2286     }
2287
2288     ClangASTContext::BuildIndirectFields(clang_type);
2289     ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
2290
2291     if (!layout_info.field_offsets.empty() ||
2292         !layout_info.base_offsets.empty() ||
2293         !layout_info.vbase_offsets.empty()) {
2294       if (type)
2295         layout_info.bit_size = type->GetByteSize() * 8;
2296       if (layout_info.bit_size == 0)
2297         layout_info.bit_size =
2298             die.GetAttributeValueAsUnsigned(DW_AT_byte_size, 0) * 8;
2299
2300       clang::CXXRecordDecl *record_decl =
2301           m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
2302       if (record_decl) {
2303         if (log) {
2304           ModuleSP module_sp = dwarf->GetObjectFile()->GetModule();
2305
2306           if (module_sp) {
2307             module_sp->LogMessage(
2308                 log,
2309                 "ClangASTContext::CompleteTypeFromDWARF (clang_type = %p) "
2310                 "caching layout info for record_decl = %p, bit_size = %" PRIu64
2311                 ", alignment = %" PRIu64
2312                 ", field_offsets[%u], base_offsets[%u], vbase_offsets[%u])",
2313                 static_cast<void *>(clang_type.GetOpaqueQualType()),
2314                 static_cast<void *>(record_decl), layout_info.bit_size,
2315                 layout_info.alignment,
2316                 static_cast<uint32_t>(layout_info.field_offsets.size()),
2317                 static_cast<uint32_t>(layout_info.base_offsets.size()),
2318                 static_cast<uint32_t>(layout_info.vbase_offsets.size()));
2319
2320             uint32_t idx;
2321             {
2322               llvm::DenseMap<const clang::FieldDecl *, uint64_t>::const_iterator
2323                   pos,
2324                   end = layout_info.field_offsets.end();
2325               for (idx = 0, pos = layout_info.field_offsets.begin(); pos != end;
2326                    ++pos, ++idx) {
2327                 module_sp->LogMessage(
2328                     log, "ClangASTContext::CompleteTypeFromDWARF (clang_type = "
2329                          "%p) field[%u] = { bit_offset=%u, name='%s' }",
2330                     static_cast<void *>(clang_type.GetOpaqueQualType()), idx,
2331                     static_cast<uint32_t>(pos->second),
2332                     pos->first->getNameAsString().c_str());
2333               }
2334             }
2335
2336             {
2337               llvm::DenseMap<const clang::CXXRecordDecl *,
2338                              clang::CharUnits>::const_iterator base_pos,
2339                   base_end = layout_info.base_offsets.end();
2340               for (idx = 0, base_pos = layout_info.base_offsets.begin();
2341                    base_pos != base_end; ++base_pos, ++idx) {
2342                 module_sp->LogMessage(
2343                     log, "ClangASTContext::CompleteTypeFromDWARF (clang_type = "
2344                          "%p) base[%u] = { byte_offset=%u, name='%s' }",
2345                     clang_type.GetOpaqueQualType(), idx,
2346                     (uint32_t)base_pos->second.getQuantity(),
2347                     base_pos->first->getNameAsString().c_str());
2348               }
2349             }
2350             {
2351               llvm::DenseMap<const clang::CXXRecordDecl *,
2352                              clang::CharUnits>::const_iterator vbase_pos,
2353                   vbase_end = layout_info.vbase_offsets.end();
2354               for (idx = 0, vbase_pos = layout_info.vbase_offsets.begin();
2355                    vbase_pos != vbase_end; ++vbase_pos, ++idx) {
2356                 module_sp->LogMessage(
2357                     log, "ClangASTContext::CompleteTypeFromDWARF (clang_type = "
2358                          "%p) vbase[%u] = { byte_offset=%u, name='%s' }",
2359                     static_cast<void *>(clang_type.GetOpaqueQualType()), idx,
2360                     static_cast<uint32_t>(vbase_pos->second.getQuantity()),
2361                     vbase_pos->first->getNameAsString().c_str());
2362               }
2363             }
2364           }
2365         }
2366         GetClangASTImporter().InsertRecordDecl(record_decl, layout_info);
2367       }
2368     }
2369   }
2370
2371     return (bool)clang_type;
2372
2373   case DW_TAG_enumeration_type:
2374     if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) {
2375       if (die.HasChildren()) {
2376         SymbolContext sc(die.GetLLDBCompileUnit());
2377         bool is_signed = false;
2378         clang_type.IsIntegerType(is_signed);
2379         ParseChildEnumerators(sc, clang_type, is_signed, type->GetByteSize(),
2380                               die);
2381       }
2382       ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
2383     }
2384     return (bool)clang_type;
2385
2386   default:
2387     assert(false && "not a forward clang type decl!");
2388     break;
2389   }
2390
2391   return false;
2392 }
2393
2394 std::vector<DWARFDIE> DWARFASTParserClang::GetDIEForDeclContext(
2395     lldb_private::CompilerDeclContext decl_context) {
2396   std::vector<DWARFDIE> result;
2397   for (auto it = m_decl_ctx_to_die.find(
2398            (clang::DeclContext *)decl_context.GetOpaqueDeclContext());
2399        it != m_decl_ctx_to_die.end(); it++)
2400     result.push_back(it->second);
2401   return result;
2402 }
2403
2404 CompilerDecl DWARFASTParserClang::GetDeclForUIDFromDWARF(const DWARFDIE &die) {
2405   clang::Decl *clang_decl = GetClangDeclForDIE(die);
2406   if (clang_decl != nullptr)
2407     return CompilerDecl(&m_ast, clang_decl);
2408   return CompilerDecl();
2409 }
2410
2411 CompilerDeclContext
2412 DWARFASTParserClang::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) {
2413   clang::DeclContext *clang_decl_ctx = GetClangDeclContextForDIE(die);
2414   if (clang_decl_ctx)
2415     return CompilerDeclContext(&m_ast, clang_decl_ctx);
2416   return CompilerDeclContext();
2417 }
2418
2419 CompilerDeclContext
2420 DWARFASTParserClang::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) {
2421   clang::DeclContext *clang_decl_ctx =
2422       GetClangDeclContextContainingDIE(die, nullptr);
2423   if (clang_decl_ctx)
2424     return CompilerDeclContext(&m_ast, clang_decl_ctx);
2425   return CompilerDeclContext();
2426 }
2427
2428 size_t DWARFASTParserClang::ParseChildEnumerators(
2429     const SymbolContext &sc, lldb_private::CompilerType &clang_type,
2430     bool is_signed, uint32_t enumerator_byte_size, const DWARFDIE &parent_die) {
2431   if (!parent_die)
2432     return 0;
2433
2434   size_t enumerators_added = 0;
2435
2436   for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
2437        die = die.GetSibling()) {
2438     const dw_tag_t tag = die.Tag();
2439     if (tag == DW_TAG_enumerator) {
2440       DWARFAttributes attributes;
2441       const size_t num_child_attributes = die.GetAttributes(attributes);
2442       if (num_child_attributes > 0) {
2443         const char *name = NULL;
2444         bool got_value = false;
2445         int64_t enum_value = 0;
2446         Declaration decl;
2447
2448         uint32_t i;
2449         for (i = 0; i < num_child_attributes; ++i) {
2450           const dw_attr_t attr = attributes.AttributeAtIndex(i);
2451           DWARFFormValue form_value;
2452           if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2453             switch (attr) {
2454             case DW_AT_const_value:
2455               got_value = true;
2456               if (is_signed)
2457                 enum_value = form_value.Signed();
2458               else
2459                 enum_value = form_value.Unsigned();
2460               break;
2461
2462             case DW_AT_name:
2463               name = form_value.AsCString();
2464               break;
2465
2466             case DW_AT_description:
2467             default:
2468             case DW_AT_decl_file:
2469               decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
2470                   form_value.Unsigned()));
2471               break;
2472             case DW_AT_decl_line:
2473               decl.SetLine(form_value.Unsigned());
2474               break;
2475             case DW_AT_decl_column:
2476               decl.SetColumn(form_value.Unsigned());
2477               break;
2478             case DW_AT_sibling:
2479               break;
2480             }
2481           }
2482         }
2483
2484         if (name && name[0] && got_value) {
2485           m_ast.AddEnumerationValueToEnumerationType(
2486               clang_type.GetOpaqueQualType(),
2487               m_ast.GetEnumerationIntegerType(clang_type.GetOpaqueQualType()),
2488               decl, name, enum_value, enumerator_byte_size * 8);
2489           ++enumerators_added;
2490         }
2491       }
2492     }
2493   }
2494   return enumerators_added;
2495 }
2496
2497 #if defined(LLDB_CONFIGURATION_DEBUG) || defined(LLDB_CONFIGURATION_RELEASE)
2498
2499 class DIEStack {
2500 public:
2501   void Push(const DWARFDIE &die) { m_dies.push_back(die); }
2502
2503   void LogDIEs(Log *log) {
2504     StreamString log_strm;
2505     const size_t n = m_dies.size();
2506     log_strm.Printf("DIEStack[%" PRIu64 "]:\n", (uint64_t)n);
2507     for (size_t i = 0; i < n; i++) {
2508       std::string qualified_name;
2509       const DWARFDIE &die = m_dies[i];
2510       die.GetQualifiedName(qualified_name);
2511       log_strm.Printf("[%" PRIu64 "] 0x%8.8x: %s name='%s'\n", (uint64_t)i,
2512                       die.GetOffset(), die.GetTagAsCString(),
2513                       qualified_name.c_str());
2514     }
2515     log->PutCString(log_strm.GetData());
2516   }
2517   void Pop() { m_dies.pop_back(); }
2518
2519   class ScopedPopper {
2520   public:
2521     ScopedPopper(DIEStack &die_stack)
2522         : m_die_stack(die_stack), m_valid(false) {}
2523
2524     void Push(const DWARFDIE &die) {
2525       m_valid = true;
2526       m_die_stack.Push(die);
2527     }
2528
2529     ~ScopedPopper() {
2530       if (m_valid)
2531         m_die_stack.Pop();
2532     }
2533
2534   protected:
2535     DIEStack &m_die_stack;
2536     bool m_valid;
2537   };
2538
2539 protected:
2540   typedef std::vector<DWARFDIE> Stack;
2541   Stack m_dies;
2542 };
2543 #endif
2544
2545 Function *DWARFASTParserClang::ParseFunctionFromDWARF(const SymbolContext &sc,
2546                                                       const DWARFDIE &die) {
2547   DWARFRangeList func_ranges;
2548   const char *name = NULL;
2549   const char *mangled = NULL;
2550   int decl_file = 0;
2551   int decl_line = 0;
2552   int decl_column = 0;
2553   int call_file = 0;
2554   int call_line = 0;
2555   int call_column = 0;
2556   DWARFExpression frame_base(die.GetCU());
2557
2558   const dw_tag_t tag = die.Tag();
2559
2560   if (tag != DW_TAG_subprogram)
2561     return NULL;
2562
2563   if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line,
2564                                decl_column, call_file, call_line, call_column,
2565                                &frame_base)) {
2566
2567     // Union of all ranges in the function DIE (if the function is
2568     // discontiguous)
2569     AddressRange func_range;
2570     lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase(0);
2571     lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd(0);
2572     if (lowest_func_addr != LLDB_INVALID_ADDRESS &&
2573         lowest_func_addr <= highest_func_addr) {
2574       ModuleSP module_sp(die.GetModule());
2575       func_range.GetBaseAddress().ResolveAddressUsingFileSections(
2576           lowest_func_addr, module_sp->GetSectionList());
2577       if (func_range.GetBaseAddress().IsValid())
2578         func_range.SetByteSize(highest_func_addr - lowest_func_addr);
2579     }
2580
2581     if (func_range.GetBaseAddress().IsValid()) {
2582       Mangled func_name;
2583       if (mangled)
2584         func_name.SetValue(ConstString(mangled), true);
2585       else if (die.GetParent().Tag() == DW_TAG_compile_unit &&
2586                Language::LanguageIsCPlusPlus(die.GetLanguage()) && name &&
2587                strcmp(name, "main") != 0) {
2588         // If the mangled name is not present in the DWARF, generate the
2589         // demangled name
2590         // using the decl context. We skip if the function is "main" as its name
2591         // is
2592         // never mangled.
2593         bool is_static = false;
2594         bool is_variadic = false;
2595         bool has_template_params = false;
2596         unsigned type_quals = 0;
2597         std::vector<CompilerType> param_types;
2598         std::vector<clang::ParmVarDecl *> param_decls;
2599         DWARFDeclContext decl_ctx;
2600         StreamString sstr;
2601
2602         die.GetDWARFDeclContext(decl_ctx);
2603         sstr << decl_ctx.GetQualifiedName();
2604
2605         clang::DeclContext *containing_decl_ctx =
2606             GetClangDeclContextContainingDIE(die, nullptr);
2607         ParseChildParameters(sc, containing_decl_ctx, die, true, is_static,
2608                              is_variadic, has_template_params, param_types,
2609                              param_decls, type_quals);
2610         sstr << "(";
2611         for (size_t i = 0; i < param_types.size(); i++) {
2612           if (i > 0)
2613             sstr << ", ";
2614           sstr << param_types[i].GetTypeName();
2615         }
2616         if (is_variadic)
2617           sstr << ", ...";
2618         sstr << ")";
2619         if (type_quals & clang::Qualifiers::Const)
2620           sstr << " const";
2621
2622         func_name.SetValue(ConstString(sstr.GetString()), false);
2623       } else
2624         func_name.SetValue(ConstString(name), false);
2625
2626       FunctionSP func_sp;
2627       std::unique_ptr<Declaration> decl_ap;
2628       if (decl_file != 0 || decl_line != 0 || decl_column != 0)
2629         decl_ap.reset(new Declaration(
2630             sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(decl_file),
2631             decl_line, decl_column));
2632
2633       SymbolFileDWARF *dwarf = die.GetDWARF();
2634       // Supply the type _only_ if it has already been parsed
2635       Type *func_type = dwarf->GetDIEToType().lookup(die.GetDIE());
2636
2637       assert(func_type == NULL || func_type != DIE_IS_BEING_PARSED);
2638
2639       if (dwarf->FixupAddress(func_range.GetBaseAddress())) {
2640         const user_id_t func_user_id = die.GetID();
2641         func_sp.reset(new Function(sc.comp_unit,
2642                                    func_user_id, // UserID is the DIE offset
2643                                    func_user_id, func_name, func_type,
2644                                    func_range)); // first address range
2645
2646         if (func_sp.get() != NULL) {
2647           if (frame_base.IsValid())
2648             func_sp->GetFrameBaseExpression() = frame_base;
2649           sc.comp_unit->AddFunction(func_sp);
2650           return func_sp.get();
2651         }
2652       }
2653     }
2654   }
2655   return NULL;
2656 }
2657
2658 bool DWARFASTParserClang::ParseChildMembers(
2659     const SymbolContext &sc, const DWARFDIE &parent_die,
2660     CompilerType &class_clang_type, const LanguageType class_language,
2661     std::vector<clang::CXXBaseSpecifier *> &base_classes,
2662     std::vector<int> &member_accessibilities,
2663     DWARFDIECollection &member_function_dies,
2664     DelayedPropertyList &delayed_properties, AccessType &default_accessibility,
2665     bool &is_a_class, ClangASTImporter::LayoutInfo &layout_info) {
2666   if (!parent_die)
2667     return 0;
2668
2669   // Get the parent byte size so we can verify any members will fit
2670   const uint64_t parent_byte_size =
2671       parent_die.GetAttributeValueAsUnsigned(DW_AT_byte_size, UINT64_MAX);
2672   const uint64_t parent_bit_size =
2673       parent_byte_size == UINT64_MAX ? UINT64_MAX : parent_byte_size * 8;
2674
2675   uint32_t member_idx = 0;
2676   BitfieldInfo last_field_info;
2677
2678   ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule();
2679   ClangASTContext *ast =
2680       llvm::dyn_cast_or_null<ClangASTContext>(class_clang_type.GetTypeSystem());
2681   if (ast == nullptr)
2682     return 0;
2683
2684   for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
2685        die = die.GetSibling()) {
2686     dw_tag_t tag = die.Tag();
2687
2688     switch (tag) {
2689     case DW_TAG_member:
2690     case DW_TAG_APPLE_property: {
2691       DWARFAttributes attributes;
2692       const size_t num_attributes = die.GetAttributes(attributes);
2693       if (num_attributes > 0) {
2694         Declaration decl;
2695         // DWARFExpression location;
2696         const char *name = NULL;
2697         const char *prop_name = NULL;
2698         const char *prop_getter_name = NULL;
2699         const char *prop_setter_name = NULL;
2700         uint32_t prop_attributes = 0;
2701
2702         bool is_artificial = false;
2703         DWARFFormValue encoding_form;
2704         AccessType accessibility = eAccessNone;
2705         uint32_t member_byte_offset =
2706             (parent_die.Tag() == DW_TAG_union_type) ? 0 : UINT32_MAX;
2707         size_t byte_size = 0;
2708         int64_t bit_offset = 0;
2709         uint64_t data_bit_offset = UINT64_MAX;
2710         size_t bit_size = 0;
2711         bool is_external =
2712             false; // On DW_TAG_members, this means the member is static
2713         uint32_t i;
2714         for (i = 0; i < num_attributes && !is_artificial; ++i) {
2715           const dw_attr_t attr = attributes.AttributeAtIndex(i);
2716           DWARFFormValue form_value;
2717           if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2718             switch (attr) {
2719             case DW_AT_decl_file:
2720               decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
2721                   form_value.Unsigned()));
2722               break;
2723             case DW_AT_decl_line:
2724               decl.SetLine(form_value.Unsigned());
2725               break;
2726             case DW_AT_decl_column:
2727               decl.SetColumn(form_value.Unsigned());
2728               break;
2729             case DW_AT_name:
2730               name = form_value.AsCString();
2731               break;
2732             case DW_AT_type:
2733               encoding_form = form_value;
2734               break;
2735             case DW_AT_bit_offset:
2736               bit_offset = form_value.Signed();
2737               break;
2738             case DW_AT_bit_size:
2739               bit_size = form_value.Unsigned();
2740               break;
2741             case DW_AT_byte_size:
2742               byte_size = form_value.Unsigned();
2743               break;
2744             case DW_AT_data_bit_offset:
2745               data_bit_offset = form_value.Unsigned();
2746               break;
2747             case DW_AT_data_member_location:
2748               if (form_value.BlockData()) {
2749                 Value initialValue(0);
2750                 Value memberOffset(0);
2751                 const DWARFDataExtractor &debug_info_data =
2752                     die.GetDWARF()->get_debug_info_data();
2753                 uint32_t block_length = form_value.Unsigned();
2754                 uint32_t block_offset =
2755                     form_value.BlockData() - debug_info_data.GetDataStart();
2756                 if (DWARFExpression::Evaluate(
2757                         nullptr, // ExecutionContext *
2758                         nullptr, // RegisterContext *
2759                         module_sp, debug_info_data, die.GetCU(), block_offset,
2760                         block_length, eRegisterKindDWARF, &initialValue,
2761                         nullptr, memberOffset, nullptr)) {
2762                   member_byte_offset = memberOffset.ResolveValue(NULL).UInt();
2763                 }
2764               } else {
2765                 // With DWARF 3 and later, if the value is an integer constant,
2766                 // this form value is the offset in bytes from the beginning
2767                 // of the containing entity.
2768                 member_byte_offset = form_value.Unsigned();
2769               }
2770               break;
2771
2772             case DW_AT_accessibility:
2773               accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
2774               break;
2775             case DW_AT_artificial:
2776               is_artificial = form_value.Boolean();
2777               break;
2778             case DW_AT_APPLE_property_name:
2779               prop_name = form_value.AsCString();
2780               break;
2781             case DW_AT_APPLE_property_getter:
2782               prop_getter_name = form_value.AsCString();
2783               break;
2784             case DW_AT_APPLE_property_setter:
2785               prop_setter_name = form_value.AsCString();
2786               break;
2787             case DW_AT_APPLE_property_attribute:
2788               prop_attributes = form_value.Unsigned();
2789               break;
2790             case DW_AT_external:
2791               is_external = form_value.Boolean();
2792               break;
2793
2794             default:
2795             case DW_AT_declaration:
2796             case DW_AT_description:
2797             case DW_AT_mutable:
2798             case DW_AT_visibility:
2799             case DW_AT_sibling:
2800               break;
2801             }
2802           }
2803         }
2804
2805         if (prop_name) {
2806           ConstString fixed_getter;
2807           ConstString fixed_setter;
2808
2809           // Check if the property getter/setter were provided as full
2810           // names.  We want basenames, so we extract them.
2811
2812           if (prop_getter_name && prop_getter_name[0] == '-') {
2813             ObjCLanguage::MethodName prop_getter_method(prop_getter_name, true);
2814             prop_getter_name = prop_getter_method.GetSelector().GetCString();
2815           }
2816
2817           if (prop_setter_name && prop_setter_name[0] == '-') {
2818             ObjCLanguage::MethodName prop_setter_method(prop_setter_name, true);
2819             prop_setter_name = prop_setter_method.GetSelector().GetCString();
2820           }
2821
2822           // If the names haven't been provided, they need to be
2823           // filled in.
2824
2825           if (!prop_getter_name) {
2826             prop_getter_name = prop_name;
2827           }
2828           if (!prop_setter_name && prop_name[0] &&
2829               !(prop_attributes & DW_APPLE_PROPERTY_readonly)) {
2830             StreamString ss;
2831
2832             ss.Printf("set%c%s:", toupper(prop_name[0]), &prop_name[1]);
2833
2834             fixed_setter.SetString(ss.GetString());
2835             prop_setter_name = fixed_setter.GetCString();
2836           }
2837         }
2838
2839         // Clang has a DWARF generation bug where sometimes it
2840         // represents fields that are references with bad byte size
2841         // and bit size/offset information such as:
2842         //
2843         //  DW_AT_byte_size( 0x00 )
2844         //  DW_AT_bit_size( 0x40 )
2845         //  DW_AT_bit_offset( 0xffffffffffffffc0 )
2846         //
2847         // So check the bit offset to make sure it is sane, and if
2848         // the values are not sane, remove them. If we don't do this
2849         // then we will end up with a crash if we try to use this
2850         // type in an expression when clang becomes unhappy with its
2851         // recycled debug info.
2852
2853         if (byte_size == 0 && bit_offset < 0) {
2854           bit_size = 0;
2855           bit_offset = 0;
2856         }
2857
2858         // FIXME: Make Clang ignore Objective-C accessibility for expressions
2859         if (class_language == eLanguageTypeObjC ||
2860             class_language == eLanguageTypeObjC_plus_plus)
2861           accessibility = eAccessNone;
2862
2863         if (member_idx == 0 && !is_artificial && name &&
2864             (strstr(name, "_vptr$") == name)) {
2865           // Not all compilers will mark the vtable pointer
2866           // member as artificial (llvm-gcc). We can't have
2867           // the virtual members in our classes otherwise it
2868           // throws off all child offsets since we end up
2869           // having and extra pointer sized member in our
2870           // class layouts.
2871           is_artificial = true;
2872         }
2873
2874         // Handle static members
2875         if (is_external && member_byte_offset == UINT32_MAX) {
2876           Type *var_type = die.ResolveTypeUID(DIERef(encoding_form));
2877
2878           if (var_type) {
2879             if (accessibility == eAccessNone)
2880               accessibility = eAccessPublic;
2881             ClangASTContext::AddVariableToRecordType(
2882                 class_clang_type, name, var_type->GetLayoutCompilerType(),
2883                 accessibility);
2884           }
2885           break;
2886         }
2887
2888         if (is_artificial == false) {
2889           Type *member_type = die.ResolveTypeUID(DIERef(encoding_form));
2890
2891           clang::FieldDecl *field_decl = NULL;
2892           if (tag == DW_TAG_member) {
2893             if (member_type) {
2894               if (accessibility == eAccessNone)
2895                 accessibility = default_accessibility;
2896               member_accessibilities.push_back(accessibility);
2897
2898               uint64_t field_bit_offset =
2899                   (member_byte_offset == UINT32_MAX ? 0
2900                                                     : (member_byte_offset * 8));
2901               if (bit_size > 0) {
2902
2903                 BitfieldInfo this_field_info;
2904                 this_field_info.bit_offset = field_bit_offset;
2905                 this_field_info.bit_size = bit_size;
2906
2907                 /////////////////////////////////////////////////////////////
2908                 // How to locate a field given the DWARF debug information
2909                 //
2910                 // AT_byte_size indicates the size of the word in which the
2911                 // bit offset must be interpreted.
2912                 //
2913                 // AT_data_member_location indicates the byte offset of the
2914                 // word from the base address of the structure.
2915                 //
2916                 // AT_bit_offset indicates how many bits into the word
2917                 // (according to the host endianness) the low-order bit of
2918                 // the field starts.  AT_bit_offset can be negative.
2919                 //
2920                 // AT_bit_size indicates the size of the field in bits.
2921                 /////////////////////////////////////////////////////////////
2922
2923                 if (data_bit_offset != UINT64_MAX) {
2924                   this_field_info.bit_offset = data_bit_offset;
2925                 } else {
2926                   if (byte_size == 0)
2927                     byte_size = member_type->GetByteSize();
2928
2929                   ObjectFile *objfile = die.GetDWARF()->GetObjectFile();
2930                   if (objfile->GetByteOrder() == eByteOrderLittle) {
2931                     this_field_info.bit_offset += byte_size * 8;
2932                     this_field_info.bit_offset -= (bit_offset + bit_size);
2933                   } else {
2934                     this_field_info.bit_offset += bit_offset;
2935                   }
2936                 }
2937
2938                 if ((this_field_info.bit_offset >= parent_bit_size) ||
2939                     !last_field_info.NextBitfieldOffsetIsValid(
2940                         this_field_info.bit_offset)) {
2941                   ObjectFile *objfile = die.GetDWARF()->GetObjectFile();
2942                   objfile->GetModule()->ReportWarning(
2943                       "0x%8.8" PRIx64 ": %s bitfield named \"%s\" has invalid "
2944                                       "bit offset (0x%8.8" PRIx64
2945                       ") member will be ignored. Please file a bug against the "
2946                       "compiler and include the preprocessed output for %s\n",
2947                       die.GetID(), DW_TAG_value_to_name(tag), name,
2948                       this_field_info.bit_offset,
2949                       sc.comp_unit ? sc.comp_unit->GetPath().c_str()
2950                                    : "the source file");
2951                   this_field_info.Clear();
2952                   continue;
2953                 }
2954
2955                 // Update the field bit offset we will report for layout
2956                 field_bit_offset = this_field_info.bit_offset;
2957
2958                 // If the member to be emitted did not start on a character
2959                 // boundary and there is
2960                 // empty space between the last field and this one, then we need
2961                 // to emit an
2962                 // anonymous member filling up the space up to its start.  There
2963                 // are three cases
2964                 // here:
2965                 //
2966                 // 1 If the previous member ended on a character boundary, then
2967                 // we can emit an
2968                 //   anonymous member starting at the most recent character
2969                 //   boundary.
2970                 //
2971                 // 2 If the previous member did not end on a character boundary
2972                 // and the distance
2973                 //   from the end of the previous member to the current member
2974                 //   is less than a
2975                 //   word width, then we can emit an anonymous member starting
2976                 //   right after the
2977                 //   previous member and right before this member.
2978                 //
2979                 // 3 If the previous member did not end on a character boundary
2980                 // and the distance
2981                 //   from the end of the previous member to the current member
2982                 //   is greater than
2983                 //   or equal a word width, then we act as in Case 1.
2984
2985                 const uint64_t character_width = 8;
2986                 const uint64_t word_width = 32;
2987
2988                 // Objective-C has invalid DW_AT_bit_offset values in older
2989                 // versions
2990                 // of clang, so we have to be careful and only insert unnamed
2991                 // bitfields
2992                 // if we have a new enough clang.
2993                 bool detect_unnamed_bitfields = true;
2994
2995                 if (class_language == eLanguageTypeObjC ||
2996                     class_language == eLanguageTypeObjC_plus_plus)
2997                   detect_unnamed_bitfields =
2998                       die.GetCU()->Supports_unnamed_objc_bitfields();
2999
3000                 if (detect_unnamed_bitfields) {
3001                   BitfieldInfo anon_field_info;
3002
3003                   if ((this_field_info.bit_offset % character_width) !=
3004                       0) // not char aligned
3005                   {
3006                     uint64_t last_field_end = 0;
3007
3008                     if (last_field_info.IsValid())
3009                       last_field_end =
3010                           last_field_info.bit_offset + last_field_info.bit_size;
3011
3012                     if (this_field_info.bit_offset != last_field_end) {
3013                       if (((last_field_end % character_width) == 0) || // case 1
3014                           (this_field_info.bit_offset - last_field_end >=
3015                            word_width)) // case 3
3016                       {
3017                         anon_field_info.bit_size =
3018                             this_field_info.bit_offset % character_width;
3019                         anon_field_info.bit_offset =
3020                             this_field_info.bit_offset -
3021                             anon_field_info.bit_size;
3022                       } else // case 2
3023                       {
3024                         anon_field_info.bit_size =
3025                             this_field_info.bit_offset - last_field_end;
3026                         anon_field_info.bit_offset = last_field_end;
3027                       }
3028                     }
3029                   }
3030
3031                   if (anon_field_info.IsValid()) {
3032                     clang::FieldDecl *unnamed_bitfield_decl =
3033                         ClangASTContext::AddFieldToRecordType(
3034                             class_clang_type, NULL,
3035                             m_ast.GetBuiltinTypeForEncodingAndBitSize(
3036                                 eEncodingSint, word_width),
3037                             accessibility, anon_field_info.bit_size);
3038
3039                     layout_info.field_offsets.insert(std::make_pair(
3040                         unnamed_bitfield_decl, anon_field_info.bit_offset));
3041                   }
3042                 }
3043                 last_field_info = this_field_info;
3044               } else {
3045                 last_field_info.Clear();
3046               }
3047
3048               CompilerType member_clang_type =
3049                   member_type->GetLayoutCompilerType();
3050               if (!member_clang_type.IsCompleteType())
3051                 member_clang_type.GetCompleteType();
3052
3053               {
3054                 // Older versions of clang emit array[0] and array[1] in the
3055                 // same way (<rdar://problem/12566646>).
3056                 // If the current field is at the end of the structure, then
3057                 // there is definitely no room for extra
3058                 // elements and we override the type to array[0].
3059
3060                 CompilerType member_array_element_type;
3061                 uint64_t member_array_size;
3062                 bool member_array_is_incomplete;
3063
3064                 if (member_clang_type.IsArrayType(
3065                         &member_array_element_type, &member_array_size,
3066                         &member_array_is_incomplete) &&
3067                     !member_array_is_incomplete) {
3068                   uint64_t parent_byte_size =
3069                       parent_die.GetAttributeValueAsUnsigned(DW_AT_byte_size,
3070                                                              UINT64_MAX);
3071
3072                   if (member_byte_offset >= parent_byte_size) {
3073                     if (member_array_size != 1 &&
3074                         (member_array_size != 0 ||
3075                          member_byte_offset > parent_byte_size)) {
3076                       module_sp->ReportError(
3077                           "0x%8.8" PRIx64
3078                           ": DW_TAG_member '%s' refers to type 0x%8.8" PRIx64
3079                           " which extends beyond the bounds of 0x%8.8" PRIx64,
3080                           die.GetID(), name, encoding_form.Reference(),
3081                           parent_die.GetID());
3082                     }
3083
3084                     member_clang_type = m_ast.CreateArrayType(
3085                         member_array_element_type, 0, false);
3086                   }
3087                 }
3088               }
3089
3090               if (ClangASTContext::IsCXXClassType(member_clang_type) &&
3091                   member_clang_type.GetCompleteType() == false) {
3092                 if (die.GetCU()->GetProducer() ==
3093                     DWARFCompileUnit::eProducerClang)
3094                   module_sp->ReportError(
3095                       "DWARF DIE at 0x%8.8x (class %s) has a member variable "
3096                       "0x%8.8x (%s) whose type is a forward declaration, not a "
3097                       "complete definition.\nTry compiling the source file "
3098                       "with -fstandalone-debug",
3099                       parent_die.GetOffset(), parent_die.GetName(),
3100                       die.GetOffset(), name);
3101                 else
3102                   module_sp->ReportError(
3103                       "DWARF DIE at 0x%8.8x (class %s) has a member variable "
3104                       "0x%8.8x (%s) whose type is a forward declaration, not a "
3105                       "complete definition.\nPlease file a bug against the "
3106                       "compiler and include the preprocessed output for %s",
3107                       parent_die.GetOffset(), parent_die.GetName(),
3108                       die.GetOffset(), name,
3109                       sc.comp_unit ? sc.comp_unit->GetPath().c_str()
3110                                    : "the source file");
3111                 // We have no choice other than to pretend that the member class
3112                 // is complete. If we don't do this, clang will crash when
3113                 // trying
3114                 // to layout the class. Since we provide layout assistance, all
3115                 // ivars in this class and other classes will be fine, this is
3116                 // the best we can do short of crashing.
3117                 if (ClangASTContext::StartTagDeclarationDefinition(
3118                         member_clang_type)) {
3119                   ClangASTContext::CompleteTagDeclarationDefinition(
3120                       member_clang_type);
3121                 } else {
3122                   module_sp->ReportError(
3123                       "DWARF DIE at 0x%8.8x (class %s) has a member variable "
3124                       "0x%8.8x (%s) whose type claims to be a C++ class but we "
3125                       "were not able to start its definition.\nPlease file a "
3126                       "bug and attach the file at the start of this error "
3127                       "message",
3128                       parent_die.GetOffset(), parent_die.GetName(),
3129                       die.GetOffset(), name);
3130                 }
3131               }
3132
3133               field_decl = ClangASTContext::AddFieldToRecordType(
3134                   class_clang_type, name, member_clang_type, accessibility,
3135                   bit_size);
3136
3137               m_ast.SetMetadataAsUserID(field_decl, die.GetID());
3138
3139               layout_info.field_offsets.insert(
3140                   std::make_pair(field_decl, field_bit_offset));
3141             } else {
3142               if (name)
3143                 module_sp->ReportError(
3144                     "0x%8.8" PRIx64
3145                     ": DW_TAG_member '%s' refers to type 0x%8.8" PRIx64
3146                     " which was unable to be parsed",
3147                     die.GetID(), name, encoding_form.Reference());
3148               else
3149                 module_sp->ReportError(
3150                     "0x%8.8" PRIx64
3151                     ": DW_TAG_member refers to type 0x%8.8" PRIx64
3152                     " which was unable to be parsed",
3153                     die.GetID(), encoding_form.Reference());
3154             }
3155           }
3156
3157           if (prop_name != NULL && member_type) {
3158             clang::ObjCIvarDecl *ivar_decl = NULL;
3159
3160             if (field_decl) {
3161               ivar_decl = clang::dyn_cast<clang::ObjCIvarDecl>(field_decl);
3162               assert(ivar_decl != NULL);
3163             }
3164
3165             ClangASTMetadata metadata;
3166             metadata.SetUserID(die.GetID());
3167             delayed_properties.push_back(DelayedAddObjCClassProperty(
3168                 class_clang_type, prop_name,
3169                 member_type->GetLayoutCompilerType(), ivar_decl,
3170                 prop_setter_name, prop_getter_name, prop_attributes,
3171                 &metadata));
3172
3173             if (ivar_decl)
3174               m_ast.SetMetadataAsUserID(ivar_decl, die.GetID());
3175           }
3176         }
3177       }
3178       ++member_idx;
3179     } break;
3180
3181     case DW_TAG_subprogram:
3182       // Let the type parsing code handle this one for us.
3183       member_function_dies.Append(die);
3184       break;
3185
3186     case DW_TAG_inheritance: {
3187       is_a_class = true;
3188       if (default_accessibility == eAccessNone)
3189         default_accessibility = eAccessPrivate;
3190       // TODO: implement DW_TAG_inheritance type parsing
3191       DWARFAttributes attributes;
3192       const size_t num_attributes = die.GetAttributes(attributes);
3193       if (num_attributes > 0) {
3194         Declaration decl;
3195         DWARFExpression location(die.GetCU());
3196         DWARFFormValue encoding_form;
3197         AccessType accessibility = default_accessibility;
3198         bool is_virtual = false;
3199         bool is_base_of_class = true;
3200         off_t member_byte_offset = 0;
3201         uint32_t i;
3202         for (i = 0; i < num_attributes; ++i) {
3203           const dw_attr_t attr = attributes.AttributeAtIndex(i);
3204           DWARFFormValue form_value;
3205           if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3206             switch (attr) {
3207             case DW_AT_decl_file:
3208               decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3209                   form_value.Unsigned()));
3210               break;
3211             case DW_AT_decl_line:
3212               decl.SetLine(form_value.Unsigned());
3213               break;
3214             case DW_AT_decl_column:
3215               decl.SetColumn(form_value.Unsigned());
3216               break;
3217             case DW_AT_type:
3218               encoding_form = form_value;
3219               break;
3220             case DW_AT_data_member_location:
3221               if (form_value.BlockData()) {
3222                 Value initialValue(0);
3223                 Value memberOffset(0);
3224                 const DWARFDataExtractor &debug_info_data =
3225                     die.GetDWARF()->get_debug_info_data();
3226                 uint32_t block_length = form_value.Unsigned();
3227                 uint32_t block_offset =
3228                     form_value.BlockData() - debug_info_data.GetDataStart();
3229                 if (DWARFExpression::Evaluate(nullptr, nullptr, module_sp,
3230                                               debug_info_data, die.GetCU(),
3231                                               block_offset, block_length,
3232                                               eRegisterKindDWARF, &initialValue,
3233                                               nullptr, memberOffset, nullptr)) {
3234                   member_byte_offset = memberOffset.ResolveValue(NULL).UInt();
3235                 }
3236               } else {
3237                 // With DWARF 3 and later, if the value is an integer constant,
3238                 // this form value is the offset in bytes from the beginning
3239                 // of the containing entity.
3240                 member_byte_offset = form_value.Unsigned();
3241               }
3242               break;
3243
3244             case DW_AT_accessibility:
3245               accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
3246               break;
3247
3248             case DW_AT_virtuality:
3249               is_virtual = form_value.Boolean();
3250               break;
3251
3252             case DW_AT_sibling:
3253               break;
3254
3255             default:
3256               break;
3257             }
3258           }
3259         }
3260
3261         Type *base_class_type = die.ResolveTypeUID(DIERef(encoding_form));
3262         if (base_class_type == NULL) {
3263           module_sp->ReportError("0x%8.8x: DW_TAG_inheritance failed to "
3264                                  "resolve the base class at 0x%8.8" PRIx64
3265                                  " from enclosing type 0x%8.8x. \nPlease file "
3266                                  "a bug and attach the file at the start of "
3267                                  "this error message",
3268                                  die.GetOffset(), encoding_form.Reference(),
3269                                  parent_die.GetOffset());
3270           break;
3271         }
3272
3273         CompilerType base_class_clang_type =
3274             base_class_type->GetFullCompilerType();
3275         assert(base_class_clang_type);
3276         if (class_language == eLanguageTypeObjC) {
3277           ast->SetObjCSuperClass(class_clang_type, base_class_clang_type);
3278         } else {
3279           base_classes.push_back(ast->CreateBaseClassSpecifier(
3280               base_class_clang_type.GetOpaqueQualType(), accessibility,
3281               is_virtual, is_base_of_class));
3282
3283           if (is_virtual) {
3284             // Do not specify any offset for virtual inheritance. The DWARF
3285             // produced by clang doesn't
3286             // give us a constant offset, but gives us a DWARF expressions that
3287             // requires an actual object
3288             // in memory. the DW_AT_data_member_location for a virtual base
3289             // class looks like:
3290             //      DW_AT_data_member_location( DW_OP_dup, DW_OP_deref,
3291             //      DW_OP_constu(0x00000018), DW_OP_minus, DW_OP_deref,
3292             //      DW_OP_plus )
3293             // Given this, there is really no valid response we can give to
3294             // clang for virtual base
3295             // class offsets, and this should eventually be removed from
3296             // LayoutRecordType() in the external
3297             // AST source in clang.
3298           } else {
3299             layout_info.base_offsets.insert(std::make_pair(
3300                 ast->GetAsCXXRecordDecl(
3301                     base_class_clang_type.GetOpaqueQualType()),
3302                 clang::CharUnits::fromQuantity(member_byte_offset)));
3303           }
3304         }
3305       }
3306     } break;
3307
3308     default:
3309       break;
3310     }
3311   }
3312
3313   return true;
3314 }
3315
3316 size_t DWARFASTParserClang::ParseChildParameters(
3317     const SymbolContext &sc, clang::DeclContext *containing_decl_ctx,
3318     const DWARFDIE &parent_die, bool skip_artificial, bool &is_static,
3319     bool &is_variadic, bool &has_template_params,
3320     std::vector<CompilerType> &function_param_types,
3321     std::vector<clang::ParmVarDecl *> &function_param_decls,
3322     unsigned &type_quals) {
3323   if (!parent_die)
3324     return 0;
3325
3326   size_t arg_idx = 0;
3327   for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
3328        die = die.GetSibling()) {
3329     const dw_tag_t tag = die.Tag();
3330     switch (tag) {
3331     case DW_TAG_formal_parameter: {
3332       DWARFAttributes attributes;
3333       const size_t num_attributes = die.GetAttributes(attributes);
3334       if (num_attributes > 0) {
3335         const char *name = NULL;
3336         Declaration decl;
3337         DWARFFormValue param_type_die_form;
3338         bool is_artificial = false;
3339         // one of None, Auto, Register, Extern, Static, PrivateExtern
3340
3341         clang::StorageClass storage = clang::SC_None;
3342         uint32_t i;
3343         for (i = 0; i < num_attributes; ++i) {
3344           const dw_attr_t attr = attributes.AttributeAtIndex(i);
3345           DWARFFormValue form_value;
3346           if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3347             switch (attr) {
3348             case DW_AT_decl_file:
3349               decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3350                   form_value.Unsigned()));
3351               break;
3352             case DW_AT_decl_line:
3353               decl.SetLine(form_value.Unsigned());
3354               break;
3355             case DW_AT_decl_column:
3356               decl.SetColumn(form_value.Unsigned());
3357               break;
3358             case DW_AT_name:
3359               name = form_value.AsCString();
3360               break;
3361             case DW_AT_type:
3362               param_type_die_form = form_value;
3363               break;
3364             case DW_AT_artificial:
3365               is_artificial = form_value.Boolean();
3366               break;
3367             case DW_AT_location:
3368             //                          if (form_value.BlockData())
3369             //                          {
3370             //                              const DWARFDataExtractor&
3371             //                              debug_info_data = debug_info();
3372             //                              uint32_t block_length =
3373             //                              form_value.Unsigned();
3374             //                              DWARFDataExtractor
3375             //                              location(debug_info_data,
3376             //                              form_value.BlockData() -
3377             //                              debug_info_data.GetDataStart(),
3378             //                              block_length);
3379             //                          }
3380             //                          else
3381             //                          {
3382             //                          }
3383             //                          break;
3384             case DW_AT_const_value:
3385             case DW_AT_default_value:
3386             case DW_AT_description:
3387             case DW_AT_endianity:
3388             case DW_AT_is_optional:
3389             case DW_AT_segment:
3390             case DW_AT_variable_parameter:
3391             default:
3392             case DW_AT_abstract_origin:
3393             case DW_AT_sibling:
3394               break;
3395             }
3396           }
3397         }
3398
3399         bool skip = false;
3400         if (skip_artificial) {
3401           if (is_artificial) {
3402             // In order to determine if a C++ member function is
3403             // "const" we have to look at the const-ness of "this"...
3404             // Ugly, but that
3405             if (arg_idx == 0) {
3406               if (DeclKindIsCXXClass(containing_decl_ctx->getDeclKind())) {
3407                 // Often times compilers omit the "this" name for the
3408                 // specification DIEs, so we can't rely upon the name
3409                 // being in the formal parameter DIE...
3410                 if (name == NULL || ::strcmp(name, "this") == 0) {
3411                   Type *this_type =
3412                       die.ResolveTypeUID(DIERef(param_type_die_form));
3413                   if (this_type) {
3414                     uint32_t encoding_mask = this_type->GetEncodingMask();
3415                     if (encoding_mask & Type::eEncodingIsPointerUID) {
3416                       is_static = false;
3417
3418                       if (encoding_mask & (1u << Type::eEncodingIsConstUID))
3419                         type_quals |= clang::Qualifiers::Const;
3420                       if (encoding_mask & (1u << Type::eEncodingIsVolatileUID))
3421                         type_quals |= clang::Qualifiers::Volatile;
3422                     }
3423                   }
3424                 }
3425               }
3426             }
3427             skip = true;
3428           } else {
3429
3430             // HACK: Objective C formal parameters "self" and "_cmd"
3431             // are not marked as artificial in the DWARF...
3432             CompileUnit *comp_unit = die.GetLLDBCompileUnit();
3433             if (comp_unit) {
3434               switch (comp_unit->GetLanguage()) {
3435               case eLanguageTypeObjC:
3436               case eLanguageTypeObjC_plus_plus:
3437                 if (name && name[0] &&
3438                     (strcmp(name, "self") == 0 || strcmp(name, "_cmd") == 0))
3439                   skip = true;
3440                 break;
3441               default:
3442                 break;
3443               }
3444             }
3445           }
3446         }
3447
3448         if (!skip) {
3449           Type *type = die.ResolveTypeUID(DIERef(param_type_die_form));
3450           if (type) {
3451             function_param_types.push_back(type->GetForwardCompilerType());
3452
3453             clang::ParmVarDecl *param_var_decl =
3454                 m_ast.CreateParameterDeclaration(
3455                     name, type->GetForwardCompilerType(), storage);
3456             assert(param_var_decl);
3457             function_param_decls.push_back(param_var_decl);
3458
3459             m_ast.SetMetadataAsUserID(param_var_decl, die.GetID());
3460           }
3461         }
3462       }
3463       arg_idx++;
3464     } break;
3465
3466     case DW_TAG_unspecified_parameters:
3467       is_variadic = true;
3468       break;
3469
3470     case DW_TAG_template_type_parameter:
3471     case DW_TAG_template_value_parameter:
3472     case DW_TAG_GNU_template_parameter_pack:
3473       // The one caller of this was never using the template_param_infos,
3474       // and the local variable was taking up a large amount of stack space
3475       // in SymbolFileDWARF::ParseType() so this was removed. If we ever need
3476       // the template params back, we can add them back.
3477       // ParseTemplateDIE (dwarf_cu, die, template_param_infos);
3478       has_template_params = true;
3479       break;
3480
3481     default:
3482       break;
3483     }
3484   }
3485   return arg_idx;
3486 }
3487
3488 void DWARFASTParserClang::ParseChildArrayInfo(
3489     const SymbolContext &sc, const DWARFDIE &parent_die, int64_t &first_index,
3490     std::vector<uint64_t> &element_orders, uint32_t &byte_stride,
3491     uint32_t &bit_stride) {
3492   if (!parent_die)
3493     return;
3494
3495   for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
3496        die = die.GetSibling()) {
3497     const dw_tag_t tag = die.Tag();
3498     switch (tag) {
3499     case DW_TAG_subrange_type: {
3500       DWARFAttributes attributes;
3501       const size_t num_child_attributes = die.GetAttributes(attributes);
3502       if (num_child_attributes > 0) {
3503         uint64_t num_elements = 0;
3504         uint64_t lower_bound = 0;
3505         uint64_t upper_bound = 0;
3506         bool upper_bound_valid = false;
3507         uint32_t i;
3508         for (i = 0; i < num_child_attributes; ++i) {
3509           const dw_attr_t attr = attributes.AttributeAtIndex(i);
3510           DWARFFormValue form_value;
3511           if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3512             switch (attr) {
3513             case DW_AT_name:
3514               break;
3515
3516             case DW_AT_count:
3517               num_elements = form_value.Unsigned();
3518               break;
3519
3520             case DW_AT_bit_stride:
3521               bit_stride = form_value.Unsigned();
3522               break;
3523
3524             case DW_AT_byte_stride:
3525               byte_stride = form_value.Unsigned();
3526               break;
3527
3528             case DW_AT_lower_bound:
3529               lower_bound = form_value.Unsigned();
3530               break;
3531
3532             case DW_AT_upper_bound:
3533               upper_bound_valid = true;
3534               upper_bound = form_value.Unsigned();
3535               break;
3536
3537             default:
3538             case DW_AT_abstract_origin:
3539             case DW_AT_accessibility:
3540             case DW_AT_allocated:
3541             case DW_AT_associated:
3542             case DW_AT_data_location:
3543             case DW_AT_declaration:
3544             case DW_AT_description:
3545             case DW_AT_sibling:
3546             case DW_AT_threads_scaled:
3547             case DW_AT_type:
3548             case DW_AT_visibility:
3549               break;
3550             }
3551           }
3552         }
3553
3554         if (num_elements == 0) {
3555           if (upper_bound_valid && upper_bound >= lower_bound)
3556             num_elements = upper_bound - lower_bound + 1;
3557         }
3558
3559         element_orders.push_back(num_elements);
3560       }
3561     } break;
3562     }
3563   }
3564 }
3565
3566 Type *DWARFASTParserClang::GetTypeForDIE(const DWARFDIE &die) {
3567   if (die) {
3568     SymbolFileDWARF *dwarf = die.GetDWARF();
3569     DWARFAttributes attributes;
3570     const size_t num_attributes = die.GetAttributes(attributes);
3571     if (num_attributes > 0) {
3572       DWARFFormValue type_die_form;
3573       for (size_t i = 0; i < num_attributes; ++i) {
3574         dw_attr_t attr = attributes.AttributeAtIndex(i);
3575         DWARFFormValue form_value;
3576
3577         if (attr == DW_AT_type &&
3578             attributes.ExtractFormValueAtIndex(i, form_value))
3579           return dwarf->ResolveTypeUID(dwarf->GetDIE(DIERef(form_value)), true);
3580       }
3581     }
3582   }
3583
3584   return nullptr;
3585 }
3586
3587 clang::Decl *DWARFASTParserClang::GetClangDeclForDIE(const DWARFDIE &die) {
3588   if (!die)
3589     return nullptr;
3590
3591   switch (die.Tag()) {
3592   case DW_TAG_variable:
3593   case DW_TAG_constant:
3594   case DW_TAG_formal_parameter:
3595   case DW_TAG_imported_declaration:
3596   case DW_TAG_imported_module:
3597     break;
3598   default:
3599     return nullptr;
3600   }
3601
3602   DIEToDeclMap::iterator cache_pos = m_die_to_decl.find(die.GetDIE());
3603   if (cache_pos != m_die_to_decl.end())
3604     return cache_pos->second;
3605
3606   if (DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification)) {
3607     clang::Decl *decl = GetClangDeclForDIE(spec_die);
3608     m_die_to_decl[die.GetDIE()] = decl;
3609     m_decl_to_die[decl].insert(die.GetDIE());
3610     return decl;
3611   }
3612
3613   if (DWARFDIE abstract_origin_die =
3614           die.GetReferencedDIE(DW_AT_abstract_origin)) {
3615     clang::Decl *decl = GetClangDeclForDIE(abstract_origin_die);
3616     m_die_to_decl[die.GetDIE()] = decl;
3617     m_decl_to_die[decl].insert(die.GetDIE());
3618     return decl;
3619   }
3620
3621   clang::Decl *decl = nullptr;
3622   switch (die.Tag()) {
3623   case DW_TAG_variable:
3624   case DW_TAG_constant:
3625   case DW_TAG_formal_parameter: {
3626     SymbolFileDWARF *dwarf = die.GetDWARF();
3627     Type *type = GetTypeForDIE(die);
3628     if (dwarf && type) {
3629       const char *name = die.GetName();
3630       clang::DeclContext *decl_context =
3631           ClangASTContext::DeclContextGetAsDeclContext(
3632               dwarf->GetDeclContextContainingUID(die.GetID()));
3633       decl = m_ast.CreateVariableDeclaration(
3634           decl_context, name,
3635           ClangUtil::GetQualType(type->GetForwardCompilerType()));
3636     }
3637     break;
3638   }
3639   case DW_TAG_imported_declaration: {
3640     SymbolFileDWARF *dwarf = die.GetDWARF();
3641     DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(DW_AT_import);
3642     if (imported_uid) {
3643       CompilerDecl imported_decl = imported_uid.GetDecl();
3644       if (imported_decl) {
3645         clang::DeclContext *decl_context =
3646             ClangASTContext::DeclContextGetAsDeclContext(
3647                 dwarf->GetDeclContextContainingUID(die.GetID()));
3648         if (clang::NamedDecl *clang_imported_decl =
3649                 llvm::dyn_cast<clang::NamedDecl>(
3650                     (clang::Decl *)imported_decl.GetOpaqueDecl()))
3651           decl =
3652               m_ast.CreateUsingDeclaration(decl_context, clang_imported_decl);
3653       }
3654     }
3655     break;
3656   }
3657   case DW_TAG_imported_module: {
3658     SymbolFileDWARF *dwarf = die.GetDWARF();
3659     DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(DW_AT_import);
3660
3661     if (imported_uid) {
3662       CompilerDeclContext imported_decl_ctx = imported_uid.GetDeclContext();
3663       if (imported_decl_ctx) {
3664         clang::DeclContext *decl_context =
3665             ClangASTContext::DeclContextGetAsDeclContext(
3666                 dwarf->GetDeclContextContainingUID(die.GetID()));
3667         if (clang::NamespaceDecl *ns_decl =
3668                 ClangASTContext::DeclContextGetAsNamespaceDecl(
3669                     imported_decl_ctx))
3670           decl = m_ast.CreateUsingDirectiveDeclaration(decl_context, ns_decl);
3671       }
3672     }
3673     break;
3674   }
3675   default:
3676     break;
3677   }
3678
3679   m_die_to_decl[die.GetDIE()] = decl;
3680   m_decl_to_die[decl].insert(die.GetDIE());
3681
3682   return decl;
3683 }
3684
3685 clang::DeclContext *
3686 DWARFASTParserClang::GetClangDeclContextForDIE(const DWARFDIE &die) {
3687   if (die) {
3688     clang::DeclContext *decl_ctx = GetCachedClangDeclContextForDIE(die);
3689     if (decl_ctx)
3690       return decl_ctx;
3691
3692     bool try_parsing_type = true;
3693     switch (die.Tag()) {
3694     case DW_TAG_compile_unit:
3695       decl_ctx = m_ast.GetTranslationUnitDecl();
3696       try_parsing_type = false;
3697       break;
3698
3699     case DW_TAG_namespace:
3700       decl_ctx = ResolveNamespaceDIE(die);
3701       try_parsing_type = false;
3702       break;
3703
3704     case DW_TAG_lexical_block:
3705       decl_ctx = GetDeclContextForBlock(die);
3706       try_parsing_type = false;
3707       break;
3708
3709     default:
3710       break;
3711     }
3712
3713     if (decl_ctx == nullptr && try_parsing_type) {
3714       Type *type = die.GetDWARF()->ResolveType(die);
3715       if (type)
3716         decl_ctx = GetCachedClangDeclContextForDIE(die);
3717     }
3718
3719     if (decl_ctx) {
3720       LinkDeclContextToDIE(decl_ctx, die);
3721       return decl_ctx;
3722     }
3723   }
3724   return nullptr;
3725 }
3726
3727 static bool IsSubroutine(const DWARFDIE &die) {
3728   switch (die.Tag()) {
3729   case DW_TAG_subprogram:
3730   case DW_TAG_inlined_subroutine:
3731     return true;
3732   default:
3733     return false;
3734   }
3735 }
3736
3737 static DWARFDIE GetContainingFunctionWithAbstractOrigin(const DWARFDIE &die) {
3738   for (DWARFDIE candidate = die; candidate; candidate = candidate.GetParent()) {
3739     if (IsSubroutine(candidate)) {
3740       if (candidate.GetReferencedDIE(DW_AT_abstract_origin)) {
3741         return candidate;
3742       } else {
3743         return DWARFDIE();
3744       }
3745     }
3746   }
3747   assert(0 && "Shouldn't call GetContainingFunctionWithAbstractOrigin on "
3748               "something not in a function");
3749   return DWARFDIE();
3750 }
3751
3752 static DWARFDIE FindAnyChildWithAbstractOrigin(const DWARFDIE &context) {
3753   for (DWARFDIE candidate = context.GetFirstChild(); candidate.IsValid();
3754        candidate = candidate.GetSibling()) {
3755     if (candidate.GetReferencedDIE(DW_AT_abstract_origin)) {
3756       return candidate;
3757     }
3758   }
3759   return DWARFDIE();
3760 }
3761
3762 static DWARFDIE FindFirstChildWithAbstractOrigin(const DWARFDIE &block,
3763                                                  const DWARFDIE &function) {
3764   assert(IsSubroutine(function));
3765   for (DWARFDIE context = block; context != function.GetParent();
3766        context = context.GetParent()) {
3767     assert(!IsSubroutine(context) || context == function);
3768     if (DWARFDIE child = FindAnyChildWithAbstractOrigin(context)) {
3769       return child;
3770     }
3771   }
3772   return DWARFDIE();
3773 }
3774
3775 clang::DeclContext *
3776 DWARFASTParserClang::GetDeclContextForBlock(const DWARFDIE &die) {
3777   assert(die.Tag() == DW_TAG_lexical_block);
3778   DWARFDIE containing_function_with_abstract_origin =
3779       GetContainingFunctionWithAbstractOrigin(die);
3780   if (!containing_function_with_abstract_origin) {
3781     return (clang::DeclContext *)ResolveBlockDIE(die);
3782   }
3783   DWARFDIE child = FindFirstChildWithAbstractOrigin(
3784       die, containing_function_with_abstract_origin);
3785   CompilerDeclContext decl_context =
3786       GetDeclContextContainingUIDFromDWARF(child);
3787   return (clang::DeclContext *)decl_context.GetOpaqueDeclContext();
3788 }
3789
3790 clang::BlockDecl *DWARFASTParserClang::ResolveBlockDIE(const DWARFDIE &die) {
3791   if (die && die.Tag() == DW_TAG_lexical_block) {
3792     clang::BlockDecl *decl =
3793         llvm::cast_or_null<clang::BlockDecl>(m_die_to_decl_ctx[die.GetDIE()]);
3794
3795     if (!decl) {
3796       DWARFDIE decl_context_die;
3797       clang::DeclContext *decl_context =
3798           GetClangDeclContextContainingDIE(die, &decl_context_die);
3799       decl = m_ast.CreateBlockDeclaration(decl_context);
3800
3801       if (decl)
3802         LinkDeclContextToDIE((clang::DeclContext *)decl, die);
3803     }
3804
3805     return decl;
3806   }
3807   return nullptr;
3808 }
3809
3810 clang::NamespaceDecl *
3811 DWARFASTParserClang::ResolveNamespaceDIE(const DWARFDIE &die) {
3812   if (die && die.Tag() == DW_TAG_namespace) {
3813     // See if we already parsed this namespace DIE and associated it with a
3814     // uniqued namespace declaration
3815     clang::NamespaceDecl *namespace_decl =
3816         static_cast<clang::NamespaceDecl *>(m_die_to_decl_ctx[die.GetDIE()]);
3817     if (namespace_decl)
3818       return namespace_decl;
3819     else {
3820       const char *namespace_name = die.GetName();
3821       clang::DeclContext *containing_decl_ctx =
3822           GetClangDeclContextContainingDIE(die, nullptr);
3823       namespace_decl = m_ast.GetUniqueNamespaceDeclaration(namespace_name,
3824                                                            containing_decl_ctx);
3825       Log *log =
3826           nullptr; // (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
3827       if (log) {
3828         SymbolFileDWARF *dwarf = die.GetDWARF();
3829         if (namespace_name) {
3830           dwarf->GetObjectFile()->GetModule()->LogMessage(
3831               log, "ASTContext => %p: 0x%8.8" PRIx64
3832                    ": DW_TAG_namespace with DW_AT_name(\"%s\") => "
3833                    "clang::NamespaceDecl *%p (original = %p)",
3834               static_cast<void *>(m_ast.getASTContext()), die.GetID(),
3835               namespace_name, static_cast<void *>(namespace_decl),
3836               static_cast<void *>(namespace_decl->getOriginalNamespace()));
3837         } else {
3838           dwarf->GetObjectFile()->GetModule()->LogMessage(
3839               log, "ASTContext => %p: 0x%8.8" PRIx64
3840                    ": DW_TAG_namespace (anonymous) => clang::NamespaceDecl *%p "
3841                    "(original = %p)",
3842               static_cast<void *>(m_ast.getASTContext()), die.GetID(),
3843               static_cast<void *>(namespace_decl),
3844               static_cast<void *>(namespace_decl->getOriginalNamespace()));
3845         }
3846       }
3847
3848       if (namespace_decl)
3849         LinkDeclContextToDIE((clang::DeclContext *)namespace_decl, die);
3850       return namespace_decl;
3851     }
3852   }
3853   return nullptr;
3854 }
3855
3856 clang::DeclContext *DWARFASTParserClang::GetClangDeclContextContainingDIE(
3857     const DWARFDIE &die, DWARFDIE *decl_ctx_die_copy) {
3858   SymbolFileDWARF *dwarf = die.GetDWARF();
3859
3860   DWARFDIE decl_ctx_die = dwarf->GetDeclContextDIEContainingDIE(die);
3861
3862   if (decl_ctx_die_copy)
3863     *decl_ctx_die_copy = decl_ctx_die;
3864
3865   if (decl_ctx_die) {
3866     clang::DeclContext *clang_decl_ctx =
3867         GetClangDeclContextForDIE(decl_ctx_die);
3868     if (clang_decl_ctx)
3869       return clang_decl_ctx;
3870   }
3871   return m_ast.GetTranslationUnitDecl();
3872 }
3873
3874 clang::DeclContext *
3875 DWARFASTParserClang::GetCachedClangDeclContextForDIE(const DWARFDIE &die) {
3876   if (die) {
3877     DIEToDeclContextMap::iterator pos = m_die_to_decl_ctx.find(die.GetDIE());
3878     if (pos != m_die_to_decl_ctx.end())
3879       return pos->second;
3880   }
3881   return nullptr;
3882 }
3883
3884 void DWARFASTParserClang::LinkDeclContextToDIE(clang::DeclContext *decl_ctx,
3885                                                const DWARFDIE &die) {
3886   m_die_to_decl_ctx[die.GetDIE()] = decl_ctx;
3887   // There can be many DIEs for a single decl context
3888   // m_decl_ctx_to_die[decl_ctx].insert(die.GetDIE());
3889   m_decl_ctx_to_die.insert(std::make_pair(decl_ctx, die));
3890 }
3891
3892 bool DWARFASTParserClang::CopyUniqueClassMethodTypes(
3893     const DWARFDIE &src_class_die, const DWARFDIE &dst_class_die,
3894     lldb_private::Type *class_type, DWARFDIECollection &failures) {
3895   if (!class_type || !src_class_die || !dst_class_die)
3896     return false;
3897   if (src_class_die.Tag() != dst_class_die.Tag())
3898     return false;
3899
3900   // We need to complete the class type so we can get all of the method types
3901   // parsed so we can then unique those types to their equivalent counterparts
3902   // in "dst_cu" and "dst_class_die"
3903   class_type->GetFullCompilerType();
3904
3905   DWARFDIE src_die;
3906   DWARFDIE dst_die;
3907   UniqueCStringMap<DWARFDIE> src_name_to_die;
3908   UniqueCStringMap<DWARFDIE> dst_name_to_die;
3909   UniqueCStringMap<DWARFDIE> src_name_to_die_artificial;
3910   UniqueCStringMap<DWARFDIE> dst_name_to_die_artificial;
3911   for (src_die = src_class_die.GetFirstChild(); src_die.IsValid();
3912        src_die = src_die.GetSibling()) {
3913     if (src_die.Tag() == DW_TAG_subprogram) {
3914       // Make sure this is a declaration and not a concrete instance by looking
3915       // for DW_AT_declaration set to 1. Sometimes concrete function instances
3916       // are placed inside the class definitions and shouldn't be included in
3917       // the list of things are are tracking here.
3918       if (src_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) == 1) {
3919         const char *src_name = src_die.GetMangledName();
3920         if (src_name) {
3921           ConstString src_const_name(src_name);
3922           if (src_die.GetAttributeValueAsUnsigned(DW_AT_artificial, 0))
3923             src_name_to_die_artificial.Append(src_const_name, src_die);
3924           else
3925             src_name_to_die.Append(src_const_name, src_die);
3926         }
3927       }
3928     }
3929   }
3930   for (dst_die = dst_class_die.GetFirstChild(); dst_die.IsValid();
3931        dst_die = dst_die.GetSibling()) {
3932     if (dst_die.Tag() == DW_TAG_subprogram) {
3933       // Make sure this is a declaration and not a concrete instance by looking
3934       // for DW_AT_declaration set to 1. Sometimes concrete function instances
3935       // are placed inside the class definitions and shouldn't be included in
3936       // the list of things are are tracking here.
3937       if (dst_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) == 1) {
3938         const char *dst_name = dst_die.GetMangledName();
3939         if (dst_name) {
3940           ConstString dst_const_name(dst_name);
3941           if (dst_die.GetAttributeValueAsUnsigned(DW_AT_artificial, 0))
3942             dst_name_to_die_artificial.Append(dst_const_name, dst_die);
3943           else
3944             dst_name_to_die.Append(dst_const_name, dst_die);
3945         }
3946       }
3947     }
3948   }
3949   const uint32_t src_size = src_name_to_die.GetSize();
3950   const uint32_t dst_size = dst_name_to_die.GetSize();
3951   Log *log = nullptr; // (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO |
3952                       // DWARF_LOG_TYPE_COMPLETION));
3953
3954   // Is everything kosher so we can go through the members at top speed?
3955   bool fast_path = true;
3956
3957   if (src_size != dst_size) {
3958     if (src_size != 0 && dst_size != 0) {
3959       if (log)
3960         log->Printf("warning: trying to unique class DIE 0x%8.8x to 0x%8.8x, "
3961                     "but they didn't have the same size (src=%d, dst=%d)",
3962                     src_class_die.GetOffset(), dst_class_die.GetOffset(),
3963                     src_size, dst_size);
3964     }
3965
3966     fast_path = false;
3967   }
3968
3969   uint32_t idx;
3970
3971   if (fast_path) {
3972     for (idx = 0; idx < src_size; ++idx) {
3973       src_die = src_name_to_die.GetValueAtIndexUnchecked(idx);
3974       dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
3975
3976       if (src_die.Tag() != dst_die.Tag()) {
3977         if (log)
3978           log->Printf("warning: tried to unique class DIE 0x%8.8x to 0x%8.8x, "
3979                       "but 0x%8.8x (%s) tags didn't match 0x%8.8x (%s)",
3980                       src_class_die.GetOffset(), dst_class_die.GetOffset(),
3981                       src_die.GetOffset(), src_die.GetTagAsCString(),
3982                       dst_die.GetOffset(), dst_die.GetTagAsCString());
3983         fast_path = false;
3984       }
3985
3986       const char *src_name = src_die.GetMangledName();
3987       const char *dst_name = dst_die.GetMangledName();
3988
3989       // Make sure the names match
3990       if (src_name == dst_name || (strcmp(src_name, dst_name) == 0))
3991         continue;
3992
3993       if (log)
3994         log->Printf("warning: tried to unique class DIE 0x%8.8x to 0x%8.8x, "
3995                     "but 0x%8.8x (%s) names didn't match 0x%8.8x (%s)",
3996                     src_class_die.GetOffset(), dst_class_die.GetOffset(),
3997                     src_die.GetOffset(), src_name, dst_die.GetOffset(),
3998                     dst_name);
3999
4000       fast_path = false;
4001     }
4002   }
4003
4004   DWARFASTParserClang *src_dwarf_ast_parser =
4005       (DWARFASTParserClang *)src_die.GetDWARFParser();
4006   DWARFASTParserClang *dst_dwarf_ast_parser =
4007       (DWARFASTParserClang *)dst_die.GetDWARFParser();
4008
4009   // Now do the work of linking the DeclContexts and Types.
4010   if (fast_path) {
4011     // We can do this quickly.  Just run across the tables index-for-index since
4012     // we know each node has matching names and tags.
4013     for (idx = 0; idx < src_size; ++idx) {
4014       src_die = src_name_to_die.GetValueAtIndexUnchecked(idx);
4015       dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
4016
4017       clang::DeclContext *src_decl_ctx =
4018           src_dwarf_ast_parser->m_die_to_decl_ctx[src_die.GetDIE()];
4019       if (src_decl_ctx) {
4020         if (log)
4021           log->Printf("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
4022                       static_cast<void *>(src_decl_ctx), src_die.GetOffset(),
4023                       dst_die.GetOffset());
4024         dst_dwarf_ast_parser->LinkDeclContextToDIE(src_decl_ctx, dst_die);
4025       } else {
4026         if (log)
4027           log->Printf("warning: tried to unique decl context from 0x%8.8x for "
4028                       "0x%8.8x, but none was found",
4029                       src_die.GetOffset(), dst_die.GetOffset());
4030       }
4031
4032       Type *src_child_type =
4033           dst_die.GetDWARF()->GetDIEToType()[src_die.GetDIE()];
4034       if (src_child_type) {
4035         if (log)
4036           log->Printf(
4037               "uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
4038               static_cast<void *>(src_child_type), src_child_type->GetID(),
4039               src_die.GetOffset(), dst_die.GetOffset());
4040         dst_die.GetDWARF()->GetDIEToType()[dst_die.GetDIE()] = src_child_type;
4041       } else {
4042         if (log)
4043           log->Printf("warning: tried to unique lldb_private::Type from "
4044                       "0x%8.8x for 0x%8.8x, but none was found",
4045                       src_die.GetOffset(), dst_die.GetOffset());
4046       }
4047     }
4048   } else {
4049     // We must do this slowly.  For each member of the destination, look
4050     // up a member in the source with the same name, check its tag, and
4051     // unique them if everything matches up.  Report failures.
4052
4053     if (!src_name_to_die.IsEmpty() && !dst_name_to_die.IsEmpty()) {
4054       src_name_to_die.Sort();
4055
4056       for (idx = 0; idx < dst_size; ++idx) {
4057         ConstString dst_name = dst_name_to_die.GetCStringAtIndex(idx);
4058         dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
4059         src_die = src_name_to_die.Find(dst_name, DWARFDIE());
4060
4061         if (src_die && (src_die.Tag() == dst_die.Tag())) {
4062           clang::DeclContext *src_decl_ctx =
4063               src_dwarf_ast_parser->m_die_to_decl_ctx[src_die.GetDIE()];
4064           if (src_decl_ctx) {
4065             if (log)
4066               log->Printf("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
4067                           static_cast<void *>(src_decl_ctx),
4068                           src_die.GetOffset(), dst_die.GetOffset());
4069             dst_dwarf_ast_parser->LinkDeclContextToDIE(src_decl_ctx, dst_die);
4070           } else {
4071             if (log)
4072               log->Printf("warning: tried to unique decl context from 0x%8.8x "
4073                           "for 0x%8.8x, but none was found",
4074                           src_die.GetOffset(), dst_die.GetOffset());
4075           }
4076
4077           Type *src_child_type =
4078               dst_die.GetDWARF()->GetDIEToType()[src_die.GetDIE()];
4079           if (src_child_type) {
4080             if (log)
4081               log->Printf("uniquing type %p (uid=0x%" PRIx64
4082                           ") from 0x%8.8x for 0x%8.8x",
4083                           static_cast<void *>(src_child_type),
4084                           src_child_type->GetID(), src_die.GetOffset(),
4085                           dst_die.GetOffset());
4086             dst_die.GetDWARF()->GetDIEToType()[dst_die.GetDIE()] =
4087                 src_child_type;
4088           } else {
4089             if (log)
4090               log->Printf("warning: tried to unique lldb_private::Type from "
4091                           "0x%8.8x for 0x%8.8x, but none was found",
4092                           src_die.GetOffset(), dst_die.GetOffset());
4093           }
4094         } else {
4095           if (log)
4096             log->Printf("warning: couldn't find a match for 0x%8.8x",
4097                         dst_die.GetOffset());
4098
4099           failures.Append(dst_die);
4100         }
4101       }
4102     }
4103   }
4104
4105   const uint32_t src_size_artificial = src_name_to_die_artificial.GetSize();
4106   const uint32_t dst_size_artificial = dst_name_to_die_artificial.GetSize();
4107
4108   if (src_size_artificial && dst_size_artificial) {
4109     dst_name_to_die_artificial.Sort();
4110
4111     for (idx = 0; idx < src_size_artificial; ++idx) {
4112       ConstString src_name_artificial =
4113           src_name_to_die_artificial.GetCStringAtIndex(idx);
4114       src_die = src_name_to_die_artificial.GetValueAtIndexUnchecked(idx);
4115       dst_die =
4116           dst_name_to_die_artificial.Find(src_name_artificial, DWARFDIE());
4117
4118       if (dst_die) {
4119         // Both classes have the artificial types, link them
4120         clang::DeclContext *src_decl_ctx =
4121             src_dwarf_ast_parser->m_die_to_decl_ctx[src_die.GetDIE()];
4122         if (src_decl_ctx) {
4123           if (log)
4124             log->Printf("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
4125                         static_cast<void *>(src_decl_ctx), src_die.GetOffset(),
4126                         dst_die.GetOffset());
4127           dst_dwarf_ast_parser->LinkDeclContextToDIE(src_decl_ctx, dst_die);
4128         } else {
4129           if (log)
4130             log->Printf("warning: tried to unique decl context from 0x%8.8x "
4131                         "for 0x%8.8x, but none was found",
4132                         src_die.GetOffset(), dst_die.GetOffset());
4133         }
4134
4135         Type *src_child_type =
4136             dst_die.GetDWARF()->GetDIEToType()[src_die.GetDIE()];
4137         if (src_child_type) {
4138           if (log)
4139             log->Printf(
4140                 "uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
4141                 static_cast<void *>(src_child_type), src_child_type->GetID(),
4142                 src_die.GetOffset(), dst_die.GetOffset());
4143           dst_die.GetDWARF()->GetDIEToType()[dst_die.GetDIE()] = src_child_type;
4144         } else {
4145           if (log)
4146             log->Printf("warning: tried to unique lldb_private::Type from "
4147                         "0x%8.8x for 0x%8.8x, but none was found",
4148                         src_die.GetOffset(), dst_die.GetOffset());
4149         }
4150       }
4151     }
4152   }
4153
4154   if (dst_size_artificial) {
4155     for (idx = 0; idx < dst_size_artificial; ++idx) {
4156       ConstString dst_name_artificial =
4157           dst_name_to_die_artificial.GetCStringAtIndex(idx);
4158       dst_die = dst_name_to_die_artificial.GetValueAtIndexUnchecked(idx);
4159       if (log)
4160         log->Printf("warning: need to create artificial method for 0x%8.8x for "
4161                     "method '%s'",
4162                     dst_die.GetOffset(), dst_name_artificial.GetCString());
4163
4164       failures.Append(dst_die);
4165     }
4166   }
4167
4168   return (failures.Size() != 0);
4169 }