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) {
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 /// addOpAddress - Add a dwarf op address data and value using the
297 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
299 void DwarfUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
300 if (!DD->useSplitDwarf()) {
301 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
302 addLabel(Die, dwarf::DW_FORM_udata, Sym);
304 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
305 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
309 /// addSectionDelta - Add a section label delta attribute data and value.
311 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
312 const MCSymbol *Hi, const MCSymbol *Lo) {
313 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
314 if (DD->getDwarfVersion() >= 4)
315 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
317 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
320 /// addDIEEntry - Add a DIE attribute data and value.
322 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
323 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
326 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
327 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
328 new (DIEValueAllocator) DIETypeSignature(Type));
331 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
333 const DIE *DieCU = Die->getUnitOrNull();
334 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
336 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
337 DieCU = getUnitDie();
339 EntryCU = getUnitDie();
340 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
341 : dwarf::DW_FORM_ref_addr,
345 /// Create a DIE with the given Tag, add the DIE to its parent, and
346 /// call insertDIE if MD is not null.
347 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
348 DIE *Die = new DIE(Tag);
349 Parent.addChild(Die);
355 /// addBlock - Add block data.
357 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
359 Block->ComputeSize(Asm);
360 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
361 Die->addValue(Attribute, Block->BestForm(), Block);
364 /// addSourceLine - Add location information to specified debug information
366 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
371 unsigned Line = V.getLineNumber();
375 DD->getOrCreateSourceID(V.getContext().getFilename(),
376 V.getContext().getDirectory(), getUniqueID());
377 assert(FileID && "Invalid file id");
378 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
379 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
382 /// addSourceLine - Add location information to specified debug information
384 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
385 // Verify global variable.
386 if (!G.isGlobalVariable())
389 unsigned Line = G.getLineNumber();
393 DD->getOrCreateSourceID(G.getFilename(), G.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, DISubprogram SP) {
402 // Verify subprogram.
403 if (!SP.isSubprogram())
406 // If the line number is 0, don't add it.
407 unsigned Line = SP.getLineNumber();
411 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
413 assert(FileID && "Invalid file id");
414 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
415 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
418 /// addSourceLine - Add location information to specified debug information
420 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
425 unsigned Line = Ty.getLineNumber();
428 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.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, DIObjCProperty Ty) {
439 if (!Ty.isObjCProperty())
442 unsigned Line = Ty.getLineNumber();
445 DIFile File = Ty.getFile();
446 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
447 File.getDirectory(), getUniqueID());
448 assert(FileID && "Invalid file id");
449 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
450 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
453 /// addSourceLine - Add location information to specified debug information
455 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
460 unsigned Line = NS.getLineNumber();
463 StringRef FN = NS.getFilename();
466 DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
467 assert(FileID && "Invalid file id");
468 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
469 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
472 /// addVariableAddress - Add DW_AT_location attribute for a
473 /// DbgVariable based on provided MachineLocation.
474 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
475 MachineLocation Location) {
476 if (DV.variableHasComplexAddress())
477 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
478 else if (DV.isBlockByrefVariable())
479 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
481 addAddress(Die, dwarf::DW_AT_location, Location,
482 DV.getVariable().isIndirect());
485 /// addRegisterOp - Add register operand.
486 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
487 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
488 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
490 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
492 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
493 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
497 /// addRegisterOffset - Add register offset.
498 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
500 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
501 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
502 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
503 if (Reg == TRI->getFrameRegister(*Asm->MF))
504 // If variable offset is based in frame register then use fbreg.
505 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
507 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
509 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
510 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
512 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
515 /// addAddress - Add an address attribute to a die based on the location
517 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
518 const MachineLocation &Location, bool Indirect) {
519 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
521 if (Location.isReg() && !Indirect)
522 addRegisterOp(Block, Location.getReg());
524 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
525 if (Indirect && !Location.isReg()) {
526 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
530 // Now attach the location information to the DIE.
531 addBlock(Die, Attribute, Block);
534 /// addComplexAddress - Start with the address based on the location provided,
535 /// and generate the DWARF information necessary to find the actual variable
536 /// given the extra address information encoded in the DbgVariable, starting
537 /// from the starting location. Add the DWARF information to the die.
539 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
540 dwarf::Attribute Attribute,
541 const MachineLocation &Location) {
542 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
543 unsigned N = DV.getNumAddrElements();
545 if (Location.isReg()) {
546 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
547 // If first address element is OpPlus then emit
548 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
549 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
552 addRegisterOp(Block, Location.getReg());
554 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
557 uint64_t Element = DV.getAddrElement(i);
558 if (Element == DIBuilder::OpPlus) {
559 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
560 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
561 } else if (Element == DIBuilder::OpDeref) {
562 if (!Location.isReg())
563 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
565 llvm_unreachable("unknown DIBuilder Opcode");
568 // Now attach the location information to the DIE.
569 addBlock(Die, Attribute, Block);
572 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
573 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
574 gives the variable VarName either the struct, or a pointer to the struct, as
575 its type. This is necessary for various behind-the-scenes things the
576 compiler needs to do with by-reference variables in Blocks.
578 However, as far as the original *programmer* is concerned, the variable
579 should still have type 'SomeType', as originally declared.
581 The function getBlockByrefType dives into the __Block_byref_x_VarName
582 struct to find the original type of the variable, which is then assigned to
583 the variable's Debug Information Entry as its real type. So far, so good.
584 However now the debugger will expect the variable VarName to have the type
585 SomeType. So we need the location attribute for the variable to be an
586 expression that explains to the debugger how to navigate through the
587 pointers and struct to find the actual variable of type SomeType.
589 The following function does just that. We start by getting
590 the "normal" location for the variable. This will be the location
591 of either the struct __Block_byref_x_VarName or the pointer to the
592 struct __Block_byref_x_VarName.
594 The struct will look something like:
596 struct __Block_byref_x_VarName {
598 struct __Block_byref_x_VarName *forwarding;
599 ... <various other fields>
601 ... <maybe more fields>
604 If we are given the struct directly (as our starting point) we
605 need to tell the debugger to:
607 1). Add the offset of the forwarding field.
609 2). Follow that pointer to get the real __Block_byref_x_VarName
610 struct to use (the real one may have been copied onto the heap).
612 3). Add the offset for the field VarName, to find the actual variable.
614 If we started with a pointer to the struct, then we need to
615 dereference that pointer first, before the other steps.
616 Translating this into DWARF ops, we will need to append the following
617 to the current location description for the variable:
619 DW_OP_deref -- optional, if we start with a pointer
620 DW_OP_plus_uconst <forward_fld_offset>
622 DW_OP_plus_uconst <varName_fld_offset>
624 That is what this function does. */
626 /// addBlockByrefAddress - Start with the address based on the location
627 /// provided, and generate the DWARF information necessary to find the
628 /// actual Block variable (navigating the Block struct) based on the
629 /// starting location. Add the DWARF information to the die. For
630 /// more information, read large comment just above here.
632 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
633 dwarf::Attribute Attribute,
634 const MachineLocation &Location) {
635 DIType Ty = DV.getType();
637 uint16_t Tag = Ty.getTag();
638 bool isPointer = false;
640 StringRef varName = DV.getName();
642 if (Tag == dwarf::DW_TAG_pointer_type) {
643 DIDerivedType DTy(Ty);
644 TmpTy = resolve(DTy.getTypeDerivedFrom());
648 DICompositeType blockStruct(TmpTy);
650 // Find the __forwarding field and the variable field in the __Block_byref
652 DIArray Fields = blockStruct.getTypeArray();
653 DIDerivedType varField;
654 DIDerivedType forwardingField;
656 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
657 DIDerivedType DT(Fields.getElement(i));
658 StringRef fieldName = DT.getName();
659 if (fieldName == "__forwarding")
660 forwardingField = DT;
661 else if (fieldName == varName)
665 // Get the offsets for the forwarding field and the variable field.
666 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
667 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
669 // Decode the original location, and use that as the start of the byref
670 // variable's location.
671 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
673 if (Location.isReg())
674 addRegisterOp(Block, Location.getReg());
676 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
678 // If we started with a pointer to the __Block_byref... struct, then
679 // the first thing we need to do is dereference the pointer (DW_OP_deref).
681 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
683 // Next add the offset for the '__forwarding' field:
684 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
685 // adding the offset if it's 0.
686 if (forwardingFieldOffset > 0) {
687 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
688 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
691 // Now dereference the __forwarding field to get to the real __Block_byref
692 // struct: DW_OP_deref.
693 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
695 // Now that we've got the real __Block_byref... struct, add the offset
696 // for the variable's field to get to the location of the actual variable:
697 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
698 if (varFieldOffset > 0) {
699 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
700 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
703 // Now attach the location information to the DIE.
704 addBlock(Die, Attribute, Block);
707 /// isTypeSigned - Return true if the type is signed.
708 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
709 if (Ty.isDerivedType())
710 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
712 if (Ty.isBasicType())
713 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
714 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
715 *SizeInBits = Ty.getSizeInBits();
721 /// Return true if type encoding is unsigned.
722 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
723 DIDerivedType DTy(Ty);
724 if (DTy.isDerivedType())
725 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
728 if (BTy.isBasicType()) {
729 unsigned Encoding = BTy.getEncoding();
730 if (Encoding == dwarf::DW_ATE_unsigned ||
731 Encoding == dwarf::DW_ATE_unsigned_char ||
732 Encoding == dwarf::DW_ATE_boolean)
738 /// If this type is derived from a base type then return base type size.
739 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
740 unsigned Tag = Ty.getTag();
742 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
743 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
744 Tag != dwarf::DW_TAG_restrict_type)
745 return Ty.getSizeInBits();
747 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
749 // If this type is not derived from any type then take conservative approach.
750 if (!BaseType.isValid())
751 return Ty.getSizeInBits();
753 // If this is a derived type, go ahead and get the base type, unless it's a
754 // reference then it's just the size of the field. Pointer types have no need
755 // of this since they're a different type of qualification on the type.
756 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
757 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
758 return Ty.getSizeInBits();
760 if (BaseType.isDerivedType())
761 return getBaseTypeSize(DD, DIDerivedType(BaseType));
763 return BaseType.getSizeInBits();
766 /// addConstantValue - Add constant value entry in variable DIE.
767 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
769 // FIXME: This is a bit conservative/simple - it emits negative values at
770 // their maximum bit width which is a bit unfortunate (& doesn't prefer
771 // udata/sdata over dataN as suggested by the DWARF spec)
772 assert(MO.isImm() && "Invalid machine operand!");
774 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
777 // If we're a signed constant definitely use sdata.
778 if (SignedConstant) {
779 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
783 // Else use data for now unless it's larger than we can deal with.
784 switch (SizeInBits) {
786 Form = dwarf::DW_FORM_data1;
789 Form = dwarf::DW_FORM_data2;
792 Form = dwarf::DW_FORM_data4;
795 Form = dwarf::DW_FORM_data8;
798 Form = dwarf::DW_FORM_udata;
799 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
802 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
805 /// addConstantFPValue - Add constant value entry in variable DIE.
806 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
807 assert(MO.isFPImm() && "Invalid machine operand!");
808 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
809 APFloat FPImm = MO.getFPImm()->getValueAPF();
811 // Get the raw data form of the floating point.
812 const APInt FltVal = FPImm.bitcastToAPInt();
813 const char *FltPtr = (const char *)FltVal.getRawData();
815 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
816 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
817 int Incr = (LittleEndian ? 1 : -1);
818 int Start = (LittleEndian ? 0 : NumBytes - 1);
819 int Stop = (LittleEndian ? NumBytes : -1);
821 // Output the constant to DWARF one byte at a time.
822 for (; Start != Stop; Start += Incr)
823 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
825 addBlock(Die, dwarf::DW_AT_const_value, Block);
828 /// addConstantFPValue - Add constant value entry in variable DIE.
829 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
830 // Pass this down to addConstantValue as an unsigned bag of bits.
831 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
834 /// addConstantValue - Add constant value entry in variable DIE.
835 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
837 addConstantValue(Die, CI->getValue(), Unsigned);
840 // addConstantValue - Add constant value entry in variable DIE.
841 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
842 unsigned CIBitWidth = Val.getBitWidth();
843 if (CIBitWidth <= 64) {
844 // If we're a signed constant definitely use sdata.
846 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
851 // Else use data for now unless it's larger than we can deal with.
853 switch (CIBitWidth) {
855 Form = dwarf::DW_FORM_data1;
858 Form = dwarf::DW_FORM_data2;
861 Form = dwarf::DW_FORM_data4;
864 Form = dwarf::DW_FORM_data8;
867 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
871 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
875 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
877 // Get the raw data form of the large APInt.
878 const uint64_t *Ptr64 = Val.getRawData();
880 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
881 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
883 // Output the constant to DWARF one byte at a time.
884 for (int i = 0; i < NumBytes; i++) {
887 c = Ptr64[i / 8] >> (8 * (i & 7));
889 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
890 addUInt(Block, dwarf::DW_FORM_data1, c);
893 addBlock(Die, dwarf::DW_AT_const_value, Block);
896 /// addTemplateParams - Add template parameters into buffer.
897 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
898 // Add template parameters.
899 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
900 DIDescriptor Element = TParams.getElement(i);
901 if (Element.isTemplateTypeParameter())
902 constructTemplateTypeParameterDIE(Buffer,
903 DITemplateTypeParameter(Element));
904 else if (Element.isTemplateValueParameter())
905 constructTemplateValueParameterDIE(Buffer,
906 DITemplateValueParameter(Element));
910 /// getOrCreateContextDIE - Get context owner's DIE.
911 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
912 if (!Context || Context.isFile())
914 if (Context.isType())
915 return getOrCreateTypeDIE(DIType(Context));
916 if (Context.isNameSpace())
917 return getOrCreateNameSpace(DINameSpace(Context));
918 if (Context.isSubprogram())
919 return getOrCreateSubprogramDIE(DISubprogram(Context));
920 return getDIE(Context);
923 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
924 DIScope Context = resolve(Ty.getContext());
925 DIE *ContextDIE = getOrCreateContextDIE(Context);
927 DIE *TyDIE = getDIE(Ty);
932 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
934 constructTypeDIE(*TyDIE, Ty);
936 updateAcceleratorTables(Context, Ty, TyDIE);
940 /// Return true if the type is appropriately scoped to be contained inside
941 /// its own type unit.
942 static bool isDwarfTypeUnitScoped(DIType Ty, const DwarfDebug *DD) {
943 DIScope Parent = DD->resolve(Ty.getContext());
945 // Don't generate a hash for anything scoped inside a function.
946 if (Parent.isSubprogram())
948 Parent = DD->resolve(Parent.getContext());
953 /// Return true if the type should be split out into a type unit.
954 static bool shouldCreateDwarfTypeUnit(DICompositeType CTy,
955 const DwarfDebug *DD) {
956 if (!GenerateDwarfTypeUnits)
959 uint16_t Tag = CTy.getTag();
962 case dwarf::DW_TAG_structure_type:
963 case dwarf::DW_TAG_union_type:
964 case dwarf::DW_TAG_enumeration_type:
965 case dwarf::DW_TAG_class_type:
966 // If this is a class, structure, union, or enumeration type
967 // that is a definition (not a declaration), and not scoped
968 // inside a function then separate this out as a type unit.
969 return !CTy.isForwardDecl() && isDwarfTypeUnitScoped(CTy, DD);
975 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
977 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
984 // Construct the context before querying for the existence of the DIE in case
985 // such construction creates the DIE.
986 DIScope Context = resolve(Ty.getContext());
987 DIE *ContextDIE = getOrCreateContextDIE(Context);
990 DIE *TyDIE = getDIE(Ty);
995 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
997 if (Ty.isBasicType())
998 constructTypeDIE(*TyDIE, DIBasicType(Ty));
999 else if (Ty.isCompositeType()) {
1000 DICompositeType CTy(Ty);
1001 if (shouldCreateDwarfTypeUnit(CTy, DD)) {
1002 DD->addDwarfTypeUnitType(getLanguage(), TyDIE, CTy);
1003 // Skip updating the accellerator tables since this is not the full type
1006 constructTypeDIE(*TyDIE, CTy);
1008 assert(Ty.isDerivedType() && "Unknown kind of DIType");
1009 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
1012 updateAcceleratorTables(Context, Ty, TyDIE);
1017 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1019 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1020 bool IsImplementation = 0;
1021 if (Ty.isCompositeType()) {
1022 DICompositeType CT(Ty);
1023 // A runtime language of 0 actually means C/C++ and that any
1024 // non-negative value is some version of Objective-C/C++.
1025 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1027 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1028 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
1030 if (!Context || Context.isCompileUnit() || Context.isFile() ||
1031 Context.isNameSpace())
1032 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1036 /// addType - Add a new type attribute to the specified entity.
1037 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
1038 assert(Ty && "Trying to add a type that doesn't exist?");
1040 // Check for pre-existence.
1041 DIEEntry *Entry = getDIEEntry(Ty);
1042 // If it exists then use the existing value.
1044 addDIEEntry(Entity, Attribute, Entry);
1049 DIE *Buffer = getOrCreateTypeDIE(Ty);
1052 Entry = createDIEEntry(Buffer);
1053 insertDIEEntry(Ty, Entry);
1054 addDIEEntry(Entity, Attribute, Entry);
1057 // Accelerator table mutators - add each name along with its companion
1058 // DIE to the proper table while ensuring that the name that we're going
1059 // to reference is in the string table. We do this since the names we
1060 // add may not only be identical to the names in the DIE.
1061 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1062 DU->getStringPoolEntry(Name);
1063 std::vector<const DIE *> &DIEs = AccelNames[Name];
1064 DIEs.push_back(Die);
1067 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1068 DU->getStringPoolEntry(Name);
1069 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1070 DIEs.push_back(Die);
1073 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1074 DU->getStringPoolEntry(Name);
1075 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1076 DIEs.push_back(Die);
1079 void DwarfUnit::addAccelType(StringRef Name,
1080 std::pair<const DIE *, unsigned> Die) {
1081 DU->getStringPoolEntry(Name);
1082 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1083 DIEs.push_back(Die);
1086 /// addGlobalName - Add a new global name to the compile unit.
1087 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1088 std::string FullName = getParentContextString(Context) + Name.str();
1089 GlobalNames[FullName] = Die;
1092 /// getParentContextString - Walks the metadata parent chain in a language
1093 /// specific manner (using the compile unit language) and returns
1094 /// it as a string. This is done at the metadata level because DIEs may
1095 /// not currently have been added to the parent context and walking the
1096 /// DIEs looking for names is more expensive than walking the metadata.
1097 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1101 // FIXME: Decide whether to implement this for non-C++ languages.
1102 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1106 SmallVector<DIScope, 1> Parents;
1107 while (!Context.isCompileUnit()) {
1108 Parents.push_back(Context);
1109 if (Context.getContext())
1110 Context = resolve(Context.getContext());
1112 // Structure, etc types will have a NULL context if they're at the top
1117 // Reverse iterate over our list to go from the outermost construct to the
1119 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1123 StringRef Name = Ctx.getName();
1124 if (!Name.empty()) {
1132 /// constructTypeDIE - Construct basic type die from DIBasicType.
1133 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1134 // Get core information.
1135 StringRef Name = BTy.getName();
1136 // Add name if not anonymous or intermediate type.
1138 addString(&Buffer, dwarf::DW_AT_name, Name);
1140 // An unspecified type only has a name attribute.
1141 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1144 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1147 uint64_t Size = BTy.getSizeInBits() >> 3;
1148 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1151 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1152 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1153 // Get core information.
1154 StringRef Name = DTy.getName();
1155 uint64_t Size = DTy.getSizeInBits() >> 3;
1156 uint16_t Tag = Buffer.getTag();
1158 // Map to main type, void will not have a type.
1159 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1161 addType(&Buffer, FromTy);
1163 // Add name if not anonymous or intermediate type.
1165 addString(&Buffer, dwarf::DW_AT_name, Name);
1167 // Add size if non-zero (derived types might be zero-sized.)
1168 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1169 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1171 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1172 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1173 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1174 // Add source line info if available and TyDesc is not a forward declaration.
1175 if (!DTy.isForwardDecl())
1176 addSourceLine(&Buffer, DTy);
1179 /// constructTypeDIE - Construct type DIE from DICompositeType.
1180 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1181 // Add name if not anonymous or intermediate type.
1182 StringRef Name = CTy.getName();
1184 uint64_t Size = CTy.getSizeInBits() >> 3;
1185 uint16_t Tag = Buffer.getTag();
1188 case dwarf::DW_TAG_array_type:
1189 constructArrayTypeDIE(Buffer, CTy);
1191 case dwarf::DW_TAG_enumeration_type:
1192 constructEnumTypeDIE(Buffer, CTy);
1194 case dwarf::DW_TAG_subroutine_type: {
1195 // Add return type. A void return won't have a type.
1196 DIArray Elements = CTy.getTypeArray();
1197 DIType RTy(Elements.getElement(0));
1199 addType(&Buffer, RTy);
1201 bool isPrototyped = true;
1203 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1204 DIDescriptor Ty = Elements.getElement(i);
1205 if (Ty.isUnspecifiedParameter()) {
1206 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1207 isPrototyped = false;
1209 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1210 addType(Arg, DIType(Ty));
1211 if (DIType(Ty).isArtificial())
1212 addFlag(Arg, dwarf::DW_AT_artificial);
1215 // Add prototype flag if we're dealing with a C language and the
1216 // function has been prototyped.
1217 uint16_t Language = getLanguage();
1219 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1220 Language == dwarf::DW_LANG_ObjC))
1221 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1223 if (CTy.isLValueReference())
1224 addFlag(&Buffer, dwarf::DW_AT_reference);
1226 if (CTy.isRValueReference())
1227 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1229 case dwarf::DW_TAG_structure_type:
1230 case dwarf::DW_TAG_union_type:
1231 case dwarf::DW_TAG_class_type: {
1232 // Add elements to structure type.
1233 DIArray Elements = CTy.getTypeArray();
1234 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1235 DIDescriptor Element = Elements.getElement(i);
1236 DIE *ElemDie = NULL;
1237 if (Element.isSubprogram()) {
1238 DISubprogram SP(Element);
1239 ElemDie = getOrCreateSubprogramDIE(SP);
1240 if (SP.isProtected())
1241 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1242 dwarf::DW_ACCESS_protected);
1243 else if (SP.isPrivate())
1244 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1245 dwarf::DW_ACCESS_private);
1247 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1248 dwarf::DW_ACCESS_public);
1249 if (SP.isExplicit())
1250 addFlag(ElemDie, dwarf::DW_AT_explicit);
1251 } else if (Element.isDerivedType()) {
1252 DIDerivedType DDTy(Element);
1253 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1254 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1255 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1256 dwarf::DW_AT_friend);
1257 } else if (DDTy.isStaticMember()) {
1258 getOrCreateStaticMemberDIE(DDTy);
1260 constructMemberDIE(Buffer, DDTy);
1262 } else if (Element.isObjCProperty()) {
1263 DIObjCProperty Property(Element);
1264 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1265 StringRef PropertyName = Property.getObjCPropertyName();
1266 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1267 addType(ElemDie, Property.getType());
1268 addSourceLine(ElemDie, Property);
1269 StringRef GetterName = Property.getObjCPropertyGetterName();
1270 if (!GetterName.empty())
1271 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1272 StringRef SetterName = Property.getObjCPropertySetterName();
1273 if (!SetterName.empty())
1274 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1275 unsigned PropertyAttributes = 0;
1276 if (Property.isReadOnlyObjCProperty())
1277 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1278 if (Property.isReadWriteObjCProperty())
1279 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1280 if (Property.isAssignObjCProperty())
1281 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1282 if (Property.isRetainObjCProperty())
1283 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1284 if (Property.isCopyObjCProperty())
1285 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1286 if (Property.isNonAtomicObjCProperty())
1287 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1288 if (PropertyAttributes)
1289 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1290 PropertyAttributes);
1292 DIEEntry *Entry = getDIEEntry(Element);
1294 Entry = createDIEEntry(ElemDie);
1295 insertDIEEntry(Element, Entry);
1301 if (CTy.isAppleBlockExtension())
1302 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1304 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1306 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1307 getOrCreateTypeDIE(ContainingType));
1309 if (CTy.isObjcClassComplete())
1310 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1312 // Add template parameters to a class, structure or union types.
1313 // FIXME: The support isn't in the metadata for this yet.
1314 if (Tag == dwarf::DW_TAG_class_type ||
1315 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1316 addTemplateParams(Buffer, CTy.getTemplateParams());
1324 // Add name if not anonymous or intermediate type.
1326 addString(&Buffer, dwarf::DW_AT_name, Name);
1328 if (Tag == dwarf::DW_TAG_enumeration_type ||
1329 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1330 Tag == dwarf::DW_TAG_union_type) {
1331 // Add size if non-zero (derived types might be zero-sized.)
1332 // TODO: Do we care about size for enum forward declarations?
1334 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1335 else if (!CTy.isForwardDecl())
1336 // Add zero size if it is not a forward declaration.
1337 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1339 // If we're a forward decl, say so.
1340 if (CTy.isForwardDecl())
1341 addFlag(&Buffer, dwarf::DW_AT_declaration);
1343 // Add source line info if available.
1344 if (!CTy.isForwardDecl())
1345 addSourceLine(&Buffer, CTy);
1347 // No harm in adding the runtime language to the declaration.
1348 unsigned RLang = CTy.getRunTimeLang();
1350 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1355 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1356 /// DITemplateTypeParameter.
1357 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1358 DITemplateTypeParameter TP) {
1360 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1361 // Add the type if it exists, it could be void and therefore no type.
1363 addType(ParamDIE, resolve(TP.getType()));
1364 if (!TP.getName().empty())
1365 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1368 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1369 /// DITemplateValueParameter.
1371 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1372 DITemplateValueParameter VP) {
1373 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1375 // Add the type if there is one, template template and template parameter
1376 // packs will not have a type.
1377 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1378 addType(ParamDIE, resolve(VP.getType()));
1379 if (!VP.getName().empty())
1380 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1381 if (Value *Val = VP.getValue()) {
1382 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1383 addConstantValue(ParamDIE, CI,
1384 isUnsignedDIType(DD, resolve(VP.getType())));
1385 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1386 // For declaration non-type template parameters (such as global values and
1388 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1389 addOpAddress(Block, Asm->getSymbol(GV));
1390 // Emit DW_OP_stack_value to use the address as the immediate value of the
1391 // parameter, rather than a pointer to it.
1392 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1393 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1394 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1395 assert(isa<MDString>(Val));
1396 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1397 cast<MDString>(Val)->getString());
1398 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1399 assert(isa<MDNode>(Val));
1400 DIArray A(cast<MDNode>(Val));
1401 addTemplateParams(*ParamDIE, A);
1406 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1407 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1408 // Construct the context before querying for the existence of the DIE in case
1409 // such construction creates the DIE.
1410 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1412 DIE *NDie = getDIE(NS);
1415 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1417 if (!NS.getName().empty()) {
1418 addString(NDie, dwarf::DW_AT_name, NS.getName());
1419 addAccelNamespace(NS.getName(), NDie);
1420 addGlobalName(NS.getName(), NDie, NS.getContext());
1422 addAccelNamespace("(anonymous namespace)", NDie);
1423 addSourceLine(NDie, NS);
1427 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1428 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1429 // Construct the context before querying for the existence of the DIE in case
1430 // such construction creates the DIE (as is the case for member function
1432 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1434 DIE *SPDie = getDIE(SP);
1438 DISubprogram SPDecl = SP.getFunctionDeclaration();
1439 if (SPDecl.isSubprogram())
1440 // Add subprogram definitions to the CU die directly.
1441 ContextDIE = UnitDie.get();
1443 // DW_TAG_inlined_subroutine may refer to this DIE.
1444 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1446 DIE *DeclDie = NULL;
1447 if (SPDecl.isSubprogram())
1448 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1450 // Add function template parameters.
1451 addTemplateParams(*SPDie, SP.getTemplateParams());
1453 // If this DIE is going to refer declaration info using AT_specification
1454 // then there is no need to add other attributes.
1456 // Refer function declaration directly.
1457 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1462 // Add the linkage name if we have one.
1463 StringRef LinkageName = SP.getLinkageName();
1464 if (!LinkageName.empty())
1465 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1466 GlobalValue::getRealLinkageName(LinkageName));
1468 // Constructors and operators for anonymous aggregates do not have names.
1469 if (!SP.getName().empty())
1470 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1472 addSourceLine(SPDie, SP);
1474 // Add the prototype if we have a prototype and we have a C like
1476 uint16_t Language = getLanguage();
1477 if (SP.isPrototyped() &&
1478 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1479 Language == dwarf::DW_LANG_ObjC))
1480 addFlag(SPDie, dwarf::DW_AT_prototyped);
1482 DICompositeType SPTy = SP.getType();
1483 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1484 "the type of a subprogram should be a subroutine");
1486 DIArray Args = SPTy.getTypeArray();
1487 // Add a return type. If this is a type like a C/C++ void type we don't add a
1489 if (Args.getElement(0))
1490 addType(SPDie, DIType(Args.getElement(0)));
1492 unsigned VK = SP.getVirtuality();
1494 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1495 DIEBlock *Block = getDIEBlock();
1496 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1497 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1498 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1499 ContainingTypeMap.insert(
1500 std::make_pair(SPDie, resolve(SP.getContainingType())));
1503 if (!SP.isDefinition()) {
1504 addFlag(SPDie, dwarf::DW_AT_declaration);
1506 // Add arguments. Do not add arguments for subprogram definition. They will
1507 // be handled while processing variables.
1508 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1509 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1510 DIType ATy(Args.getElement(i));
1512 if (ATy.isArtificial())
1513 addFlag(Arg, dwarf::DW_AT_artificial);
1517 if (SP.isArtificial())
1518 addFlag(SPDie, dwarf::DW_AT_artificial);
1520 if (!SP.isLocalToUnit())
1521 addFlag(SPDie, dwarf::DW_AT_external);
1523 if (SP.isOptimized())
1524 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1526 if (unsigned isa = Asm->getISAEncoding()) {
1527 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1530 if (SP.isLValueReference())
1531 addFlag(SPDie, dwarf::DW_AT_reference);
1533 if (SP.isRValueReference())
1534 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1539 // Return const expression if value is a GEP to access merged global
1541 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1542 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1543 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1544 if (!CE || CE->getNumOperands() != 3 ||
1545 CE->getOpcode() != Instruction::GetElementPtr)
1548 // First operand points to a global struct.
1549 Value *Ptr = CE->getOperand(0);
1550 if (!isa<GlobalValue>(Ptr) ||
1551 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1554 // Second operand is zero.
1555 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1556 if (!CI || !CI->isZero())
1559 // Third operand is offset.
1560 if (!isa<ConstantInt>(CE->getOperand(2)))
1566 /// createGlobalVariableDIE - create global variable DIE.
1567 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1568 // Check for pre-existence.
1572 if (!GV.isGlobalVariable())
1575 DIScope GVContext = GV.getContext();
1576 DIType GTy = GV.getType();
1578 // If this is a static data member definition, some attributes belong
1579 // to the declaration DIE.
1580 DIE *VariableDIE = NULL;
1581 bool IsStaticMember = false;
1582 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1583 if (SDMDecl.Verify()) {
1584 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1585 // We need the declaration DIE that is in the static member's class.
1586 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1587 IsStaticMember = true;
1590 // If this is not a static data member definition, create the variable
1591 // DIE and add the initial set of attributes to it.
1593 // Construct the context before querying for the existence of the DIE in
1594 // case such construction creates the DIE.
1595 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1598 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1600 // Add name and type.
1601 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1602 addType(VariableDIE, GTy);
1604 // Add scoping info.
1605 if (!GV.isLocalToUnit())
1606 addFlag(VariableDIE, dwarf::DW_AT_external);
1608 // Add line number info.
1609 addSourceLine(VariableDIE, GV);
1613 bool addToAccelTable = false;
1614 DIE *VariableSpecDIE = NULL;
1615 bool isGlobalVariable = GV.getGlobal() != NULL;
1616 if (isGlobalVariable) {
1617 addToAccelTable = true;
1618 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1619 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1620 if (GV.getGlobal()->isThreadLocal()) {
1621 // FIXME: Make this work with -gsplit-dwarf.
1622 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1623 assert((PointerSize == 4 || PointerSize == 8) &&
1624 "Add support for other sizes if necessary");
1625 const MCExpr *Expr =
1626 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1627 // Based on GCC's support for TLS:
1628 if (!DD->useSplitDwarf()) {
1629 // 1) Start with a constNu of the appropriate pointer size
1630 addUInt(Block, dwarf::DW_FORM_data1,
1631 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1632 // 2) containing the (relocated) offset of the TLS variable
1633 // within the module's TLS block.
1634 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1636 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1637 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1639 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1640 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1642 DD->addArangeLabel(SymbolCU(this, Sym));
1643 addOpAddress(Block, Sym);
1645 // Do not create specification DIE if context is either compile unit
1647 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1648 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1649 // Create specification DIE.
1650 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1651 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1652 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1653 // A static member's declaration is already flagged as such.
1654 if (!SDMDecl.Verify())
1655 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1657 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1659 // Add the linkage name.
1660 StringRef LinkageName = GV.getLinkageName();
1661 if (!LinkageName.empty())
1662 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1663 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1665 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1667 dwarf::DW_AT_MIPS_linkage_name,
1668 GlobalValue::getRealLinkageName(LinkageName));
1669 } else if (const ConstantInt *CI =
1670 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1671 // AT_const_value was added when the static member was created. To avoid
1672 // emitting AT_const_value multiple times, we only add AT_const_value when
1673 // it is not a static member.
1674 if (!IsStaticMember)
1675 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1676 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1677 addToAccelTable = true;
1678 // GV is a merged global.
1679 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1680 Value *Ptr = CE->getOperand(0);
1681 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1682 DD->addArangeLabel(SymbolCU(this, Sym));
1683 addOpAddress(Block, Sym);
1684 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1685 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1686 addUInt(Block, dwarf::DW_FORM_udata,
1687 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1688 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1689 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1692 if (addToAccelTable) {
1693 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1694 addAccelName(GV.getName(), AddrDIE);
1696 // If the linkage name is different than the name, go ahead and output
1697 // that as well into the name table.
1698 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1699 addAccelName(GV.getLinkageName(), AddrDIE);
1702 if (!GV.isLocalToUnit())
1703 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1707 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1708 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1709 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1710 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1712 // The LowerBound value defines the lower bounds which is typically zero for
1713 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1714 // Count == -1 then the array is unbounded and we do not emit
1715 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1716 // Count == 0, then the array has zero elements in which case we do not emit
1718 int64_t LowerBound = SR.getLo();
1719 int64_t DefaultLowerBound = getDefaultLowerBound();
1720 int64_t Count = SR.getCount();
1722 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1723 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1725 if (Count != -1 && Count != 0)
1726 // FIXME: An unbounded array should reference the expression that defines
1728 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1729 LowerBound + Count - 1);
1732 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1733 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1735 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1737 // Emit the element type.
1738 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1740 // Get an anonymous type for index type.
1741 // FIXME: This type should be passed down from the front end
1742 // as different languages may have different sizes for indexes.
1743 DIE *IdxTy = getIndexTyDie();
1745 // Construct an anonymous type for index type.
1746 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1747 addString(IdxTy, dwarf::DW_AT_name, "int");
1748 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1749 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1750 dwarf::DW_ATE_signed);
1751 setIndexTyDie(IdxTy);
1754 // Add subranges to array type.
1755 DIArray Elements = CTy.getTypeArray();
1756 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1757 DIDescriptor Element = Elements.getElement(i);
1758 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1759 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1763 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1764 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1765 DIArray Elements = CTy.getTypeArray();
1767 // Add enumerators to enumeration type.
1768 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1769 DIEnumerator Enum(Elements.getElement(i));
1770 if (Enum.isEnumerator()) {
1771 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1772 StringRef Name = Enum.getName();
1773 addString(Enumerator, dwarf::DW_AT_name, Name);
1774 int64_t Value = Enum.getEnumValue();
1775 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1778 // Add the enumerator to the __apple_names accelerator table.
1779 addAccelName(Name, Enumerator);
1782 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1784 addType(&Buffer, DTy);
1785 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1789 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1791 void DwarfUnit::constructContainingTypeDIEs() {
1792 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1793 CE = ContainingTypeMap.end();
1795 DIE *SPDie = CI->first;
1796 DIDescriptor D(CI->second);
1799 DIE *NDie = getDIE(D);
1802 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1806 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1807 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1808 StringRef Name = DV.getName();
1810 // Define variable debug information entry.
1811 DIE *VariableDie = new DIE(DV.getTag());
1812 DbgVariable *AbsVar = DV.getAbstractVariable();
1813 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1815 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1818 addString(VariableDie, dwarf::DW_AT_name, Name);
1819 addSourceLine(VariableDie, DV.getVariable());
1820 addType(VariableDie, DV.getType());
1823 if (DV.isArtificial())
1824 addFlag(VariableDie, dwarf::DW_AT_artificial);
1826 if (isScopeAbstract) {
1827 DV.setDIE(VariableDie);
1831 // Add variable address.
1833 unsigned Offset = DV.getDotDebugLocOffset();
1834 if (Offset != ~0U) {
1835 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1836 Asm->GetTempSymbol("debug_loc", Offset));
1837 DV.setDIE(VariableDie);
1841 // Check if variable is described by a DBG_VALUE instruction.
1842 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1843 assert(DVInsn->getNumOperands() == 3);
1844 if (DVInsn->getOperand(0).isReg()) {
1845 const MachineOperand RegOp = DVInsn->getOperand(0);
1846 // If the second operand is an immediate, this is an indirect value.
1847 if (DVInsn->getOperand(1).isImm()) {
1848 MachineLocation Location(RegOp.getReg(),
1849 DVInsn->getOperand(1).getImm());
1850 addVariableAddress(DV, VariableDie, Location);
1851 } else if (RegOp.getReg())
1852 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1853 } else if (DVInsn->getOperand(0).isImm())
1854 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1855 else if (DVInsn->getOperand(0).isFPImm())
1856 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1857 else if (DVInsn->getOperand(0).isCImm())
1858 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1859 isUnsignedDIType(DD, DV.getType()));
1861 DV.setDIE(VariableDie);
1864 // .. else use frame index.
1865 int FI = DV.getFrameIndex();
1867 unsigned FrameReg = 0;
1868 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1869 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1870 MachineLocation Location(FrameReg, Offset);
1871 addVariableAddress(DV, VariableDie, Location);
1875 DV.setDIE(VariableDie);
1879 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1880 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1881 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1882 StringRef Name = DT.getName();
1884 addString(MemberDie, dwarf::DW_AT_name, Name);
1886 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1888 addSourceLine(MemberDie, DT);
1890 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1891 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1893 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1895 // For C++, virtual base classes are not at fixed offset. Use following
1896 // expression to extract appropriate offset from vtable.
1897 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1899 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1900 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1901 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1902 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1903 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1904 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1905 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1906 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1908 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1910 uint64_t Size = DT.getSizeInBits();
1911 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1912 uint64_t OffsetInBytes;
1914 if (Size != FieldSize) {
1916 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1917 getBaseTypeSize(DD, DT) >> 3);
1918 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1920 uint64_t Offset = DT.getOffsetInBits();
1921 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1922 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1923 uint64_t FieldOffset = (HiMark - FieldSize);
1924 Offset -= FieldOffset;
1926 // Maybe we need to work from the other end.
1927 if (Asm->getDataLayout().isLittleEndian())
1928 Offset = FieldSize - (Offset + Size);
1929 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1931 // Here WD_AT_data_member_location points to the anonymous
1932 // field that includes this bit field.
1933 OffsetInBytes = FieldOffset >> 3;
1935 // This is not a bitfield.
1936 OffsetInBytes = DT.getOffsetInBits() >> 3;
1937 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None, OffsetInBytes);
1940 if (DT.isProtected())
1941 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1942 dwarf::DW_ACCESS_protected);
1943 else if (DT.isPrivate())
1944 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1945 dwarf::DW_ACCESS_private);
1946 // Otherwise C++ member and base classes are considered public.
1948 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1949 dwarf::DW_ACCESS_public);
1951 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1952 dwarf::DW_VIRTUALITY_virtual);
1954 // Objective-C properties.
1955 if (MDNode *PNode = DT.getObjCProperty())
1956 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1957 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1960 if (DT.isArtificial())
1961 addFlag(MemberDie, dwarf::DW_AT_artificial);
1964 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1965 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1969 // Construct the context before querying for the existence of the DIE in case
1970 // such construction creates the DIE.
1971 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1972 assert(dwarf::isType(ContextDIE->getTag()) &&
1973 "Static member should belong to a type.");
1975 DIE *StaticMemberDIE = getDIE(DT);
1976 if (StaticMemberDIE)
1977 return StaticMemberDIE;
1979 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1981 DIType Ty = resolve(DT.getTypeDerivedFrom());
1983 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1984 addType(StaticMemberDIE, Ty);
1985 addSourceLine(StaticMemberDIE, DT);
1986 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1987 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1989 // FIXME: We could omit private if the parent is a class_type, and
1990 // public if the parent is something else.
1991 if (DT.isProtected())
1992 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1993 dwarf::DW_ACCESS_protected);
1994 else if (DT.isPrivate())
1995 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1996 dwarf::DW_ACCESS_private);
1998 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1999 dwarf::DW_ACCESS_public);
2001 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2002 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
2003 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2004 addConstantFPValue(StaticMemberDIE, CFP);
2006 return StaticMemberDIE;
2009 void DwarfUnit::emitHeader(const MCSection *ASection,
2010 const MCSymbol *ASectionSym) const {
2011 Asm->OutStreamer.AddComment("DWARF version number");
2012 Asm->EmitInt16(DD->getDwarfVersion());
2013 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2014 // We share one abbreviations table across all units so it's always at the
2015 // start of the section. Use a relocatable offset where needed to ensure
2016 // linking doesn't invalidate that offset.
2017 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2018 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2019 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2022 DwarfCompileUnit::~DwarfCompileUnit() {}
2023 DwarfTypeUnit::~DwarfTypeUnit() {}
2025 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
2026 const MCSymbol *ASectionSym) const {
2027 DwarfUnit::emitHeader(ASection, ASectionSym);
2028 Asm->OutStreamer.AddComment("Type Signature");
2029 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2030 Asm->OutStreamer.AddComment("Type DIE Offset");
2031 Asm->OutStreamer.EmitIntValue(Ty->getOffset(), sizeof(Ty->getOffset()));
2034 void DwarfTypeUnit::initSection(const MCSection *Section) {
2035 assert(!this->Section);
2036 this->Section = Section;
2037 // Since each type unit is contained in its own COMDAT section, the begin
2038 // label and the section label are the same. Using the begin label emission in
2039 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2040 // the only other alternative of lazily constructing start-of-section labels
2041 // and storing a mapping in DwarfDebug (or AsmPrinter).
2042 this->SectionSym = this->LabelBegin =
2043 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2045 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2046 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());