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/IR/Mangler.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Target/TargetFrameLowering.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
39 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
40 cl::desc("Generate DWARF4 type units."),
43 /// Unit - Unit constructor.
44 DwarfUnit::DwarfUnit(unsigned UID, DIE *D, DICompileUnit Node, AsmPrinter *A,
45 DwarfDebug *DW, DwarfFile *DWU)
46 : UniqueID(UID), CUNode(Node), UnitDie(D), DebugInfoOffset(0), Asm(A),
47 DD(DW), DU(DWU), IndexTyDie(0), Section(0), Skeleton(0) {
48 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
51 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
52 AsmPrinter *A, DwarfDebug *DW,
54 : DwarfUnit(UID, D, Node, A, DW, DWU) {
58 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DIE *D, DICompileUnit CUNode,
59 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
60 : DwarfUnit(UID, D, CUNode, A, DW, DWU) {}
62 /// ~Unit - Destructor for compile unit.
63 DwarfUnit::~DwarfUnit() {
64 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
65 DIEBlocks[j]->~DIEBlock();
68 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
69 /// information entry.
70 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) {
71 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
75 /// getDefaultLowerBound - Return the default lower bound for an array. If the
76 /// DWARF version doesn't handle the language, return -1.
77 int64_t DwarfUnit::getDefaultLowerBound() const {
78 switch (getLanguage()) {
82 case dwarf::DW_LANG_C89:
83 case dwarf::DW_LANG_C99:
84 case dwarf::DW_LANG_C:
85 case dwarf::DW_LANG_C_plus_plus:
86 case dwarf::DW_LANG_ObjC:
87 case dwarf::DW_LANG_ObjC_plus_plus:
90 case dwarf::DW_LANG_Fortran77:
91 case dwarf::DW_LANG_Fortran90:
92 case dwarf::DW_LANG_Fortran95:
95 // The languages below have valid values only if the DWARF version >= 4.
96 case dwarf::DW_LANG_Java:
97 case dwarf::DW_LANG_Python:
98 case dwarf::DW_LANG_UPC:
99 case dwarf::DW_LANG_D:
100 if (dwarf::DWARF_VERSION >= 4)
104 case dwarf::DW_LANG_Ada83:
105 case dwarf::DW_LANG_Ada95:
106 case dwarf::DW_LANG_Cobol74:
107 case dwarf::DW_LANG_Cobol85:
108 case dwarf::DW_LANG_Modula2:
109 case dwarf::DW_LANG_Pascal83:
110 case dwarf::DW_LANG_PLI:
111 if (dwarf::DWARF_VERSION >= 4)
119 /// Check whether the DIE for this MDNode can be shared across CUs.
120 static bool isShareableAcrossCUs(DIDescriptor D) {
121 // When the MDNode can be part of the type system, the DIE can be shared
123 // Combining type units and cross-CU DIE sharing is lower value (since
124 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
125 // level already) but may be implementable for some value in projects
126 // building multiple independent libraries with LTO and then linking those
128 return (D.isType() ||
129 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
130 !GenerateDwarfTypeUnits;
133 /// getDIE - Returns the debug information entry map slot for the
134 /// specified debug variable. We delegate the request to DwarfDebug
135 /// when the DIE for this MDNode can be shared across CUs. The mappings
136 /// will be kept in DwarfDebug for shareable DIEs.
137 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
138 if (isShareableAcrossCUs(D))
139 return DD->getDIE(D);
140 return MDNodeToDieMap.lookup(D);
143 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
144 /// when the DIE for this MDNode can be shared across CUs. The mappings
145 /// will be kept in DwarfDebug for shareable DIEs.
146 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
147 if (isShareableAcrossCUs(Desc)) {
148 DD->insertDIE(Desc, D);
151 MDNodeToDieMap.insert(std::make_pair(Desc, D));
154 /// addFlag - Add a flag that is true.
155 void DwarfUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
156 if (DD->getDwarfVersion() >= 4)
157 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
159 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
162 /// addUInt - Add an unsigned integer attribute data and value.
164 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
165 Optional<dwarf::Form> Form, uint64_t Integer) {
167 Form = DIEInteger::BestForm(false, Integer);
168 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
170 Die->addValue(Attribute, *Form, Value);
173 void DwarfUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
174 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
177 /// addSInt - Add an signed integer attribute data and value.
179 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
180 Optional<dwarf::Form> Form, int64_t Integer) {
182 Form = DIEInteger::BestForm(true, Integer);
183 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
184 Die->addValue(Attribute, *Form, Value);
187 void DwarfUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form,
189 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
192 /// addString - Add a string attribute data and value. We always emit a
193 /// reference to the string pool instead of immediate strings so that DIEs have
194 /// more predictable sizes. In the case of split dwarf we emit an index
195 /// into another table which gets us the static offset into the string
197 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute,
200 if (!DD->useSplitDwarf())
201 return addLocalString(Die, Attribute, String);
203 unsigned idx = DU->getStringPoolIndex(String);
204 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
205 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
206 Die->addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
209 /// addLocalString - Add a string attribute data and value. This is guaranteed
210 /// to be in the local string pool instead of indirected.
211 void DwarfUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
213 MCSymbol *Symb = DU->getStringPoolEntry(String);
215 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
216 Value = new (DIEValueAllocator) DIELabel(Symb);
218 MCSymbol *StringPool = DU->getStringPoolSym();
219 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
221 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
222 Die->addValue(Attribute, dwarf::DW_FORM_strp, Str);
225 /// addExpr - Add a Dwarf expression attribute data and value.
227 void DwarfUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
228 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
229 Die->addValue((dwarf::Attribute)0, Form, Value);
232 /// addLabel - Add a Dwarf label attribute data and value.
234 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
235 const MCSymbol *Label) {
236 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
237 Die->addValue(Attribute, Form, Value);
240 void DwarfUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
241 const MCSymbol *Label) {
242 addLabel(Die, (dwarf::Attribute)0, Form, Label);
245 /// addSectionLabel - Add a Dwarf section label attribute data and value.
247 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
248 const MCSymbol *Label) {
249 if (DD->getDwarfVersion() >= 4)
250 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
252 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
255 /// addSectionOffset - Add an offset into a section attribute data and value.
257 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
259 if (DD->getDwarfVersion() >= 4)
260 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
262 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
265 /// addLabelAddress - Add a dwarf label attribute data and value using
266 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
268 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
271 DD->addArangeLabel(SymbolCU(this, Label));
273 if (!DD->useSplitDwarf()) {
275 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
276 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
278 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
279 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
282 unsigned idx = DU->getAddrPoolIndex(Label);
283 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
284 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
288 /// addOpAddress - Add a dwarf op address data and value using the
289 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
291 void DwarfUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
292 if (!DD->useSplitDwarf()) {
293 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
294 addLabel(Die, dwarf::DW_FORM_udata, Sym);
296 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
297 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
301 /// addSectionDelta - Add a section label delta attribute data and value.
303 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
304 const MCSymbol *Hi, const MCSymbol *Lo) {
305 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
306 if (DD->getDwarfVersion() >= 4)
307 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
309 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
312 /// addDIEEntry - Add a DIE attribute data and value.
314 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
315 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
318 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
319 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
320 new (DIEValueAllocator) DIETypeSignature(Type));
323 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
325 const DIE *DieCU = Die->getUnitOrNull();
326 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
328 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
329 DieCU = getUnitDie();
331 EntryCU = getUnitDie();
332 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
333 : dwarf::DW_FORM_ref_addr,
337 /// Create a DIE with the given Tag, add the DIE to its parent, and
338 /// call insertDIE if MD is not null.
339 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
340 DIE *Die = new DIE(Tag);
341 Parent.addChild(Die);
347 /// addBlock - Add block data.
349 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
351 Block->ComputeSize(Asm);
352 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
353 Die->addValue(Attribute, Block->BestForm(), Block);
356 /// addSourceLine - Add location information to specified debug information
358 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
363 unsigned Line = V.getLineNumber();
367 DD->getOrCreateSourceID(V.getContext().getFilename(),
368 V.getContext().getDirectory(), getUniqueID());
369 assert(FileID && "Invalid file id");
370 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
371 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
374 /// addSourceLine - Add location information to specified debug information
376 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
377 // Verify global variable.
378 if (!G.isGlobalVariable())
381 unsigned Line = G.getLineNumber();
385 DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(), getUniqueID());
386 assert(FileID && "Invalid file id");
387 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
388 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
391 /// addSourceLine - Add location information to specified debug information
393 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
394 // Verify subprogram.
395 if (!SP.isSubprogram())
398 // If the line number is 0, don't add it.
399 unsigned Line = SP.getLineNumber();
403 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
405 assert(FileID && "Invalid file id");
406 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
407 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
410 /// addSourceLine - Add location information to specified debug information
412 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
417 unsigned Line = Ty.getLineNumber();
420 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.getDirectory(),
422 assert(FileID && "Invalid file id");
423 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
424 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
427 /// addSourceLine - Add location information to specified debug information
429 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
431 if (!Ty.isObjCProperty())
434 unsigned Line = Ty.getLineNumber();
437 DIFile File = Ty.getFile();
438 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
439 File.getDirectory(), getUniqueID());
440 assert(FileID && "Invalid file id");
441 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
442 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
445 /// addSourceLine - Add location information to specified debug information
447 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
452 unsigned Line = NS.getLineNumber();
455 StringRef FN = NS.getFilename();
458 DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
459 assert(FileID && "Invalid file id");
460 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
461 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
464 /// addVariableAddress - Add DW_AT_location attribute for a
465 /// DbgVariable based on provided MachineLocation.
466 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
467 MachineLocation Location) {
468 if (DV.variableHasComplexAddress())
469 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
470 else if (DV.isBlockByrefVariable())
471 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
473 addAddress(Die, dwarf::DW_AT_location, Location,
474 DV.getVariable().isIndirect());
477 /// addRegisterOp - Add register operand.
478 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
479 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
480 int DWReg = RI->getDwarfRegNum(Reg, false);
481 bool isSubRegister = DWReg < 0;
485 // Go up the super-register chain until we hit a valid dwarf register number.
486 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
487 DWReg = RI->getDwarfRegNum(*SR, false);
489 Idx = RI->getSubRegIndex(*SR, Reg);
493 DEBUG(llvm::dbgs() << "Invalid Dwarf register number.\n");
494 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
500 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
502 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
503 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
508 unsigned Size = RI->getSubRegIdxSize(Idx);
509 unsigned Offset = RI->getSubRegIdxOffset(Idx);
511 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
512 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
513 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
515 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
516 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
521 /// addRegisterOffset - Add register offset.
522 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
524 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
525 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
526 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
527 if (Reg == TRI->getFrameRegister(*Asm->MF))
528 // If variable offset is based in frame register then use fbreg.
529 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
531 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
533 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
534 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
536 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
539 /// addAddress - Add an address attribute to a die based on the location
541 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
542 const MachineLocation &Location, bool Indirect) {
543 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
545 if (Location.isReg() && !Indirect)
546 addRegisterOp(Block, Location.getReg());
548 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
549 if (Indirect && !Location.isReg()) {
550 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
554 // Now attach the location information to the DIE.
555 addBlock(Die, Attribute, Block);
558 /// addComplexAddress - Start with the address based on the location provided,
559 /// and generate the DWARF information necessary to find the actual variable
560 /// given the extra address information encoded in the DbgVariable, starting
561 /// from the starting location. Add the DWARF information to the die.
563 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
564 dwarf::Attribute Attribute,
565 const MachineLocation &Location) {
566 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
567 unsigned N = DV.getNumAddrElements();
569 if (Location.isReg()) {
570 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
571 // If first address element is OpPlus then emit
572 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
573 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
576 addRegisterOp(Block, Location.getReg());
578 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
581 uint64_t Element = DV.getAddrElement(i);
582 if (Element == DIBuilder::OpPlus) {
583 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
584 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
585 } else if (Element == DIBuilder::OpDeref) {
586 if (!Location.isReg())
587 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
589 llvm_unreachable("unknown DIBuilder Opcode");
592 // Now attach the location information to the DIE.
593 addBlock(Die, Attribute, Block);
596 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
597 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
598 gives the variable VarName either the struct, or a pointer to the struct, as
599 its type. This is necessary for various behind-the-scenes things the
600 compiler needs to do with by-reference variables in Blocks.
602 However, as far as the original *programmer* is concerned, the variable
603 should still have type 'SomeType', as originally declared.
605 The function getBlockByrefType dives into the __Block_byref_x_VarName
606 struct to find the original type of the variable, which is then assigned to
607 the variable's Debug Information Entry as its real type. So far, so good.
608 However now the debugger will expect the variable VarName to have the type
609 SomeType. So we need the location attribute for the variable to be an
610 expression that explains to the debugger how to navigate through the
611 pointers and struct to find the actual variable of type SomeType.
613 The following function does just that. We start by getting
614 the "normal" location for the variable. This will be the location
615 of either the struct __Block_byref_x_VarName or the pointer to the
616 struct __Block_byref_x_VarName.
618 The struct will look something like:
620 struct __Block_byref_x_VarName {
622 struct __Block_byref_x_VarName *forwarding;
623 ... <various other fields>
625 ... <maybe more fields>
628 If we are given the struct directly (as our starting point) we
629 need to tell the debugger to:
631 1). Add the offset of the forwarding field.
633 2). Follow that pointer to get the real __Block_byref_x_VarName
634 struct to use (the real one may have been copied onto the heap).
636 3). Add the offset for the field VarName, to find the actual variable.
638 If we started with a pointer to the struct, then we need to
639 dereference that pointer first, before the other steps.
640 Translating this into DWARF ops, we will need to append the following
641 to the current location description for the variable:
643 DW_OP_deref -- optional, if we start with a pointer
644 DW_OP_plus_uconst <forward_fld_offset>
646 DW_OP_plus_uconst <varName_fld_offset>
648 That is what this function does. */
650 /// addBlockByrefAddress - Start with the address based on the location
651 /// provided, and generate the DWARF information necessary to find the
652 /// actual Block variable (navigating the Block struct) based on the
653 /// starting location. Add the DWARF information to the die. For
654 /// more information, read large comment just above here.
656 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
657 dwarf::Attribute Attribute,
658 const MachineLocation &Location) {
659 DIType Ty = DV.getType();
661 uint16_t Tag = Ty.getTag();
662 bool isPointer = false;
664 StringRef varName = DV.getName();
666 if (Tag == dwarf::DW_TAG_pointer_type) {
667 DIDerivedType DTy(Ty);
668 TmpTy = resolve(DTy.getTypeDerivedFrom());
672 DICompositeType blockStruct(TmpTy);
674 // Find the __forwarding field and the variable field in the __Block_byref
676 DIArray Fields = blockStruct.getTypeArray();
677 DIDerivedType varField;
678 DIDerivedType forwardingField;
680 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
681 DIDerivedType DT(Fields.getElement(i));
682 StringRef fieldName = DT.getName();
683 if (fieldName == "__forwarding")
684 forwardingField = DT;
685 else if (fieldName == varName)
689 // Get the offsets for the forwarding field and the variable field.
690 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
691 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
693 // Decode the original location, and use that as the start of the byref
694 // variable's location.
695 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
697 if (Location.isReg())
698 addRegisterOp(Block, Location.getReg());
700 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
702 // If we started with a pointer to the __Block_byref... struct, then
703 // the first thing we need to do is dereference the pointer (DW_OP_deref).
705 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
707 // Next add the offset for the '__forwarding' field:
708 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
709 // adding the offset if it's 0.
710 if (forwardingFieldOffset > 0) {
711 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
712 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
715 // Now dereference the __forwarding field to get to the real __Block_byref
716 // struct: DW_OP_deref.
717 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
719 // Now that we've got the real __Block_byref... struct, add the offset
720 // for the variable's field to get to the location of the actual variable:
721 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
722 if (varFieldOffset > 0) {
723 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
724 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
727 // Now attach the location information to the DIE.
728 addBlock(Die, Attribute, Block);
731 /// isTypeSigned - Return true if the type is signed.
732 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
733 if (Ty.isDerivedType())
734 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
736 if (Ty.isBasicType())
737 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
738 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
739 *SizeInBits = Ty.getSizeInBits();
745 /// Return true if type encoding is unsigned.
746 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
747 DIDerivedType DTy(Ty);
748 if (DTy.isDerivedType())
749 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
752 if (BTy.isBasicType()) {
753 unsigned Encoding = BTy.getEncoding();
754 if (Encoding == dwarf::DW_ATE_unsigned ||
755 Encoding == dwarf::DW_ATE_unsigned_char ||
756 Encoding == dwarf::DW_ATE_boolean)
762 /// If this type is derived from a base type then return base type size.
763 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
764 unsigned Tag = Ty.getTag();
766 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
767 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
768 Tag != dwarf::DW_TAG_restrict_type)
769 return Ty.getSizeInBits();
771 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
773 // If this type is not derived from any type then take conservative approach.
774 if (!BaseType.isValid())
775 return Ty.getSizeInBits();
777 // If this is a derived type, go ahead and get the base type, unless it's a
778 // reference then it's just the size of the field. Pointer types have no need
779 // of this since they're a different type of qualification on the type.
780 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
781 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
782 return Ty.getSizeInBits();
784 if (BaseType.isDerivedType())
785 return getBaseTypeSize(DD, DIDerivedType(BaseType));
787 return BaseType.getSizeInBits();
790 /// addConstantValue - Add constant value entry in variable DIE.
791 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
793 // FIXME: This is a bit conservative/simple - it emits negative values at
794 // their maximum bit width which is a bit unfortunate (& doesn't prefer
795 // udata/sdata over dataN as suggested by the DWARF spec)
796 assert(MO.isImm() && "Invalid machine operand!");
798 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
801 // If we're a signed constant definitely use sdata.
802 if (SignedConstant) {
803 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
807 // Else use data for now unless it's larger than we can deal with.
808 switch (SizeInBits) {
810 Form = dwarf::DW_FORM_data1;
813 Form = dwarf::DW_FORM_data2;
816 Form = dwarf::DW_FORM_data4;
819 Form = dwarf::DW_FORM_data8;
822 Form = dwarf::DW_FORM_udata;
823 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
826 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
829 /// addConstantFPValue - Add constant value entry in variable DIE.
830 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
831 assert(MO.isFPImm() && "Invalid machine operand!");
832 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
833 APFloat FPImm = MO.getFPImm()->getValueAPF();
835 // Get the raw data form of the floating point.
836 const APInt FltVal = FPImm.bitcastToAPInt();
837 const char *FltPtr = (const char *)FltVal.getRawData();
839 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
840 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
841 int Incr = (LittleEndian ? 1 : -1);
842 int Start = (LittleEndian ? 0 : NumBytes - 1);
843 int Stop = (LittleEndian ? NumBytes : -1);
845 // Output the constant to DWARF one byte at a time.
846 for (; Start != Stop; Start += Incr)
847 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
849 addBlock(Die, dwarf::DW_AT_const_value, Block);
852 /// addConstantFPValue - Add constant value entry in variable DIE.
853 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
854 // Pass this down to addConstantValue as an unsigned bag of bits.
855 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
858 /// addConstantValue - Add constant value entry in variable DIE.
859 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
861 addConstantValue(Die, CI->getValue(), Unsigned);
864 // addConstantValue - Add constant value entry in variable DIE.
865 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
866 unsigned CIBitWidth = Val.getBitWidth();
867 if (CIBitWidth <= 64) {
868 // If we're a signed constant definitely use sdata.
870 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
875 // Else use data for now unless it's larger than we can deal with.
877 switch (CIBitWidth) {
879 Form = dwarf::DW_FORM_data1;
882 Form = dwarf::DW_FORM_data2;
885 Form = dwarf::DW_FORM_data4;
888 Form = dwarf::DW_FORM_data8;
891 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
895 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
899 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
901 // Get the raw data form of the large APInt.
902 const uint64_t *Ptr64 = Val.getRawData();
904 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
905 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
907 // Output the constant to DWARF one byte at a time.
908 for (int i = 0; i < NumBytes; i++) {
911 c = Ptr64[i / 8] >> (8 * (i & 7));
913 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
914 addUInt(Block, dwarf::DW_FORM_data1, c);
917 addBlock(Die, dwarf::DW_AT_const_value, Block);
920 /// addTemplateParams - Add template parameters into buffer.
921 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
922 // Add template parameters.
923 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
924 DIDescriptor Element = TParams.getElement(i);
925 if (Element.isTemplateTypeParameter())
926 constructTemplateTypeParameterDIE(Buffer,
927 DITemplateTypeParameter(Element));
928 else if (Element.isTemplateValueParameter())
929 constructTemplateValueParameterDIE(Buffer,
930 DITemplateValueParameter(Element));
934 /// getOrCreateContextDIE - Get context owner's DIE.
935 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
936 if (!Context || Context.isFile())
938 if (Context.isType())
939 return getOrCreateTypeDIE(DIType(Context));
940 if (Context.isNameSpace())
941 return getOrCreateNameSpace(DINameSpace(Context));
942 if (Context.isSubprogram())
943 return getOrCreateSubprogramDIE(DISubprogram(Context));
944 return getDIE(Context);
947 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
948 DIScope Context = resolve(Ty.getContext());
949 DIE *ContextDIE = getOrCreateContextDIE(Context);
951 DIE *TyDIE = getDIE(Ty);
956 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
958 constructTypeDIE(*TyDIE, Ty);
960 updateAcceleratorTables(Context, Ty, TyDIE);
964 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
966 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
973 // Construct the context before querying for the existence of the DIE in case
974 // such construction creates the DIE.
975 DIScope Context = resolve(Ty.getContext());
976 DIE *ContextDIE = getOrCreateContextDIE(Context);
979 DIE *TyDIE = getDIE(Ty);
984 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
986 if (Ty.isBasicType())
987 constructTypeDIE(*TyDIE, DIBasicType(Ty));
988 else if (Ty.isCompositeType()) {
989 DICompositeType CTy(Ty);
990 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
991 if (MDString *TypeId = CTy.getIdentifier()) {
992 DD->addDwarfTypeUnitType(getCUNode(), TypeId->getString(), TyDIE, CTy);
993 // Skip updating the accellerator tables since this is not the full type
996 constructTypeDIE(*TyDIE, CTy);
998 assert(Ty.isDerivedType() && "Unknown kind of DIType");
999 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
1002 updateAcceleratorTables(Context, Ty, TyDIE);
1007 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1009 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1010 bool IsImplementation = 0;
1011 if (Ty.isCompositeType()) {
1012 DICompositeType CT(Ty);
1013 // A runtime language of 0 actually means C/C++ and that any
1014 // non-negative value is some version of Objective-C/C++.
1015 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1017 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1018 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
1020 if (!Context || Context.isCompileUnit() || Context.isFile() ||
1021 Context.isNameSpace())
1022 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1026 /// addType - Add a new type attribute to the specified entity.
1027 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
1028 assert(Ty && "Trying to add a type that doesn't exist?");
1030 // Check for pre-existence.
1031 DIEEntry *Entry = getDIEEntry(Ty);
1032 // If it exists then use the existing value.
1034 addDIEEntry(Entity, Attribute, Entry);
1039 DIE *Buffer = getOrCreateTypeDIE(Ty);
1042 Entry = createDIEEntry(Buffer);
1043 insertDIEEntry(Ty, Entry);
1044 addDIEEntry(Entity, Attribute, Entry);
1047 // Accelerator table mutators - add each name along with its companion
1048 // DIE to the proper table while ensuring that the name that we're going
1049 // to reference is in the string table. We do this since the names we
1050 // add may not only be identical to the names in the DIE.
1051 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1052 if (!DD->useDwarfAccelTables()) return;
1053 DU->getStringPoolEntry(Name);
1054 std::vector<const DIE *> &DIEs = AccelNames[Name];
1055 DIEs.push_back(Die);
1058 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1059 if (!DD->useDwarfAccelTables()) return;
1060 DU->getStringPoolEntry(Name);
1061 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1062 DIEs.push_back(Die);
1065 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1066 if (!DD->useDwarfAccelTables()) return;
1067 DU->getStringPoolEntry(Name);
1068 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1069 DIEs.push_back(Die);
1072 void DwarfUnit::addAccelType(StringRef Name,
1073 std::pair<const DIE *, unsigned> Die) {
1074 if (!DD->useDwarfAccelTables()) return;
1075 DU->getStringPoolEntry(Name);
1076 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1077 DIEs.push_back(Die);
1080 /// addGlobalName - Add a new global name to the compile unit.
1081 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1082 std::string FullName = getParentContextString(Context) + Name.str();
1083 GlobalNames[FullName] = Die;
1086 /// getParentContextString - Walks the metadata parent chain in a language
1087 /// specific manner (using the compile unit language) and returns
1088 /// it as a string. This is done at the metadata level because DIEs may
1089 /// not currently have been added to the parent context and walking the
1090 /// DIEs looking for names is more expensive than walking the metadata.
1091 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1095 // FIXME: Decide whether to implement this for non-C++ languages.
1096 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1100 SmallVector<DIScope, 1> Parents;
1101 while (!Context.isCompileUnit()) {
1102 Parents.push_back(Context);
1103 if (Context.getContext())
1104 Context = resolve(Context.getContext());
1106 // Structure, etc types will have a NULL context if they're at the top
1111 // Reverse iterate over our list to go from the outermost construct to the
1113 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1117 StringRef Name = Ctx.getName();
1118 if (!Name.empty()) {
1126 /// constructTypeDIE - Construct basic type die from DIBasicType.
1127 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1128 // Get core information.
1129 StringRef Name = BTy.getName();
1130 // Add name if not anonymous or intermediate type.
1132 addString(&Buffer, dwarf::DW_AT_name, Name);
1134 // An unspecified type only has a name attribute.
1135 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1138 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1141 uint64_t Size = BTy.getSizeInBits() >> 3;
1142 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1145 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1146 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1147 // Get core information.
1148 StringRef Name = DTy.getName();
1149 uint64_t Size = DTy.getSizeInBits() >> 3;
1150 uint16_t Tag = Buffer.getTag();
1152 // Map to main type, void will not have a type.
1153 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1155 addType(&Buffer, FromTy);
1157 // Add name if not anonymous or intermediate type.
1159 addString(&Buffer, dwarf::DW_AT_name, Name);
1161 // Add size if non-zero (derived types might be zero-sized.)
1162 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1163 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1165 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1166 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1167 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1168 // Add source line info if available and TyDesc is not a forward declaration.
1169 if (!DTy.isForwardDecl())
1170 addSourceLine(&Buffer, DTy);
1173 /// constructTypeDIE - Construct type DIE from DICompositeType.
1174 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1175 // Add name if not anonymous or intermediate type.
1176 StringRef Name = CTy.getName();
1178 uint64_t Size = CTy.getSizeInBits() >> 3;
1179 uint16_t Tag = Buffer.getTag();
1182 case dwarf::DW_TAG_array_type:
1183 constructArrayTypeDIE(Buffer, CTy);
1185 case dwarf::DW_TAG_enumeration_type:
1186 constructEnumTypeDIE(Buffer, CTy);
1188 case dwarf::DW_TAG_subroutine_type: {
1189 // Add return type. A void return won't have a type.
1190 DIArray Elements = CTy.getTypeArray();
1191 DIType RTy(Elements.getElement(0));
1193 addType(&Buffer, RTy);
1195 bool isPrototyped = true;
1197 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1198 DIDescriptor Ty = Elements.getElement(i);
1199 if (Ty.isUnspecifiedParameter()) {
1200 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1201 isPrototyped = false;
1203 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1204 addType(Arg, DIType(Ty));
1205 if (DIType(Ty).isArtificial())
1206 addFlag(Arg, dwarf::DW_AT_artificial);
1209 // Add prototype flag if we're dealing with a C language and the
1210 // function has been prototyped.
1211 uint16_t Language = getLanguage();
1213 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1214 Language == dwarf::DW_LANG_ObjC))
1215 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1217 if (CTy.isLValueReference())
1218 addFlag(&Buffer, dwarf::DW_AT_reference);
1220 if (CTy.isRValueReference())
1221 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1223 case dwarf::DW_TAG_structure_type:
1224 case dwarf::DW_TAG_union_type:
1225 case dwarf::DW_TAG_class_type: {
1226 // Add elements to structure type.
1227 DIArray Elements = CTy.getTypeArray();
1228 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1229 DIDescriptor Element = Elements.getElement(i);
1230 DIE *ElemDie = NULL;
1231 if (Element.isSubprogram())
1232 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1233 else if (Element.isDerivedType()) {
1234 DIDerivedType DDTy(Element);
1235 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1236 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1237 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1238 dwarf::DW_AT_friend);
1239 } else if (DDTy.isStaticMember()) {
1240 getOrCreateStaticMemberDIE(DDTy);
1242 constructMemberDIE(Buffer, DDTy);
1244 } else if (Element.isObjCProperty()) {
1245 DIObjCProperty Property(Element);
1246 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1247 StringRef PropertyName = Property.getObjCPropertyName();
1248 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1249 if (Property.getType())
1250 addType(ElemDie, Property.getType());
1251 addSourceLine(ElemDie, Property);
1252 StringRef GetterName = Property.getObjCPropertyGetterName();
1253 if (!GetterName.empty())
1254 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1255 StringRef SetterName = Property.getObjCPropertySetterName();
1256 if (!SetterName.empty())
1257 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1258 unsigned PropertyAttributes = 0;
1259 if (Property.isReadOnlyObjCProperty())
1260 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1261 if (Property.isReadWriteObjCProperty())
1262 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1263 if (Property.isAssignObjCProperty())
1264 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1265 if (Property.isRetainObjCProperty())
1266 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1267 if (Property.isCopyObjCProperty())
1268 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1269 if (Property.isNonAtomicObjCProperty())
1270 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1271 if (PropertyAttributes)
1272 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1273 PropertyAttributes);
1275 DIEEntry *Entry = getDIEEntry(Element);
1277 Entry = createDIEEntry(ElemDie);
1278 insertDIEEntry(Element, Entry);
1284 if (CTy.isAppleBlockExtension())
1285 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1287 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1289 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1290 getOrCreateTypeDIE(ContainingType));
1292 if (CTy.isObjcClassComplete())
1293 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1295 // Add template parameters to a class, structure or union types.
1296 // FIXME: The support isn't in the metadata for this yet.
1297 if (Tag == dwarf::DW_TAG_class_type ||
1298 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1299 addTemplateParams(Buffer, CTy.getTemplateParams());
1307 // Add name if not anonymous or intermediate type.
1309 addString(&Buffer, dwarf::DW_AT_name, Name);
1311 if (Tag == dwarf::DW_TAG_enumeration_type ||
1312 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1313 Tag == dwarf::DW_TAG_union_type) {
1314 // Add size if non-zero (derived types might be zero-sized.)
1315 // TODO: Do we care about size for enum forward declarations?
1317 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1318 else if (!CTy.isForwardDecl())
1319 // Add zero size if it is not a forward declaration.
1320 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1322 // If we're a forward decl, say so.
1323 if (CTy.isForwardDecl())
1324 addFlag(&Buffer, dwarf::DW_AT_declaration);
1326 // Add source line info if available.
1327 if (!CTy.isForwardDecl())
1328 addSourceLine(&Buffer, CTy);
1330 // No harm in adding the runtime language to the declaration.
1331 unsigned RLang = CTy.getRunTimeLang();
1333 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1338 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1339 /// DITemplateTypeParameter.
1340 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1341 DITemplateTypeParameter TP) {
1343 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1344 // Add the type if it exists, it could be void and therefore no type.
1346 addType(ParamDIE, resolve(TP.getType()));
1347 if (!TP.getName().empty())
1348 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1351 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1352 /// DITemplateValueParameter.
1354 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1355 DITemplateValueParameter VP) {
1356 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1358 // Add the type if there is one, template template and template parameter
1359 // packs will not have a type.
1360 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1361 addType(ParamDIE, resolve(VP.getType()));
1362 if (!VP.getName().empty())
1363 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1364 if (Value *Val = VP.getValue()) {
1365 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1366 addConstantValue(ParamDIE, CI,
1367 isUnsignedDIType(DD, resolve(VP.getType())));
1368 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1369 // For declaration non-type template parameters (such as global values and
1371 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1372 addOpAddress(Block, Asm->getSymbol(GV));
1373 // Emit DW_OP_stack_value to use the address as the immediate value of the
1374 // parameter, rather than a pointer to it.
1375 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1376 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1377 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1378 assert(isa<MDString>(Val));
1379 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1380 cast<MDString>(Val)->getString());
1381 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1382 assert(isa<MDNode>(Val));
1383 DIArray A(cast<MDNode>(Val));
1384 addTemplateParams(*ParamDIE, A);
1389 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1390 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1391 // Construct the context before querying for the existence of the DIE in case
1392 // such construction creates the DIE.
1393 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1395 DIE *NDie = getDIE(NS);
1398 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1400 if (!NS.getName().empty()) {
1401 addString(NDie, dwarf::DW_AT_name, NS.getName());
1402 addAccelNamespace(NS.getName(), NDie);
1403 addGlobalName(NS.getName(), NDie, NS.getContext());
1405 addAccelNamespace("(anonymous namespace)", NDie);
1406 addSourceLine(NDie, NS);
1410 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1411 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1412 // Construct the context before querying for the existence of the DIE in case
1413 // such construction creates the DIE (as is the case for member function
1415 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1417 DIE *SPDie = getDIE(SP);
1421 DISubprogram SPDecl = SP.getFunctionDeclaration();
1422 if (SPDecl.isSubprogram())
1423 // Add subprogram definitions to the CU die directly.
1424 ContextDIE = UnitDie.get();
1426 // DW_TAG_inlined_subroutine may refer to this DIE.
1427 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1429 DIE *DeclDie = NULL;
1430 if (SPDecl.isSubprogram())
1431 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1433 // Add function template parameters.
1434 addTemplateParams(*SPDie, SP.getTemplateParams());
1436 // If this DIE is going to refer declaration info using AT_specification
1437 // then there is no need to add other attributes.
1439 // Refer function declaration directly.
1440 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1445 // Add the linkage name if we have one.
1446 StringRef LinkageName = SP.getLinkageName();
1447 if (!LinkageName.empty())
1448 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1449 GlobalValue::getRealLinkageName(LinkageName));
1451 // Constructors and operators for anonymous aggregates do not have names.
1452 if (!SP.getName().empty())
1453 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1455 addSourceLine(SPDie, SP);
1457 // Add the prototype if we have a prototype and we have a C like
1459 uint16_t Language = getLanguage();
1460 if (SP.isPrototyped() &&
1461 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1462 Language == dwarf::DW_LANG_ObjC))
1463 addFlag(SPDie, dwarf::DW_AT_prototyped);
1465 DICompositeType SPTy = SP.getType();
1466 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1467 "the type of a subprogram should be a subroutine");
1469 DIArray Args = SPTy.getTypeArray();
1470 // Add a return type. If this is a type like a C/C++ void type we don't add a
1472 if (Args.getElement(0))
1473 addType(SPDie, DIType(Args.getElement(0)));
1475 unsigned VK = SP.getVirtuality();
1477 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1478 DIEBlock *Block = getDIEBlock();
1479 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1480 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1481 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1482 ContainingTypeMap.insert(
1483 std::make_pair(SPDie, resolve(SP.getContainingType())));
1486 if (!SP.isDefinition()) {
1487 addFlag(SPDie, dwarf::DW_AT_declaration);
1489 // Add arguments. Do not add arguments for subprogram definition. They will
1490 // be handled while processing variables.
1491 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1492 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1493 DIType ATy(Args.getElement(i));
1495 if (ATy.isArtificial())
1496 addFlag(Arg, dwarf::DW_AT_artificial);
1500 if (SP.isArtificial())
1501 addFlag(SPDie, dwarf::DW_AT_artificial);
1503 if (!SP.isLocalToUnit())
1504 addFlag(SPDie, dwarf::DW_AT_external);
1506 if (SP.isOptimized())
1507 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1509 if (unsigned isa = Asm->getISAEncoding()) {
1510 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1513 if (SP.isLValueReference())
1514 addFlag(SPDie, dwarf::DW_AT_reference);
1516 if (SP.isRValueReference())
1517 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1519 if (SP.isProtected())
1520 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1521 dwarf::DW_ACCESS_protected);
1522 else if (SP.isPrivate())
1523 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1524 dwarf::DW_ACCESS_private);
1526 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1527 dwarf::DW_ACCESS_public);
1529 if (SP.isExplicit())
1530 addFlag(SPDie, dwarf::DW_AT_explicit);
1535 // Return const expression if value is a GEP to access merged global
1537 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1538 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1539 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1540 if (!CE || CE->getNumOperands() != 3 ||
1541 CE->getOpcode() != Instruction::GetElementPtr)
1544 // First operand points to a global struct.
1545 Value *Ptr = CE->getOperand(0);
1546 if (!isa<GlobalValue>(Ptr) ||
1547 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1550 // Second operand is zero.
1551 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1552 if (!CI || !CI->isZero())
1555 // Third operand is offset.
1556 if (!isa<ConstantInt>(CE->getOperand(2)))
1562 /// createGlobalVariableDIE - create global variable DIE.
1563 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1564 // Check for pre-existence.
1568 assert(GV.isGlobalVariable());
1570 DIScope GVContext = GV.getContext();
1571 DIType GTy = GV.getType();
1573 // If this is a static data member definition, some attributes belong
1574 // to the declaration DIE.
1575 DIE *VariableDIE = NULL;
1576 bool IsStaticMember = false;
1577 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1578 if (SDMDecl.Verify()) {
1579 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1580 // We need the declaration DIE that is in the static member's class.
1581 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1582 IsStaticMember = true;
1585 // If this is not a static data member definition, create the variable
1586 // DIE and add the initial set of attributes to it.
1588 // Construct the context before querying for the existence of the DIE in
1589 // case such construction creates the DIE.
1590 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1593 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1595 // Add name and type.
1596 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1597 addType(VariableDIE, GTy);
1599 // Add scoping info.
1600 if (!GV.isLocalToUnit())
1601 addFlag(VariableDIE, dwarf::DW_AT_external);
1603 // Add line number info.
1604 addSourceLine(VariableDIE, GV);
1608 bool addToAccelTable = false;
1609 DIE *VariableSpecDIE = NULL;
1610 bool isGlobalVariable = GV.getGlobal() != NULL;
1611 if (isGlobalVariable) {
1612 addToAccelTable = true;
1613 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1614 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1615 if (GV.getGlobal()->isThreadLocal()) {
1616 // FIXME: Make this work with -gsplit-dwarf.
1617 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1618 assert((PointerSize == 4 || PointerSize == 8) &&
1619 "Add support for other sizes if necessary");
1620 const MCExpr *Expr =
1621 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1622 // Based on GCC's support for TLS:
1623 if (!DD->useSplitDwarf()) {
1624 // 1) Start with a constNu of the appropriate pointer size
1625 addUInt(Block, dwarf::DW_FORM_data1,
1626 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1627 // 2) containing the (relocated) offset of the TLS variable
1628 // within the module's TLS block.
1629 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1631 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1632 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1634 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1635 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1637 DD->addArangeLabel(SymbolCU(this, Sym));
1638 addOpAddress(Block, Sym);
1640 // Do not create specification DIE if context is either compile unit
1642 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1643 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1644 // Create specification DIE.
1645 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1646 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1647 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1648 // A static member's declaration is already flagged as such.
1649 if (!SDMDecl.Verify())
1650 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1652 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1654 // Add the linkage name.
1655 StringRef LinkageName = GV.getLinkageName();
1656 if (!LinkageName.empty())
1657 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1658 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1660 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1662 dwarf::DW_AT_MIPS_linkage_name,
1663 GlobalValue::getRealLinkageName(LinkageName));
1664 } else if (const ConstantInt *CI =
1665 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1666 // AT_const_value was added when the static member was created. To avoid
1667 // emitting AT_const_value multiple times, we only add AT_const_value when
1668 // it is not a static member.
1669 if (!IsStaticMember)
1670 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1671 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1672 addToAccelTable = true;
1673 // GV is a merged global.
1674 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1675 Value *Ptr = CE->getOperand(0);
1676 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1677 DD->addArangeLabel(SymbolCU(this, Sym));
1678 addOpAddress(Block, Sym);
1679 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1680 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1681 addUInt(Block, dwarf::DW_FORM_udata,
1682 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1683 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1684 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1687 if (addToAccelTable) {
1688 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1689 addAccelName(GV.getName(), AddrDIE);
1691 // If the linkage name is different than the name, go ahead and output
1692 // that as well into the name table.
1693 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1694 addAccelName(GV.getLinkageName(), AddrDIE);
1697 if (!GV.isLocalToUnit())
1698 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1702 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1703 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1704 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1705 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1707 // The LowerBound value defines the lower bounds which is typically zero for
1708 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1709 // Count == -1 then the array is unbounded and we do not emit
1710 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1711 // Count == 0, then the array has zero elements in which case we do not emit
1713 int64_t LowerBound = SR.getLo();
1714 int64_t DefaultLowerBound = getDefaultLowerBound();
1715 int64_t Count = SR.getCount();
1717 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1718 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1720 if (Count != -1 && Count != 0)
1721 // FIXME: An unbounded array should reference the expression that defines
1723 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1724 LowerBound + Count - 1);
1727 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1728 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1730 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1732 // Emit the element type.
1733 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1735 // Get an anonymous type for index type.
1736 // FIXME: This type should be passed down from the front end
1737 // as different languages may have different sizes for indexes.
1738 DIE *IdxTy = getIndexTyDie();
1740 // Construct an anonymous type for index type.
1741 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1742 addString(IdxTy, dwarf::DW_AT_name, "int");
1743 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1744 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1745 dwarf::DW_ATE_signed);
1746 setIndexTyDie(IdxTy);
1749 // Add subranges to array type.
1750 DIArray Elements = CTy.getTypeArray();
1751 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1752 DIDescriptor Element = Elements.getElement(i);
1753 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1754 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1758 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1759 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1760 DIArray Elements = CTy.getTypeArray();
1762 // Add enumerators to enumeration type.
1763 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1764 DIEnumerator Enum(Elements.getElement(i));
1765 if (Enum.isEnumerator()) {
1766 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1767 StringRef Name = Enum.getName();
1768 addString(Enumerator, dwarf::DW_AT_name, Name);
1769 int64_t Value = Enum.getEnumValue();
1770 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1774 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1776 addType(&Buffer, DTy);
1777 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1781 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1783 void DwarfUnit::constructContainingTypeDIEs() {
1784 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1785 CE = ContainingTypeMap.end();
1787 DIE *SPDie = CI->first;
1788 DIDescriptor D(CI->second);
1791 DIE *NDie = getDIE(D);
1794 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1798 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1799 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1800 StringRef Name = DV.getName();
1802 // Define variable debug information entry.
1803 DIE *VariableDie = new DIE(DV.getTag());
1804 DbgVariable *AbsVar = DV.getAbstractVariable();
1805 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1807 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1810 addString(VariableDie, dwarf::DW_AT_name, Name);
1811 addSourceLine(VariableDie, DV.getVariable());
1812 addType(VariableDie, DV.getType());
1815 if (DV.isArtificial())
1816 addFlag(VariableDie, dwarf::DW_AT_artificial);
1818 if (isScopeAbstract) {
1819 DV.setDIE(VariableDie);
1823 // Add variable address.
1825 unsigned Offset = DV.getDotDebugLocOffset();
1826 if (Offset != ~0U) {
1827 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1828 Asm->GetTempSymbol("debug_loc", Offset));
1829 DV.setDIE(VariableDie);
1833 // Check if variable is described by a DBG_VALUE instruction.
1834 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1835 assert(DVInsn->getNumOperands() == 3);
1836 if (DVInsn->getOperand(0).isReg()) {
1837 const MachineOperand RegOp = DVInsn->getOperand(0);
1838 // If the second operand is an immediate, this is an indirect value.
1839 if (DVInsn->getOperand(1).isImm()) {
1840 MachineLocation Location(RegOp.getReg(),
1841 DVInsn->getOperand(1).getImm());
1842 addVariableAddress(DV, VariableDie, Location);
1843 } else if (RegOp.getReg())
1844 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1845 } else if (DVInsn->getOperand(0).isImm())
1846 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1847 else if (DVInsn->getOperand(0).isFPImm())
1848 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1849 else if (DVInsn->getOperand(0).isCImm())
1850 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1851 isUnsignedDIType(DD, DV.getType()));
1853 DV.setDIE(VariableDie);
1856 // .. else use frame index.
1857 int FI = DV.getFrameIndex();
1859 unsigned FrameReg = 0;
1860 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1861 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1862 MachineLocation Location(FrameReg, Offset);
1863 addVariableAddress(DV, VariableDie, Location);
1867 DV.setDIE(VariableDie);
1871 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1872 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1873 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1874 StringRef Name = DT.getName();
1876 addString(MemberDie, dwarf::DW_AT_name, Name);
1878 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1880 addSourceLine(MemberDie, DT);
1882 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1884 // For C++, virtual base classes are not at fixed offset. Use following
1885 // expression to extract appropriate offset from vtable.
1886 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1888 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1889 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1890 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1891 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1892 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1893 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1894 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1895 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1897 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1899 uint64_t Size = DT.getSizeInBits();
1900 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1901 uint64_t OffsetInBytes;
1903 if (Size != FieldSize) {
1905 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1906 getBaseTypeSize(DD, DT) >> 3);
1907 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1909 uint64_t Offset = DT.getOffsetInBits();
1910 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1911 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1912 uint64_t FieldOffset = (HiMark - FieldSize);
1913 Offset -= FieldOffset;
1915 // Maybe we need to work from the other end.
1916 if (Asm->getDataLayout().isLittleEndian())
1917 Offset = FieldSize - (Offset + Size);
1918 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1920 // Here DW_AT_data_member_location points to the anonymous
1921 // field that includes this bit field.
1922 OffsetInBytes = FieldOffset >> 3;
1924 // This is not a bitfield.
1925 OffsetInBytes = DT.getOffsetInBits() >> 3;
1927 if (DD->getDwarfVersion() <= 2) {
1928 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1929 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1930 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1931 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1933 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1937 if (DT.isProtected())
1938 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1939 dwarf::DW_ACCESS_protected);
1940 else if (DT.isPrivate())
1941 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1942 dwarf::DW_ACCESS_private);
1943 // Otherwise C++ member and base classes are considered public.
1945 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1946 dwarf::DW_ACCESS_public);
1948 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1949 dwarf::DW_VIRTUALITY_virtual);
1951 // Objective-C properties.
1952 if (MDNode *PNode = DT.getObjCProperty())
1953 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1954 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1957 if (DT.isArtificial())
1958 addFlag(MemberDie, dwarf::DW_AT_artificial);
1961 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1962 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1966 // Construct the context before querying for the existence of the DIE in case
1967 // such construction creates the DIE.
1968 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1969 assert(dwarf::isType(ContextDIE->getTag()) &&
1970 "Static member should belong to a type.");
1972 DIE *StaticMemberDIE = getDIE(DT);
1973 if (StaticMemberDIE)
1974 return StaticMemberDIE;
1976 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1978 DIType Ty = resolve(DT.getTypeDerivedFrom());
1980 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1981 addType(StaticMemberDIE, Ty);
1982 addSourceLine(StaticMemberDIE, DT);
1983 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1984 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1986 // FIXME: We could omit private if the parent is a class_type, and
1987 // public if the parent is something else.
1988 if (DT.isProtected())
1989 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1990 dwarf::DW_ACCESS_protected);
1991 else if (DT.isPrivate())
1992 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1993 dwarf::DW_ACCESS_private);
1995 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1996 dwarf::DW_ACCESS_public);
1998 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1999 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
2000 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2001 addConstantFPValue(StaticMemberDIE, CFP);
2003 return StaticMemberDIE;
2006 void DwarfUnit::emitHeader(const MCSection *ASection,
2007 const MCSymbol *ASectionSym) const {
2008 Asm->OutStreamer.AddComment("DWARF version number");
2009 Asm->EmitInt16(DD->getDwarfVersion());
2010 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2011 // We share one abbreviations table across all units so it's always at the
2012 // start of the section. Use a relocatable offset where needed to ensure
2013 // linking doesn't invalidate that offset.
2014 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2015 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2016 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2019 DwarfCompileUnit::~DwarfCompileUnit() {}
2020 DwarfTypeUnit::~DwarfTypeUnit() {}
2022 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
2023 const MCSymbol *ASectionSym) const {
2024 DwarfUnit::emitHeader(ASection, ASectionSym);
2025 Asm->OutStreamer.AddComment("Type Signature");
2026 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2027 Asm->OutStreamer.AddComment("Type DIE Offset");
2028 // In a skeleton type unit there is no type DIE so emit a zero offset.
2029 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2030 sizeof(Ty->getOffset()));
2033 void DwarfTypeUnit::initSection(const MCSection *Section) {
2034 assert(!this->Section);
2035 this->Section = Section;
2036 // Since each type unit is contained in its own COMDAT section, the begin
2037 // label and the section label are the same. Using the begin label emission in
2038 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2039 // the only other alternative of lazily constructing start-of-section labels
2040 // and storing a mapping in DwarfDebug (or AsmPrinter).
2041 this->SectionSym = this->LabelBegin =
2042 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2044 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2045 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());