1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for constructing a dwarf compile unit.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
16 #include "DwarfUnit.h"
17 #include "DwarfAccelTable.h"
18 #include "DwarfDebug.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/DIBuilder.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCSection.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/Target/Mangler.h"
29 #include "llvm/Target/TargetFrameLowering.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Support/CommandLine.h"
38 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
39 cl::desc("Generate DWARF4 type units."),
42 /// Unit - Unit constructor.
43 DwarfUnit::DwarfUnit(unsigned UID, DIE *D, DICompileUnit Node, AsmPrinter *A,
44 DwarfDebug *DW, DwarfFile *DWU)
45 : UniqueID(UID), Node(Node), UnitDie(D), DebugInfoOffset(0), Asm(A), DD(DW),
46 DU(DWU), IndexTyDie(0), Section(0), Skeleton(0) {
47 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
50 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
51 AsmPrinter *A, DwarfDebug *DW,
53 : DwarfUnit(UID, D, Node, A, DW, DWU) {
57 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DIE *D, uint16_t Language,
58 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
59 : DwarfUnit(UID, D, DICompileUnit(), A, DW, DWU), Language(Language) {}
61 /// ~Unit - Destructor for compile unit.
62 DwarfUnit::~DwarfUnit() {
63 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
64 DIEBlocks[j]->~DIEBlock();
67 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
68 /// information entry.
69 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) {
70 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
74 /// getDefaultLowerBound - Return the default lower bound for an array. If the
75 /// DWARF version doesn't handle the language, return -1.
76 int64_t DwarfUnit::getDefaultLowerBound() const {
77 switch (getLanguage()) {
81 case dwarf::DW_LANG_C89:
82 case dwarf::DW_LANG_C99:
83 case dwarf::DW_LANG_C:
84 case dwarf::DW_LANG_C_plus_plus:
85 case dwarf::DW_LANG_ObjC:
86 case dwarf::DW_LANG_ObjC_plus_plus:
89 case dwarf::DW_LANG_Fortran77:
90 case dwarf::DW_LANG_Fortran90:
91 case dwarf::DW_LANG_Fortran95:
94 // The languages below have valid values only if the DWARF version >= 4.
95 case dwarf::DW_LANG_Java:
96 case dwarf::DW_LANG_Python:
97 case dwarf::DW_LANG_UPC:
98 case dwarf::DW_LANG_D:
99 if (dwarf::DWARF_VERSION >= 4)
103 case dwarf::DW_LANG_Ada83:
104 case dwarf::DW_LANG_Ada95:
105 case dwarf::DW_LANG_Cobol74:
106 case dwarf::DW_LANG_Cobol85:
107 case dwarf::DW_LANG_Modula2:
108 case dwarf::DW_LANG_Pascal83:
109 case dwarf::DW_LANG_PLI:
110 if (dwarf::DWARF_VERSION >= 4)
118 /// Check whether the DIE for this MDNode can be shared across CUs.
119 static bool isShareableAcrossCUs(DIDescriptor D) {
120 // When the MDNode can be part of the type system, the DIE can be shared
122 // Combining type units and cross-CU DIE sharing is lower value (since
123 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
124 // level already) but may be implementable for some value in projects
125 // building multiple independent libraries with LTO and then linking those
127 return (D.isType() ||
128 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
129 !GenerateDwarfTypeUnits;
132 /// getDIE - Returns the debug information entry map slot for the
133 /// specified debug variable. We delegate the request to DwarfDebug
134 /// when the DIE for this MDNode can be shared across CUs. The mappings
135 /// will be kept in DwarfDebug for shareable DIEs.
136 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
137 if (isShareableAcrossCUs(D))
138 return DD->getDIE(D);
139 return MDNodeToDieMap.lookup(D);
142 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
143 /// when the DIE for this MDNode can be shared across CUs. The mappings
144 /// will be kept in DwarfDebug for shareable DIEs.
145 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
146 if (isShareableAcrossCUs(Desc)) {
147 DD->insertDIE(Desc, D);
150 MDNodeToDieMap.insert(std::make_pair(Desc, D));
153 /// addFlag - Add a flag that is true.
154 void DwarfUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
155 if (DD->getDwarfVersion() >= 4)
156 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
158 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
161 /// addUInt - Add an unsigned integer attribute data and value.
163 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
164 Optional<dwarf::Form> Form, uint64_t Integer) {
166 Form = DIEInteger::BestForm(false, Integer);
167 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
169 Die->addValue(Attribute, *Form, Value);
172 void DwarfUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
173 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
176 /// addSInt - Add an signed integer attribute data and value.
178 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
179 Optional<dwarf::Form> Form, int64_t Integer) {
181 Form = DIEInteger::BestForm(true, Integer);
182 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
183 Die->addValue(Attribute, *Form, Value);
186 void DwarfUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form,
188 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
191 /// addString - Add a string attribute data and value. We always emit a
192 /// reference to the string pool instead of immediate strings so that DIEs have
193 /// more predictable sizes. In the case of split dwarf we emit an index
194 /// into another table which gets us the static offset into the string
196 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute,
200 if (!DD->useSplitDwarf()) {
201 MCSymbol *Symb = DU->getStringPoolEntry(String);
202 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
203 Value = new (DIEValueAllocator) DIELabel(Symb);
205 MCSymbol *StringPool = DU->getStringPoolSym();
206 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
208 Form = dwarf::DW_FORM_strp;
210 unsigned idx = DU->getStringPoolIndex(String);
211 Value = new (DIEValueAllocator) DIEInteger(idx);
212 Form = dwarf::DW_FORM_GNU_str_index;
214 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
215 Die->addValue(Attribute, Form, Str);
218 /// addLocalString - Add a string attribute data and value. This is guaranteed
219 /// to be in the local string pool instead of indirected.
220 void DwarfUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
222 MCSymbol *Symb = DU->getStringPoolEntry(String);
224 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
225 Value = new (DIEValueAllocator) DIELabel(Symb);
227 MCSymbol *StringPool = DU->getStringPoolSym();
228 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
230 Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
233 /// addExpr - Add a Dwarf expression attribute data and value.
235 void DwarfUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
236 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
237 Die->addValue((dwarf::Attribute)0, Form, Value);
240 /// addLabel - Add a Dwarf label attribute data and value.
242 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
243 const MCSymbol *Label) {
244 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
245 Die->addValue(Attribute, Form, Value);
248 void DwarfUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
249 const MCSymbol *Label) {
250 addLabel(Die, (dwarf::Attribute)0, Form, Label);
253 /// addSectionLabel - Add a Dwarf section label attribute data and value.
255 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
256 const MCSymbol *Label) {
257 if (DD->getDwarfVersion() >= 4)
258 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
260 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
263 /// addSectionOffset - Add an offset into a section attribute data and value.
265 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
267 if (DD->getDwarfVersion() >= 4)
268 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
270 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
273 /// addLabelAddress - Add a dwarf label attribute data and value using
274 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
276 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
279 DD->addArangeLabel(SymbolCU(this, Label));
281 if (!DD->useSplitDwarf()) {
283 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
284 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
286 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
287 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
290 unsigned idx = DU->getAddrPoolIndex(Label);
291 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
292 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
296 /// addLocalLabelAddress - Add a dwarf label attribute data and value using
298 void DwarfCompileUnit::addLocalLabelAddress(DIE *Die,
299 dwarf::Attribute Attribute,
302 DD->addArangeLabel(SymbolCU(this, Label));
305 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
306 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
308 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
309 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
313 /// addOpAddress - Add a dwarf op address data and value using the
314 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
316 void DwarfUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
317 if (!DD->useSplitDwarf()) {
318 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
319 addLabel(Die, dwarf::DW_FORM_udata, Sym);
321 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
322 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
326 /// addSectionDelta - Add a section label delta attribute data and value.
328 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
329 const MCSymbol *Hi, const MCSymbol *Lo) {
330 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
331 if (DD->getDwarfVersion() >= 4)
332 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
334 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
337 /// addDIEEntry - Add a DIE attribute data and value.
339 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
340 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
343 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
344 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
345 new (DIEValueAllocator) DIETypeSignature(Type));
348 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
350 const DIE *DieCU = Die->getUnitOrNull();
351 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
353 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
354 DieCU = getUnitDie();
356 EntryCU = getUnitDie();
357 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
358 : dwarf::DW_FORM_ref_addr,
362 /// Create a DIE with the given Tag, add the DIE to its parent, and
363 /// call insertDIE if MD is not null.
364 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
365 DIE *Die = new DIE(Tag);
366 Parent.addChild(Die);
372 /// addBlock - Add block data.
374 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
376 Block->ComputeSize(Asm);
377 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
378 Die->addValue(Attribute, Block->BestForm(), Block);
381 /// addSourceLine - Add location information to specified debug information
383 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
388 unsigned Line = V.getLineNumber();
392 DD->getOrCreateSourceID(V.getContext().getFilename(),
393 V.getContext().getDirectory(), getUniqueID());
394 assert(FileID && "Invalid file id");
395 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
396 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
399 /// addSourceLine - Add location information to specified debug information
401 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
402 // Verify global variable.
403 if (!G.isGlobalVariable())
406 unsigned Line = G.getLineNumber();
410 DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(), getUniqueID());
411 assert(FileID && "Invalid file id");
412 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
413 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
416 /// addSourceLine - Add location information to specified debug information
418 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
419 // Verify subprogram.
420 if (!SP.isSubprogram())
423 // If the line number is 0, don't add it.
424 unsigned Line = SP.getLineNumber();
428 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
430 assert(FileID && "Invalid file id");
431 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
432 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
435 /// addSourceLine - Add location information to specified debug information
437 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
442 unsigned Line = Ty.getLineNumber();
445 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.getDirectory(),
447 assert(FileID && "Invalid file id");
448 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
449 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
452 /// addSourceLine - Add location information to specified debug information
454 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
456 if (!Ty.isObjCProperty())
459 unsigned Line = Ty.getLineNumber();
462 DIFile File = Ty.getFile();
463 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
464 File.getDirectory(), getUniqueID());
465 assert(FileID && "Invalid file id");
466 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
467 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
470 /// addSourceLine - Add location information to specified debug information
472 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
477 unsigned Line = NS.getLineNumber();
480 StringRef FN = NS.getFilename();
483 DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
484 assert(FileID && "Invalid file id");
485 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
486 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
489 /// addVariableAddress - Add DW_AT_location attribute for a
490 /// DbgVariable based on provided MachineLocation.
491 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
492 MachineLocation Location) {
493 if (DV.variableHasComplexAddress())
494 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
495 else if (DV.isBlockByrefVariable())
496 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
498 addAddress(Die, dwarf::DW_AT_location, Location,
499 DV.getVariable().isIndirect());
502 /// addRegisterOp - Add register operand.
503 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
504 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
505 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
507 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
509 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
510 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
514 /// addRegisterOffset - Add register offset.
515 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
517 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
518 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
519 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
520 if (Reg == TRI->getFrameRegister(*Asm->MF))
521 // If variable offset is based in frame register then use fbreg.
522 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
524 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
526 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
527 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
529 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
532 /// addAddress - Add an address attribute to a die based on the location
534 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
535 const MachineLocation &Location, bool Indirect) {
536 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
538 if (Location.isReg() && !Indirect)
539 addRegisterOp(Block, Location.getReg());
541 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
542 if (Indirect && !Location.isReg()) {
543 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
547 // Now attach the location information to the DIE.
548 addBlock(Die, Attribute, Block);
551 /// addComplexAddress - Start with the address based on the location provided,
552 /// and generate the DWARF information necessary to find the actual variable
553 /// given the extra address information encoded in the DbgVariable, starting
554 /// from the starting location. Add the DWARF information to the die.
556 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
557 dwarf::Attribute Attribute,
558 const MachineLocation &Location) {
559 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
560 unsigned N = DV.getNumAddrElements();
562 if (Location.isReg()) {
563 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
564 // If first address element is OpPlus then emit
565 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
566 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
569 addRegisterOp(Block, Location.getReg());
571 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
574 uint64_t Element = DV.getAddrElement(i);
575 if (Element == DIBuilder::OpPlus) {
576 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
577 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
578 } else if (Element == DIBuilder::OpDeref) {
579 if (!Location.isReg())
580 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
582 llvm_unreachable("unknown DIBuilder Opcode");
585 // Now attach the location information to the DIE.
586 addBlock(Die, Attribute, Block);
589 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
590 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
591 gives the variable VarName either the struct, or a pointer to the struct, as
592 its type. This is necessary for various behind-the-scenes things the
593 compiler needs to do with by-reference variables in Blocks.
595 However, as far as the original *programmer* is concerned, the variable
596 should still have type 'SomeType', as originally declared.
598 The function getBlockByrefType dives into the __Block_byref_x_VarName
599 struct to find the original type of the variable, which is then assigned to
600 the variable's Debug Information Entry as its real type. So far, so good.
601 However now the debugger will expect the variable VarName to have the type
602 SomeType. So we need the location attribute for the variable to be an
603 expression that explains to the debugger how to navigate through the
604 pointers and struct to find the actual variable of type SomeType.
606 The following function does just that. We start by getting
607 the "normal" location for the variable. This will be the location
608 of either the struct __Block_byref_x_VarName or the pointer to the
609 struct __Block_byref_x_VarName.
611 The struct will look something like:
613 struct __Block_byref_x_VarName {
615 struct __Block_byref_x_VarName *forwarding;
616 ... <various other fields>
618 ... <maybe more fields>
621 If we are given the struct directly (as our starting point) we
622 need to tell the debugger to:
624 1). Add the offset of the forwarding field.
626 2). Follow that pointer to get the real __Block_byref_x_VarName
627 struct to use (the real one may have been copied onto the heap).
629 3). Add the offset for the field VarName, to find the actual variable.
631 If we started with a pointer to the struct, then we need to
632 dereference that pointer first, before the other steps.
633 Translating this into DWARF ops, we will need to append the following
634 to the current location description for the variable:
636 DW_OP_deref -- optional, if we start with a pointer
637 DW_OP_plus_uconst <forward_fld_offset>
639 DW_OP_plus_uconst <varName_fld_offset>
641 That is what this function does. */
643 /// addBlockByrefAddress - Start with the address based on the location
644 /// provided, and generate the DWARF information necessary to find the
645 /// actual Block variable (navigating the Block struct) based on the
646 /// starting location. Add the DWARF information to the die. For
647 /// more information, read large comment just above here.
649 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
650 dwarf::Attribute Attribute,
651 const MachineLocation &Location) {
652 DIType Ty = DV.getType();
654 uint16_t Tag = Ty.getTag();
655 bool isPointer = false;
657 StringRef varName = DV.getName();
659 if (Tag == dwarf::DW_TAG_pointer_type) {
660 DIDerivedType DTy(Ty);
661 TmpTy = resolve(DTy.getTypeDerivedFrom());
665 DICompositeType blockStruct(TmpTy);
667 // Find the __forwarding field and the variable field in the __Block_byref
669 DIArray Fields = blockStruct.getTypeArray();
670 DIDerivedType varField;
671 DIDerivedType forwardingField;
673 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
674 DIDerivedType DT(Fields.getElement(i));
675 StringRef fieldName = DT.getName();
676 if (fieldName == "__forwarding")
677 forwardingField = DT;
678 else if (fieldName == varName)
682 // Get the offsets for the forwarding field and the variable field.
683 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
684 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
686 // Decode the original location, and use that as the start of the byref
687 // variable's location.
688 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
690 if (Location.isReg())
691 addRegisterOp(Block, Location.getReg());
693 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
695 // If we started with a pointer to the __Block_byref... struct, then
696 // the first thing we need to do is dereference the pointer (DW_OP_deref).
698 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
700 // Next add the offset for the '__forwarding' field:
701 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
702 // adding the offset if it's 0.
703 if (forwardingFieldOffset > 0) {
704 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
705 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
708 // Now dereference the __forwarding field to get to the real __Block_byref
709 // struct: DW_OP_deref.
710 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
712 // Now that we've got the real __Block_byref... struct, add the offset
713 // for the variable's field to get to the location of the actual variable:
714 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
715 if (varFieldOffset > 0) {
716 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
717 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
720 // Now attach the location information to the DIE.
721 addBlock(Die, Attribute, Block);
724 /// isTypeSigned - Return true if the type is signed.
725 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
726 if (Ty.isDerivedType())
727 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
729 if (Ty.isBasicType())
730 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
731 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
732 *SizeInBits = Ty.getSizeInBits();
738 /// Return true if type encoding is unsigned.
739 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
740 DIDerivedType DTy(Ty);
741 if (DTy.isDerivedType())
742 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
745 if (BTy.isBasicType()) {
746 unsigned Encoding = BTy.getEncoding();
747 if (Encoding == dwarf::DW_ATE_unsigned ||
748 Encoding == dwarf::DW_ATE_unsigned_char ||
749 Encoding == dwarf::DW_ATE_boolean)
755 /// If this type is derived from a base type then return base type size.
756 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
757 unsigned Tag = Ty.getTag();
759 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
760 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
761 Tag != dwarf::DW_TAG_restrict_type)
762 return Ty.getSizeInBits();
764 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
766 // If this type is not derived from any type then take conservative approach.
767 if (!BaseType.isValid())
768 return Ty.getSizeInBits();
770 // If this is a derived type, go ahead and get the base type, unless it's a
771 // reference then it's just the size of the field. Pointer types have no need
772 // of this since they're a different type of qualification on the type.
773 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
774 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
775 return Ty.getSizeInBits();
777 if (BaseType.isDerivedType())
778 return getBaseTypeSize(DD, DIDerivedType(BaseType));
780 return BaseType.getSizeInBits();
783 /// addConstantValue - Add constant value entry in variable DIE.
784 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
786 // FIXME: This is a bit conservative/simple - it emits negative values at
787 // their maximum bit width which is a bit unfortunate (& doesn't prefer
788 // udata/sdata over dataN as suggested by the DWARF spec)
789 assert(MO.isImm() && "Invalid machine operand!");
791 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
794 // If we're a signed constant definitely use sdata.
795 if (SignedConstant) {
796 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
800 // Else use data for now unless it's larger than we can deal with.
801 switch (SizeInBits) {
803 Form = dwarf::DW_FORM_data1;
806 Form = dwarf::DW_FORM_data2;
809 Form = dwarf::DW_FORM_data4;
812 Form = dwarf::DW_FORM_data8;
815 Form = dwarf::DW_FORM_udata;
816 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
819 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
822 /// addConstantFPValue - Add constant value entry in variable DIE.
823 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
824 assert(MO.isFPImm() && "Invalid machine operand!");
825 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
826 APFloat FPImm = MO.getFPImm()->getValueAPF();
828 // Get the raw data form of the floating point.
829 const APInt FltVal = FPImm.bitcastToAPInt();
830 const char *FltPtr = (const char *)FltVal.getRawData();
832 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
833 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
834 int Incr = (LittleEndian ? 1 : -1);
835 int Start = (LittleEndian ? 0 : NumBytes - 1);
836 int Stop = (LittleEndian ? NumBytes : -1);
838 // Output the constant to DWARF one byte at a time.
839 for (; Start != Stop; Start += Incr)
840 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
842 addBlock(Die, dwarf::DW_AT_const_value, Block);
845 /// addConstantFPValue - Add constant value entry in variable DIE.
846 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
847 // Pass this down to addConstantValue as an unsigned bag of bits.
848 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
851 /// addConstantValue - Add constant value entry in variable DIE.
852 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
854 addConstantValue(Die, CI->getValue(), Unsigned);
857 // addConstantValue - Add constant value entry in variable DIE.
858 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
859 unsigned CIBitWidth = Val.getBitWidth();
860 if (CIBitWidth <= 64) {
861 // If we're a signed constant definitely use sdata.
863 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
868 // Else use data for now unless it's larger than we can deal with.
870 switch (CIBitWidth) {
872 Form = dwarf::DW_FORM_data1;
875 Form = dwarf::DW_FORM_data2;
878 Form = dwarf::DW_FORM_data4;
881 Form = dwarf::DW_FORM_data8;
884 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
888 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
892 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
894 // Get the raw data form of the large APInt.
895 const uint64_t *Ptr64 = Val.getRawData();
897 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
898 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
900 // Output the constant to DWARF one byte at a time.
901 for (int i = 0; i < NumBytes; i++) {
904 c = Ptr64[i / 8] >> (8 * (i & 7));
906 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
907 addUInt(Block, dwarf::DW_FORM_data1, c);
910 addBlock(Die, dwarf::DW_AT_const_value, Block);
913 /// addTemplateParams - Add template parameters into buffer.
914 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
915 // Add template parameters.
916 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
917 DIDescriptor Element = TParams.getElement(i);
918 if (Element.isTemplateTypeParameter())
919 constructTemplateTypeParameterDIE(Buffer,
920 DITemplateTypeParameter(Element));
921 else if (Element.isTemplateValueParameter())
922 constructTemplateValueParameterDIE(Buffer,
923 DITemplateValueParameter(Element));
927 /// getOrCreateContextDIE - Get context owner's DIE.
928 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
929 if (!Context || Context.isFile())
931 if (Context.isType())
932 return getOrCreateTypeDIE(DIType(Context));
933 if (Context.isNameSpace())
934 return getOrCreateNameSpace(DINameSpace(Context));
935 if (Context.isSubprogram())
936 return getOrCreateSubprogramDIE(DISubprogram(Context));
937 return getDIE(Context);
940 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
941 DIScope Context = resolve(Ty.getContext());
942 DIE *ContextDIE = getOrCreateContextDIE(Context);
944 DIE *TyDIE = getDIE(Ty);
949 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
951 constructTypeDIE(*TyDIE, Ty);
953 updateAcceleratorTables(Context, Ty, TyDIE);
957 /// Return true if the type is appropriately scoped to be contained inside
958 /// its own type unit.
959 static bool isDwarfTypeUnitScoped(DIType Ty, const DwarfDebug *DD) {
960 DIScope Parent = DD->resolve(Ty.getContext());
962 // Don't generate a hash for anything scoped inside a function.
963 if (Parent.isSubprogram())
965 Parent = DD->resolve(Parent.getContext());
970 /// Return true if the type should be split out into a type unit.
971 static bool shouldCreateDwarfTypeUnit(DICompositeType CTy,
972 const DwarfDebug *DD) {
973 if (!GenerateDwarfTypeUnits)
976 uint16_t Tag = CTy.getTag();
979 case dwarf::DW_TAG_structure_type:
980 case dwarf::DW_TAG_union_type:
981 case dwarf::DW_TAG_enumeration_type:
982 case dwarf::DW_TAG_class_type:
983 // If this is a class, structure, union, or enumeration type
984 // that is a definition (not a declaration), and not scoped
985 // inside a function then separate this out as a type unit.
986 return !CTy.isForwardDecl() && isDwarfTypeUnitScoped(CTy, DD);
992 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
994 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
1001 // Construct the context before querying for the existence of the DIE in case
1002 // such construction creates the DIE.
1003 DIScope Context = resolve(Ty.getContext());
1004 DIE *ContextDIE = getOrCreateContextDIE(Context);
1007 DIE *TyDIE = getDIE(Ty);
1012 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
1014 if (Ty.isBasicType())
1015 constructTypeDIE(*TyDIE, DIBasicType(Ty));
1016 else if (Ty.isCompositeType()) {
1017 DICompositeType CTy(Ty);
1018 if (shouldCreateDwarfTypeUnit(CTy, DD)) {
1019 DD->addDwarfTypeUnitType(getLanguage(), TyDIE, CTy);
1020 // Skip updating the accellerator tables since this is not the full type
1023 constructTypeDIE(*TyDIE, CTy);
1025 assert(Ty.isDerivedType() && "Unknown kind of DIType");
1026 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
1029 updateAcceleratorTables(Context, Ty, TyDIE);
1034 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1036 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1037 bool IsImplementation = 0;
1038 if (Ty.isCompositeType()) {
1039 DICompositeType CT(Ty);
1040 // A runtime language of 0 actually means C/C++ and that any
1041 // non-negative value is some version of Objective-C/C++.
1042 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1044 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1045 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
1047 if (!Context || Context.isCompileUnit() || Context.isFile() ||
1048 Context.isNameSpace())
1049 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1053 /// addType - Add a new type attribute to the specified entity.
1054 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
1055 assert(Ty && "Trying to add a type that doesn't exist?");
1057 // Check for pre-existence.
1058 DIEEntry *Entry = getDIEEntry(Ty);
1059 // If it exists then use the existing value.
1061 addDIEEntry(Entity, Attribute, Entry);
1066 DIE *Buffer = getOrCreateTypeDIE(Ty);
1069 Entry = createDIEEntry(Buffer);
1070 insertDIEEntry(Ty, Entry);
1071 addDIEEntry(Entity, Attribute, Entry);
1074 // Accelerator table mutators - add each name along with its companion
1075 // DIE to the proper table while ensuring that the name that we're going
1076 // to reference is in the string table. We do this since the names we
1077 // add may not only be identical to the names in the DIE.
1078 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1079 DU->getStringPoolEntry(Name);
1080 std::vector<const DIE *> &DIEs = AccelNames[Name];
1081 DIEs.push_back(Die);
1084 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1085 DU->getStringPoolEntry(Name);
1086 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1087 DIEs.push_back(Die);
1090 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1091 DU->getStringPoolEntry(Name);
1092 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1093 DIEs.push_back(Die);
1096 void DwarfUnit::addAccelType(StringRef Name,
1097 std::pair<const DIE *, unsigned> Die) {
1098 DU->getStringPoolEntry(Name);
1099 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1100 DIEs.push_back(Die);
1103 /// addGlobalName - Add a new global name to the compile unit.
1104 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1105 std::string FullName = getParentContextString(Context) + Name.str();
1106 GlobalNames[FullName] = Die;
1109 /// getParentContextString - Walks the metadata parent chain in a language
1110 /// specific manner (using the compile unit language) and returns
1111 /// it as a string. This is done at the metadata level because DIEs may
1112 /// not currently have been added to the parent context and walking the
1113 /// DIEs looking for names is more expensive than walking the metadata.
1114 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1118 // FIXME: Decide whether to implement this for non-C++ languages.
1119 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1123 SmallVector<DIScope, 1> Parents;
1124 while (!Context.isCompileUnit()) {
1125 Parents.push_back(Context);
1126 if (Context.getContext())
1127 Context = resolve(Context.getContext());
1129 // Structure, etc types will have a NULL context if they're at the top
1134 // Reverse iterate over our list to go from the outermost construct to the
1136 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1140 StringRef Name = Ctx.getName();
1141 if (!Name.empty()) {
1149 /// constructTypeDIE - Construct basic type die from DIBasicType.
1150 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1151 // Get core information.
1152 StringRef Name = BTy.getName();
1153 // Add name if not anonymous or intermediate type.
1155 addString(&Buffer, dwarf::DW_AT_name, Name);
1157 // An unspecified type only has a name attribute.
1158 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1161 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1164 uint64_t Size = BTy.getSizeInBits() >> 3;
1165 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1168 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1169 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1170 // Get core information.
1171 StringRef Name = DTy.getName();
1172 uint64_t Size = DTy.getSizeInBits() >> 3;
1173 uint16_t Tag = Buffer.getTag();
1175 // Map to main type, void will not have a type.
1176 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1178 addType(&Buffer, FromTy);
1180 // Add name if not anonymous or intermediate type.
1182 addString(&Buffer, dwarf::DW_AT_name, Name);
1184 // Add size if non-zero (derived types might be zero-sized.)
1185 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1186 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1188 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1189 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1190 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1191 // Add source line info if available and TyDesc is not a forward declaration.
1192 if (!DTy.isForwardDecl())
1193 addSourceLine(&Buffer, DTy);
1196 /// constructTypeDIE - Construct type DIE from DICompositeType.
1197 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1198 // Add name if not anonymous or intermediate type.
1199 StringRef Name = CTy.getName();
1201 uint64_t Size = CTy.getSizeInBits() >> 3;
1202 uint16_t Tag = Buffer.getTag();
1205 case dwarf::DW_TAG_array_type:
1206 constructArrayTypeDIE(Buffer, CTy);
1208 case dwarf::DW_TAG_enumeration_type:
1209 constructEnumTypeDIE(Buffer, CTy);
1211 case dwarf::DW_TAG_subroutine_type: {
1212 // Add return type. A void return won't have a type.
1213 DIArray Elements = CTy.getTypeArray();
1214 DIType RTy(Elements.getElement(0));
1216 addType(&Buffer, RTy);
1218 bool isPrototyped = true;
1220 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1221 DIDescriptor Ty = Elements.getElement(i);
1222 if (Ty.isUnspecifiedParameter()) {
1223 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1224 isPrototyped = false;
1226 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1227 addType(Arg, DIType(Ty));
1228 if (DIType(Ty).isArtificial())
1229 addFlag(Arg, dwarf::DW_AT_artificial);
1232 // Add prototype flag if we're dealing with a C language and the
1233 // function has been prototyped.
1234 uint16_t Language = getLanguage();
1236 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1237 Language == dwarf::DW_LANG_ObjC))
1238 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1240 if (CTy.isLValueReference())
1241 addFlag(&Buffer, dwarf::DW_AT_reference);
1243 if (CTy.isRValueReference())
1244 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1246 case dwarf::DW_TAG_structure_type:
1247 case dwarf::DW_TAG_union_type:
1248 case dwarf::DW_TAG_class_type: {
1249 // Add elements to structure type.
1250 DIArray Elements = CTy.getTypeArray();
1251 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1252 DIDescriptor Element = Elements.getElement(i);
1253 DIE *ElemDie = NULL;
1254 if (Element.isSubprogram()) {
1255 DISubprogram SP(Element);
1256 ElemDie = getOrCreateSubprogramDIE(SP);
1257 if (SP.isProtected())
1258 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1259 dwarf::DW_ACCESS_protected);
1260 else if (SP.isPrivate())
1261 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1262 dwarf::DW_ACCESS_private);
1264 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1265 dwarf::DW_ACCESS_public);
1266 if (SP.isExplicit())
1267 addFlag(ElemDie, dwarf::DW_AT_explicit);
1268 } else if (Element.isDerivedType()) {
1269 DIDerivedType DDTy(Element);
1270 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1271 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1272 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1273 dwarf::DW_AT_friend);
1274 } else if (DDTy.isStaticMember()) {
1275 getOrCreateStaticMemberDIE(DDTy);
1277 constructMemberDIE(Buffer, DDTy);
1279 } else if (Element.isObjCProperty()) {
1280 DIObjCProperty Property(Element);
1281 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1282 StringRef PropertyName = Property.getObjCPropertyName();
1283 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1284 addType(ElemDie, Property.getType());
1285 addSourceLine(ElemDie, Property);
1286 StringRef GetterName = Property.getObjCPropertyGetterName();
1287 if (!GetterName.empty())
1288 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1289 StringRef SetterName = Property.getObjCPropertySetterName();
1290 if (!SetterName.empty())
1291 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1292 unsigned PropertyAttributes = 0;
1293 if (Property.isReadOnlyObjCProperty())
1294 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1295 if (Property.isReadWriteObjCProperty())
1296 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1297 if (Property.isAssignObjCProperty())
1298 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1299 if (Property.isRetainObjCProperty())
1300 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1301 if (Property.isCopyObjCProperty())
1302 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1303 if (Property.isNonAtomicObjCProperty())
1304 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1305 if (PropertyAttributes)
1306 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1307 PropertyAttributes);
1309 DIEEntry *Entry = getDIEEntry(Element);
1311 Entry = createDIEEntry(ElemDie);
1312 insertDIEEntry(Element, Entry);
1318 if (CTy.isAppleBlockExtension())
1319 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1321 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1323 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1324 getOrCreateTypeDIE(ContainingType));
1326 if (CTy.isObjcClassComplete())
1327 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1329 // Add template parameters to a class, structure or union types.
1330 // FIXME: The support isn't in the metadata for this yet.
1331 if (Tag == dwarf::DW_TAG_class_type ||
1332 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1333 addTemplateParams(Buffer, CTy.getTemplateParams());
1341 // Add name if not anonymous or intermediate type.
1343 addString(&Buffer, dwarf::DW_AT_name, Name);
1345 if (Tag == dwarf::DW_TAG_enumeration_type ||
1346 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1347 Tag == dwarf::DW_TAG_union_type) {
1348 // Add size if non-zero (derived types might be zero-sized.)
1349 // TODO: Do we care about size for enum forward declarations?
1351 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1352 else if (!CTy.isForwardDecl())
1353 // Add zero size if it is not a forward declaration.
1354 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1356 // If we're a forward decl, say so.
1357 if (CTy.isForwardDecl())
1358 addFlag(&Buffer, dwarf::DW_AT_declaration);
1360 // Add source line info if available.
1361 if (!CTy.isForwardDecl())
1362 addSourceLine(&Buffer, CTy);
1364 // No harm in adding the runtime language to the declaration.
1365 unsigned RLang = CTy.getRunTimeLang();
1367 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1372 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1373 /// DITemplateTypeParameter.
1374 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1375 DITemplateTypeParameter TP) {
1377 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1378 // Add the type if it exists, it could be void and therefore no type.
1380 addType(ParamDIE, resolve(TP.getType()));
1381 if (!TP.getName().empty())
1382 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1385 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1386 /// DITemplateValueParameter.
1388 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1389 DITemplateValueParameter VP) {
1390 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1392 // Add the type if there is one, template template and template parameter
1393 // packs will not have a type.
1394 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1395 addType(ParamDIE, resolve(VP.getType()));
1396 if (!VP.getName().empty())
1397 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1398 if (Value *Val = VP.getValue()) {
1399 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1400 addConstantValue(ParamDIE, CI,
1401 isUnsignedDIType(DD, resolve(VP.getType())));
1402 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1403 // For declaration non-type template parameters (such as global values and
1405 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1406 addOpAddress(Block, Asm->getSymbol(GV));
1407 // Emit DW_OP_stack_value to use the address as the immediate value of the
1408 // parameter, rather than a pointer to it.
1409 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1410 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1411 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1412 assert(isa<MDString>(Val));
1413 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1414 cast<MDString>(Val)->getString());
1415 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1416 assert(isa<MDNode>(Val));
1417 DIArray A(cast<MDNode>(Val));
1418 addTemplateParams(*ParamDIE, A);
1423 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1424 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1425 // Construct the context before querying for the existence of the DIE in case
1426 // such construction creates the DIE.
1427 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1429 DIE *NDie = getDIE(NS);
1432 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1434 if (!NS.getName().empty()) {
1435 addString(NDie, dwarf::DW_AT_name, NS.getName());
1436 addAccelNamespace(NS.getName(), NDie);
1437 addGlobalName(NS.getName(), NDie, NS.getContext());
1439 addAccelNamespace("(anonymous namespace)", NDie);
1440 addSourceLine(NDie, NS);
1444 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1445 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1446 // Construct the context before querying for the existence of the DIE in case
1447 // such construction creates the DIE (as is the case for member function
1449 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1451 DIE *SPDie = getDIE(SP);
1455 DISubprogram SPDecl = SP.getFunctionDeclaration();
1456 if (SPDecl.isSubprogram())
1457 // Add subprogram definitions to the CU die directly.
1458 ContextDIE = UnitDie.get();
1460 // DW_TAG_inlined_subroutine may refer to this DIE.
1461 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1463 DIE *DeclDie = NULL;
1464 if (SPDecl.isSubprogram())
1465 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1467 // Add function template parameters.
1468 addTemplateParams(*SPDie, SP.getTemplateParams());
1470 // If this DIE is going to refer declaration info using AT_specification
1471 // then there is no need to add other attributes.
1473 // Refer function declaration directly.
1474 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1479 // Add the linkage name if we have one.
1480 StringRef LinkageName = SP.getLinkageName();
1481 if (!LinkageName.empty())
1482 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1483 GlobalValue::getRealLinkageName(LinkageName));
1485 // Constructors and operators for anonymous aggregates do not have names.
1486 if (!SP.getName().empty())
1487 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1489 addSourceLine(SPDie, SP);
1491 // Add the prototype if we have a prototype and we have a C like
1493 uint16_t Language = getLanguage();
1494 if (SP.isPrototyped() &&
1495 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1496 Language == dwarf::DW_LANG_ObjC))
1497 addFlag(SPDie, dwarf::DW_AT_prototyped);
1499 DICompositeType SPTy = SP.getType();
1500 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1501 "the type of a subprogram should be a subroutine");
1503 DIArray Args = SPTy.getTypeArray();
1504 // Add a return type. If this is a type like a C/C++ void type we don't add a
1506 if (Args.getElement(0))
1507 addType(SPDie, DIType(Args.getElement(0)));
1509 unsigned VK = SP.getVirtuality();
1511 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1512 DIEBlock *Block = getDIEBlock();
1513 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1514 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1515 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1516 ContainingTypeMap.insert(
1517 std::make_pair(SPDie, resolve(SP.getContainingType())));
1520 if (!SP.isDefinition()) {
1521 addFlag(SPDie, dwarf::DW_AT_declaration);
1523 // Add arguments. Do not add arguments for subprogram definition. They will
1524 // be handled while processing variables.
1525 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1526 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1527 DIType ATy(Args.getElement(i));
1529 if (ATy.isArtificial())
1530 addFlag(Arg, dwarf::DW_AT_artificial);
1534 if (SP.isArtificial())
1535 addFlag(SPDie, dwarf::DW_AT_artificial);
1537 if (!SP.isLocalToUnit())
1538 addFlag(SPDie, dwarf::DW_AT_external);
1540 if (SP.isOptimized())
1541 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1543 if (unsigned isa = Asm->getISAEncoding()) {
1544 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1547 if (SP.isLValueReference())
1548 addFlag(SPDie, dwarf::DW_AT_reference);
1550 if (SP.isRValueReference())
1551 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1556 // Return const expression if value is a GEP to access merged global
1558 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1559 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1560 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1561 if (!CE || CE->getNumOperands() != 3 ||
1562 CE->getOpcode() != Instruction::GetElementPtr)
1565 // First operand points to a global struct.
1566 Value *Ptr = CE->getOperand(0);
1567 if (!isa<GlobalValue>(Ptr) ||
1568 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1571 // Second operand is zero.
1572 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1573 if (!CI || !CI->isZero())
1576 // Third operand is offset.
1577 if (!isa<ConstantInt>(CE->getOperand(2)))
1583 /// createGlobalVariableDIE - create global variable DIE.
1584 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1585 // Check for pre-existence.
1589 if (!GV.isGlobalVariable())
1592 DIScope GVContext = GV.getContext();
1593 DIType GTy = GV.getType();
1595 // If this is a static data member definition, some attributes belong
1596 // to the declaration DIE.
1597 DIE *VariableDIE = NULL;
1598 bool IsStaticMember = false;
1599 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1600 if (SDMDecl.Verify()) {
1601 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1602 // We need the declaration DIE that is in the static member's class.
1603 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1604 IsStaticMember = true;
1607 // If this is not a static data member definition, create the variable
1608 // DIE and add the initial set of attributes to it.
1610 // Construct the context before querying for the existence of the DIE in
1611 // case such construction creates the DIE.
1612 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1615 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1617 // Add name and type.
1618 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1619 addType(VariableDIE, GTy);
1621 // Add scoping info.
1622 if (!GV.isLocalToUnit())
1623 addFlag(VariableDIE, dwarf::DW_AT_external);
1625 // Add line number info.
1626 addSourceLine(VariableDIE, GV);
1630 bool addToAccelTable = false;
1631 DIE *VariableSpecDIE = NULL;
1632 bool isGlobalVariable = GV.getGlobal() != NULL;
1633 if (isGlobalVariable) {
1634 addToAccelTable = true;
1635 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1636 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1637 if (GV.getGlobal()->isThreadLocal()) {
1638 // FIXME: Make this work with -gsplit-dwarf.
1639 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1640 assert((PointerSize == 4 || PointerSize == 8) &&
1641 "Add support for other sizes if necessary");
1642 const MCExpr *Expr =
1643 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1644 // Based on GCC's support for TLS:
1645 if (!DD->useSplitDwarf()) {
1646 // 1) Start with a constNu of the appropriate pointer size
1647 addUInt(Block, dwarf::DW_FORM_data1,
1648 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1649 // 2) containing the (relocated) offset of the TLS variable
1650 // within the module's TLS block.
1651 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1653 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1654 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1656 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1657 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1659 DD->addArangeLabel(SymbolCU(this, Sym));
1660 addOpAddress(Block, Sym);
1662 // Do not create specification DIE if context is either compile unit
1664 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1665 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1666 // Create specification DIE.
1667 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1668 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1669 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1670 // A static member's declaration is already flagged as such.
1671 if (!SDMDecl.Verify())
1672 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1674 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1676 // Add the linkage name.
1677 StringRef LinkageName = GV.getLinkageName();
1678 if (!LinkageName.empty())
1679 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1680 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1682 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1684 dwarf::DW_AT_MIPS_linkage_name,
1685 GlobalValue::getRealLinkageName(LinkageName));
1686 } else if (const ConstantInt *CI =
1687 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1688 // AT_const_value was added when the static member was created. To avoid
1689 // emitting AT_const_value multiple times, we only add AT_const_value when
1690 // it is not a static member.
1691 if (!IsStaticMember)
1692 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1693 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1694 addToAccelTable = true;
1695 // GV is a merged global.
1696 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1697 Value *Ptr = CE->getOperand(0);
1698 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1699 DD->addArangeLabel(SymbolCU(this, Sym));
1700 addOpAddress(Block, Sym);
1701 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1702 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1703 addUInt(Block, dwarf::DW_FORM_udata,
1704 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1705 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1706 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1709 if (addToAccelTable) {
1710 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1711 addAccelName(GV.getName(), AddrDIE);
1713 // If the linkage name is different than the name, go ahead and output
1714 // that as well into the name table.
1715 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1716 addAccelName(GV.getLinkageName(), AddrDIE);
1719 if (!GV.isLocalToUnit())
1720 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1724 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1725 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1726 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1727 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1729 // The LowerBound value defines the lower bounds which is typically zero for
1730 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1731 // Count == -1 then the array is unbounded and we do not emit
1732 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1733 // Count == 0, then the array has zero elements in which case we do not emit
1735 int64_t LowerBound = SR.getLo();
1736 int64_t DefaultLowerBound = getDefaultLowerBound();
1737 int64_t Count = SR.getCount();
1739 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1740 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1742 if (Count != -1 && Count != 0)
1743 // FIXME: An unbounded array should reference the expression that defines
1745 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1746 LowerBound + Count - 1);
1749 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1750 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1752 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1754 // Emit the element type.
1755 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1757 // Get an anonymous type for index type.
1758 // FIXME: This type should be passed down from the front end
1759 // as different languages may have different sizes for indexes.
1760 DIE *IdxTy = getIndexTyDie();
1762 // Construct an anonymous type for index type.
1763 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1764 addString(IdxTy, dwarf::DW_AT_name, "int");
1765 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1766 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1767 dwarf::DW_ATE_signed);
1768 setIndexTyDie(IdxTy);
1771 // Add subranges to array type.
1772 DIArray Elements = CTy.getTypeArray();
1773 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1774 DIDescriptor Element = Elements.getElement(i);
1775 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1776 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1780 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1781 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1782 DIArray Elements = CTy.getTypeArray();
1784 // Add enumerators to enumeration type.
1785 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1786 DIEnumerator Enum(Elements.getElement(i));
1787 if (Enum.isEnumerator()) {
1788 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1789 StringRef Name = Enum.getName();
1790 addString(Enumerator, dwarf::DW_AT_name, Name);
1791 int64_t Value = Enum.getEnumValue();
1792 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1795 // Add the enumerator to the __apple_names accelerator table.
1796 addAccelName(Name, Enumerator);
1799 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1801 addType(&Buffer, DTy);
1802 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1806 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1808 void DwarfUnit::constructContainingTypeDIEs() {
1809 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1810 CE = ContainingTypeMap.end();
1812 DIE *SPDie = CI->first;
1813 DIDescriptor D(CI->second);
1816 DIE *NDie = getDIE(D);
1819 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1823 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1824 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1825 StringRef Name = DV.getName();
1827 // Define variable debug information entry.
1828 DIE *VariableDie = new DIE(DV.getTag());
1829 DbgVariable *AbsVar = DV.getAbstractVariable();
1830 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1832 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1835 addString(VariableDie, dwarf::DW_AT_name, Name);
1836 addSourceLine(VariableDie, DV.getVariable());
1837 addType(VariableDie, DV.getType());
1840 if (DV.isArtificial())
1841 addFlag(VariableDie, dwarf::DW_AT_artificial);
1843 if (isScopeAbstract) {
1844 DV.setDIE(VariableDie);
1848 // Add variable address.
1850 unsigned Offset = DV.getDotDebugLocOffset();
1851 if (Offset != ~0U) {
1852 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1853 Asm->GetTempSymbol("debug_loc", Offset));
1854 DV.setDIE(VariableDie);
1858 // Check if variable is described by a DBG_VALUE instruction.
1859 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1860 assert(DVInsn->getNumOperands() == 3);
1861 if (DVInsn->getOperand(0).isReg()) {
1862 const MachineOperand RegOp = DVInsn->getOperand(0);
1863 // If the second operand is an immediate, this is an indirect value.
1864 if (DVInsn->getOperand(1).isImm()) {
1865 MachineLocation Location(RegOp.getReg(),
1866 DVInsn->getOperand(1).getImm());
1867 addVariableAddress(DV, VariableDie, Location);
1868 } else if (RegOp.getReg())
1869 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1870 } else if (DVInsn->getOperand(0).isImm())
1871 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1872 else if (DVInsn->getOperand(0).isFPImm())
1873 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1874 else if (DVInsn->getOperand(0).isCImm())
1875 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1876 isUnsignedDIType(DD, DV.getType()));
1878 DV.setDIE(VariableDie);
1881 // .. else use frame index.
1882 int FI = DV.getFrameIndex();
1884 unsigned FrameReg = 0;
1885 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1886 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1887 MachineLocation Location(FrameReg, Offset);
1888 addVariableAddress(DV, VariableDie, Location);
1892 DV.setDIE(VariableDie);
1896 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1897 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1898 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1899 StringRef Name = DT.getName();
1901 addString(MemberDie, dwarf::DW_AT_name, Name);
1903 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1905 addSourceLine(MemberDie, DT);
1907 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1908 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1910 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1912 // For C++, virtual base classes are not at fixed offset. Use following
1913 // expression to extract appropriate offset from vtable.
1914 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1916 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1917 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1918 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1919 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1920 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1921 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1922 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1923 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1925 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1927 uint64_t Size = DT.getSizeInBits();
1928 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1929 uint64_t OffsetInBytes;
1931 if (Size != FieldSize) {
1933 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1934 getBaseTypeSize(DD, DT) >> 3);
1935 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1937 uint64_t Offset = DT.getOffsetInBits();
1938 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1939 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1940 uint64_t FieldOffset = (HiMark - FieldSize);
1941 Offset -= FieldOffset;
1943 // Maybe we need to work from the other end.
1944 if (Asm->getDataLayout().isLittleEndian())
1945 Offset = FieldSize - (Offset + Size);
1946 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1948 // Here WD_AT_data_member_location points to the anonymous
1949 // field that includes this bit field.
1950 OffsetInBytes = FieldOffset >> 3;
1952 // This is not a bitfield.
1953 OffsetInBytes = DT.getOffsetInBits() >> 3;
1954 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None, OffsetInBytes);
1957 if (DT.isProtected())
1958 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1959 dwarf::DW_ACCESS_protected);
1960 else if (DT.isPrivate())
1961 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1962 dwarf::DW_ACCESS_private);
1963 // Otherwise C++ member and base classes are considered public.
1965 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1966 dwarf::DW_ACCESS_public);
1968 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1969 dwarf::DW_VIRTUALITY_virtual);
1971 // Objective-C properties.
1972 if (MDNode *PNode = DT.getObjCProperty())
1973 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1974 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1977 if (DT.isArtificial())
1978 addFlag(MemberDie, dwarf::DW_AT_artificial);
1981 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1982 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1986 // Construct the context before querying for the existence of the DIE in case
1987 // such construction creates the DIE.
1988 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1989 assert(dwarf::isType(ContextDIE->getTag()) &&
1990 "Static member should belong to a type.");
1992 DIE *StaticMemberDIE = getDIE(DT);
1993 if (StaticMemberDIE)
1994 return StaticMemberDIE;
1996 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1998 DIType Ty = resolve(DT.getTypeDerivedFrom());
2000 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
2001 addType(StaticMemberDIE, Ty);
2002 addSourceLine(StaticMemberDIE, DT);
2003 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
2004 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
2006 // FIXME: We could omit private if the parent is a class_type, and
2007 // public if the parent is something else.
2008 if (DT.isProtected())
2009 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2010 dwarf::DW_ACCESS_protected);
2011 else if (DT.isPrivate())
2012 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2013 dwarf::DW_ACCESS_private);
2015 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2016 dwarf::DW_ACCESS_public);
2018 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2019 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
2020 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2021 addConstantFPValue(StaticMemberDIE, CFP);
2023 return StaticMemberDIE;
2026 void DwarfUnit::emitHeader(const MCSection *ASection,
2027 const MCSymbol *ASectionSym) const {
2028 Asm->OutStreamer.AddComment("DWARF version number");
2029 Asm->EmitInt16(DD->getDwarfVersion());
2030 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2031 // We share one abbreviations table across all units so it's always at the
2032 // start of the section. Use a relocatable offset where needed to ensure
2033 // linking doesn't invalidate that offset.
2034 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2035 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2036 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2039 DwarfCompileUnit::~DwarfCompileUnit() {}
2040 DwarfTypeUnit::~DwarfTypeUnit() {}
2042 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
2043 const MCSymbol *ASectionSym) const {
2044 DwarfUnit::emitHeader(ASection, ASectionSym);
2045 Asm->OutStreamer.AddComment("Type Signature");
2046 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2047 Asm->OutStreamer.AddComment("Type DIE Offset");
2048 Asm->OutStreamer.EmitIntValue(Ty->getOffset(), sizeof(Ty->getOffset()));
2051 void DwarfTypeUnit::initSection(const MCSection *Section) {
2052 assert(!this->Section);
2053 this->Section = Section;
2054 // Since each type unit is contained in its own COMDAT section, the begin
2055 // label and the section label are the same. Using the begin label emission in
2056 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2057 // the only other alternative of lazily constructing start-of-section labels
2058 // and storing a mapping in DwarfDebug (or AsmPrinter).
2059 this->SectionSym = this->LabelBegin =
2060 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2062 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2063 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());