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) {
359 assert(V.isVariable());
361 unsigned Line = V.getLineNumber();
365 DD->getOrCreateSourceID(V.getContext().getFilename(),
366 V.getContext().getDirectory(), getUniqueID());
367 assert(FileID && "Invalid file id");
368 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
369 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
372 /// addSourceLine - Add location information to specified debug information
374 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
375 assert(G.isGlobalVariable());
377 unsigned Line = G.getLineNumber();
381 DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(), getUniqueID());
382 assert(FileID && "Invalid file id");
383 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
384 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
387 /// addSourceLine - Add location information to specified debug information
389 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
390 assert(SP.isSubprogram());
392 // If the line number is 0, don't add it.
393 unsigned Line = SP.getLineNumber();
397 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
399 assert(FileID && "Invalid file id");
400 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
401 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
404 /// addSourceLine - Add location information to specified debug information
406 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
409 unsigned Line = Ty.getLineNumber();
412 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.getDirectory(),
414 assert(FileID && "Invalid file id");
415 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
416 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
419 /// addSourceLine - Add location information to specified debug information
421 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
422 assert(Ty.isObjCProperty());
424 unsigned Line = Ty.getLineNumber();
427 DIFile File = Ty.getFile();
428 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
429 File.getDirectory(), getUniqueID());
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, DINameSpace NS) {
440 unsigned Line = NS.getLineNumber();
443 StringRef FN = NS.getFilename();
446 DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
447 assert(FileID && "Invalid file id");
448 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
449 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
452 /// addVariableAddress - Add DW_AT_location attribute for a
453 /// DbgVariable based on provided MachineLocation.
454 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
455 MachineLocation Location) {
456 if (DV.variableHasComplexAddress())
457 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
458 else if (DV.isBlockByrefVariable())
459 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
461 addAddress(Die, dwarf::DW_AT_location, Location,
462 DV.getVariable().isIndirect());
465 /// addRegisterOp - Add register operand.
466 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
467 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
468 int DWReg = RI->getDwarfRegNum(Reg, false);
469 bool isSubRegister = DWReg < 0;
473 // Go up the super-register chain until we hit a valid dwarf register number.
474 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
475 DWReg = RI->getDwarfRegNum(*SR, false);
477 Idx = RI->getSubRegIndex(*SR, Reg);
481 DEBUG(llvm::dbgs() << "Invalid Dwarf register number.\n");
482 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
488 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
490 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
491 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
496 unsigned Size = RI->getSubRegIdxSize(Idx);
497 unsigned Offset = RI->getSubRegIdxOffset(Idx);
499 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
500 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
501 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
503 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
504 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
509 /// addRegisterOffset - Add register offset.
510 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
512 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
513 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
514 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
515 if (Reg == TRI->getFrameRegister(*Asm->MF))
516 // If variable offset is based in frame register then use fbreg.
517 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
519 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
521 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
522 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
524 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
527 /// addAddress - Add an address attribute to a die based on the location
529 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
530 const MachineLocation &Location, bool Indirect) {
531 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
533 if (Location.isReg() && !Indirect)
534 addRegisterOp(Block, Location.getReg());
536 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
537 if (Indirect && !Location.isReg()) {
538 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
542 // Now attach the location information to the DIE.
543 addBlock(Die, Attribute, Block);
546 /// addComplexAddress - Start with the address based on the location provided,
547 /// and generate the DWARF information necessary to find the actual variable
548 /// given the extra address information encoded in the DbgVariable, starting
549 /// from the starting location. Add the DWARF information to the die.
551 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
552 dwarf::Attribute Attribute,
553 const MachineLocation &Location) {
554 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
555 unsigned N = DV.getNumAddrElements();
557 if (Location.isReg()) {
558 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
559 // If first address element is OpPlus then emit
560 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
561 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
564 addRegisterOp(Block, Location.getReg());
566 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
569 uint64_t Element = DV.getAddrElement(i);
570 if (Element == DIBuilder::OpPlus) {
571 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
572 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
573 } else if (Element == DIBuilder::OpDeref) {
574 if (!Location.isReg())
575 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
577 llvm_unreachable("unknown DIBuilder Opcode");
580 // Now attach the location information to the DIE.
581 addBlock(Die, Attribute, Block);
584 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
585 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
586 gives the variable VarName either the struct, or a pointer to the struct, as
587 its type. This is necessary for various behind-the-scenes things the
588 compiler needs to do with by-reference variables in Blocks.
590 However, as far as the original *programmer* is concerned, the variable
591 should still have type 'SomeType', as originally declared.
593 The function getBlockByrefType dives into the __Block_byref_x_VarName
594 struct to find the original type of the variable, which is then assigned to
595 the variable's Debug Information Entry as its real type. So far, so good.
596 However now the debugger will expect the variable VarName to have the type
597 SomeType. So we need the location attribute for the variable to be an
598 expression that explains to the debugger how to navigate through the
599 pointers and struct to find the actual variable of type SomeType.
601 The following function does just that. We start by getting
602 the "normal" location for the variable. This will be the location
603 of either the struct __Block_byref_x_VarName or the pointer to the
604 struct __Block_byref_x_VarName.
606 The struct will look something like:
608 struct __Block_byref_x_VarName {
610 struct __Block_byref_x_VarName *forwarding;
611 ... <various other fields>
613 ... <maybe more fields>
616 If we are given the struct directly (as our starting point) we
617 need to tell the debugger to:
619 1). Add the offset of the forwarding field.
621 2). Follow that pointer to get the real __Block_byref_x_VarName
622 struct to use (the real one may have been copied onto the heap).
624 3). Add the offset for the field VarName, to find the actual variable.
626 If we started with a pointer to the struct, then we need to
627 dereference that pointer first, before the other steps.
628 Translating this into DWARF ops, we will need to append the following
629 to the current location description for the variable:
631 DW_OP_deref -- optional, if we start with a pointer
632 DW_OP_plus_uconst <forward_fld_offset>
634 DW_OP_plus_uconst <varName_fld_offset>
636 That is what this function does. */
638 /// addBlockByrefAddress - Start with the address based on the location
639 /// provided, and generate the DWARF information necessary to find the
640 /// actual Block variable (navigating the Block struct) based on the
641 /// starting location. Add the DWARF information to the die. For
642 /// more information, read large comment just above here.
644 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
645 dwarf::Attribute Attribute,
646 const MachineLocation &Location) {
647 DIType Ty = DV.getType();
649 uint16_t Tag = Ty.getTag();
650 bool isPointer = false;
652 StringRef varName = DV.getName();
654 if (Tag == dwarf::DW_TAG_pointer_type) {
655 DIDerivedType DTy(Ty);
656 TmpTy = resolve(DTy.getTypeDerivedFrom());
660 DICompositeType blockStruct(TmpTy);
662 // Find the __forwarding field and the variable field in the __Block_byref
664 DIArray Fields = blockStruct.getTypeArray();
665 DIDerivedType varField;
666 DIDerivedType forwardingField;
668 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
669 DIDerivedType DT(Fields.getElement(i));
670 StringRef fieldName = DT.getName();
671 if (fieldName == "__forwarding")
672 forwardingField = DT;
673 else if (fieldName == varName)
677 // Get the offsets for the forwarding field and the variable field.
678 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
679 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
681 // Decode the original location, and use that as the start of the byref
682 // variable's location.
683 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
685 if (Location.isReg())
686 addRegisterOp(Block, Location.getReg());
688 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
690 // If we started with a pointer to the __Block_byref... struct, then
691 // the first thing we need to do is dereference the pointer (DW_OP_deref).
693 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
695 // Next add the offset for the '__forwarding' field:
696 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
697 // adding the offset if it's 0.
698 if (forwardingFieldOffset > 0) {
699 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
700 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
703 // Now dereference the __forwarding field to get to the real __Block_byref
704 // struct: DW_OP_deref.
705 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
707 // Now that we've got the real __Block_byref... struct, add the offset
708 // for the variable's field to get to the location of the actual variable:
709 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
710 if (varFieldOffset > 0) {
711 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
712 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
715 // Now attach the location information to the DIE.
716 addBlock(Die, Attribute, Block);
719 /// isTypeSigned - Return true if the type is signed.
720 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
721 if (Ty.isDerivedType())
722 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
724 if (Ty.isBasicType())
725 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
726 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
727 *SizeInBits = Ty.getSizeInBits();
733 /// Return true if type encoding is unsigned.
734 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
735 DIDerivedType DTy(Ty);
736 if (DTy.isDerivedType())
737 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
740 if (BTy.isBasicType()) {
741 unsigned Encoding = BTy.getEncoding();
742 if (Encoding == dwarf::DW_ATE_unsigned ||
743 Encoding == dwarf::DW_ATE_unsigned_char ||
744 Encoding == dwarf::DW_ATE_boolean)
750 /// If this type is derived from a base type then return base type size.
751 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
752 unsigned Tag = Ty.getTag();
754 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
755 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
756 Tag != dwarf::DW_TAG_restrict_type)
757 return Ty.getSizeInBits();
759 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
761 // If this type is not derived from any type then take conservative approach.
762 if (!BaseType.isValid())
763 return Ty.getSizeInBits();
765 // If this is a derived type, go ahead and get the base type, unless it's a
766 // reference then it's just the size of the field. Pointer types have no need
767 // of this since they're a different type of qualification on the type.
768 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
769 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
770 return Ty.getSizeInBits();
772 if (BaseType.isDerivedType())
773 return getBaseTypeSize(DD, DIDerivedType(BaseType));
775 return BaseType.getSizeInBits();
778 /// addConstantValue - Add constant value entry in variable DIE.
779 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
781 // FIXME: This is a bit conservative/simple - it emits negative values at
782 // their maximum bit width which is a bit unfortunate (& doesn't prefer
783 // udata/sdata over dataN as suggested by the DWARF spec)
784 assert(MO.isImm() && "Invalid machine operand!");
786 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
789 // If we're a signed constant definitely use sdata.
790 if (SignedConstant) {
791 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
795 // Else use data for now unless it's larger than we can deal with.
796 switch (SizeInBits) {
798 Form = dwarf::DW_FORM_data1;
801 Form = dwarf::DW_FORM_data2;
804 Form = dwarf::DW_FORM_data4;
807 Form = dwarf::DW_FORM_data8;
810 Form = dwarf::DW_FORM_udata;
811 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
814 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
817 /// addConstantFPValue - Add constant value entry in variable DIE.
818 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
819 assert(MO.isFPImm() && "Invalid machine operand!");
820 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
821 APFloat FPImm = MO.getFPImm()->getValueAPF();
823 // Get the raw data form of the floating point.
824 const APInt FltVal = FPImm.bitcastToAPInt();
825 const char *FltPtr = (const char *)FltVal.getRawData();
827 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
828 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
829 int Incr = (LittleEndian ? 1 : -1);
830 int Start = (LittleEndian ? 0 : NumBytes - 1);
831 int Stop = (LittleEndian ? NumBytes : -1);
833 // Output the constant to DWARF one byte at a time.
834 for (; Start != Stop; Start += Incr)
835 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
837 addBlock(Die, dwarf::DW_AT_const_value, Block);
840 /// addConstantFPValue - Add constant value entry in variable DIE.
841 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
842 // Pass this down to addConstantValue as an unsigned bag of bits.
843 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
846 /// addConstantValue - Add constant value entry in variable DIE.
847 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
849 addConstantValue(Die, CI->getValue(), Unsigned);
852 // addConstantValue - Add constant value entry in variable DIE.
853 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
854 unsigned CIBitWidth = Val.getBitWidth();
855 if (CIBitWidth <= 64) {
856 // If we're a signed constant definitely use sdata.
858 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
863 // Else use data for now unless it's larger than we can deal with.
865 switch (CIBitWidth) {
867 Form = dwarf::DW_FORM_data1;
870 Form = dwarf::DW_FORM_data2;
873 Form = dwarf::DW_FORM_data4;
876 Form = dwarf::DW_FORM_data8;
879 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
883 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
887 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
889 // Get the raw data form of the large APInt.
890 const uint64_t *Ptr64 = Val.getRawData();
892 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
893 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
895 // Output the constant to DWARF one byte at a time.
896 for (int i = 0; i < NumBytes; i++) {
899 c = Ptr64[i / 8] >> (8 * (i & 7));
901 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
902 addUInt(Block, dwarf::DW_FORM_data1, c);
905 addBlock(Die, dwarf::DW_AT_const_value, Block);
908 /// addTemplateParams - Add template parameters into buffer.
909 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
910 // Add template parameters.
911 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
912 DIDescriptor Element = TParams.getElement(i);
913 if (Element.isTemplateTypeParameter())
914 constructTemplateTypeParameterDIE(Buffer,
915 DITemplateTypeParameter(Element));
916 else if (Element.isTemplateValueParameter())
917 constructTemplateValueParameterDIE(Buffer,
918 DITemplateValueParameter(Element));
922 /// getOrCreateContextDIE - Get context owner's DIE.
923 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
924 if (!Context || Context.isFile())
926 if (Context.isType())
927 return getOrCreateTypeDIE(DIType(Context));
928 if (Context.isNameSpace())
929 return getOrCreateNameSpace(DINameSpace(Context));
930 if (Context.isSubprogram())
931 return getOrCreateSubprogramDIE(DISubprogram(Context));
932 return getDIE(Context);
935 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
936 DIScope Context = resolve(Ty.getContext());
937 DIE *ContextDIE = getOrCreateContextDIE(Context);
939 DIE *TyDIE = getDIE(Ty);
944 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
946 constructTypeDIE(*TyDIE, Ty);
948 updateAcceleratorTables(Context, Ty, TyDIE);
952 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
954 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
961 // Construct the context before querying for the existence of the DIE in case
962 // such construction creates the DIE.
963 DIScope Context = resolve(Ty.getContext());
964 DIE *ContextDIE = getOrCreateContextDIE(Context);
967 DIE *TyDIE = getDIE(Ty);
972 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
974 if (Ty.isBasicType())
975 constructTypeDIE(*TyDIE, DIBasicType(Ty));
976 else if (Ty.isCompositeType()) {
977 DICompositeType CTy(Ty);
978 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
979 if (MDString *TypeId = CTy.getIdentifier()) {
980 DD->addDwarfTypeUnitType(getCUNode(), TypeId->getString(), TyDIE, CTy);
981 // Skip updating the accellerator tables since this is not the full type
984 constructTypeDIE(*TyDIE, CTy);
986 assert(Ty.isDerivedType() && "Unknown kind of DIType");
987 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
990 updateAcceleratorTables(Context, Ty, TyDIE);
995 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
997 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
998 bool IsImplementation = 0;
999 if (Ty.isCompositeType()) {
1000 DICompositeType CT(Ty);
1001 // A runtime language of 0 actually means C/C++ and that any
1002 // non-negative value is some version of Objective-C/C++.
1003 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1005 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1006 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
1008 if (!Context || Context.isCompileUnit() || Context.isFile() ||
1009 Context.isNameSpace())
1010 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1014 /// addType - Add a new type attribute to the specified entity.
1015 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
1016 assert(Ty && "Trying to add a type that doesn't exist?");
1018 // Check for pre-existence.
1019 DIEEntry *Entry = getDIEEntry(Ty);
1020 // If it exists then use the existing value.
1022 addDIEEntry(Entity, Attribute, Entry);
1027 DIE *Buffer = getOrCreateTypeDIE(Ty);
1030 Entry = createDIEEntry(Buffer);
1031 insertDIEEntry(Ty, Entry);
1032 addDIEEntry(Entity, Attribute, Entry);
1035 // Accelerator table mutators - add each name along with its companion
1036 // DIE to the proper table while ensuring that the name that we're going
1037 // to reference is in the string table. We do this since the names we
1038 // add may not only be identical to the names in the DIE.
1039 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1040 if (!DD->useDwarfAccelTables()) return;
1041 DU->getStringPoolEntry(Name);
1042 std::vector<const DIE *> &DIEs = AccelNames[Name];
1043 DIEs.push_back(Die);
1046 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1047 if (!DD->useDwarfAccelTables()) return;
1048 DU->getStringPoolEntry(Name);
1049 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1050 DIEs.push_back(Die);
1053 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1054 if (!DD->useDwarfAccelTables()) return;
1055 DU->getStringPoolEntry(Name);
1056 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1057 DIEs.push_back(Die);
1060 void DwarfUnit::addAccelType(StringRef Name,
1061 std::pair<const DIE *, unsigned> Die) {
1062 if (!DD->useDwarfAccelTables()) return;
1063 DU->getStringPoolEntry(Name);
1064 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1065 DIEs.push_back(Die);
1068 /// addGlobalName - Add a new global name to the compile unit.
1069 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1070 std::string FullName = getParentContextString(Context) + Name.str();
1071 GlobalNames[FullName] = Die;
1074 /// getParentContextString - Walks the metadata parent chain in a language
1075 /// specific manner (using the compile unit language) and returns
1076 /// it as a string. This is done at the metadata level because DIEs may
1077 /// not currently have been added to the parent context and walking the
1078 /// DIEs looking for names is more expensive than walking the metadata.
1079 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1083 // FIXME: Decide whether to implement this for non-C++ languages.
1084 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1088 SmallVector<DIScope, 1> Parents;
1089 while (!Context.isCompileUnit()) {
1090 Parents.push_back(Context);
1091 if (Context.getContext())
1092 Context = resolve(Context.getContext());
1094 // Structure, etc types will have a NULL context if they're at the top
1099 // Reverse iterate over our list to go from the outermost construct to the
1101 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1105 StringRef Name = Ctx.getName();
1106 if (!Name.empty()) {
1114 /// constructTypeDIE - Construct basic type die from DIBasicType.
1115 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1116 // Get core information.
1117 StringRef Name = BTy.getName();
1118 // Add name if not anonymous or intermediate type.
1120 addString(&Buffer, dwarf::DW_AT_name, Name);
1122 // An unspecified type only has a name attribute.
1123 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1126 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1129 uint64_t Size = BTy.getSizeInBits() >> 3;
1130 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1133 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1134 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1135 // Get core information.
1136 StringRef Name = DTy.getName();
1137 uint64_t Size = DTy.getSizeInBits() >> 3;
1138 uint16_t Tag = Buffer.getTag();
1140 // Map to main type, void will not have a type.
1141 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1143 addType(&Buffer, FromTy);
1145 // Add name if not anonymous or intermediate type.
1147 addString(&Buffer, dwarf::DW_AT_name, Name);
1149 // Add size if non-zero (derived types might be zero-sized.)
1150 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1151 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1153 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1154 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1155 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1156 // Add source line info if available and TyDesc is not a forward declaration.
1157 if (!DTy.isForwardDecl())
1158 addSourceLine(&Buffer, DTy);
1161 /// constructTypeDIE - Construct type DIE from DICompositeType.
1162 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1163 // Add name if not anonymous or intermediate type.
1164 StringRef Name = CTy.getName();
1166 uint64_t Size = CTy.getSizeInBits() >> 3;
1167 uint16_t Tag = Buffer.getTag();
1170 case dwarf::DW_TAG_array_type:
1171 constructArrayTypeDIE(Buffer, CTy);
1173 case dwarf::DW_TAG_enumeration_type:
1174 constructEnumTypeDIE(Buffer, CTy);
1176 case dwarf::DW_TAG_subroutine_type: {
1177 // Add return type. A void return won't have a type.
1178 DIArray Elements = CTy.getTypeArray();
1179 DIType RTy(Elements.getElement(0));
1181 addType(&Buffer, RTy);
1183 bool isPrototyped = true;
1185 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1186 DIDescriptor Ty = Elements.getElement(i);
1187 if (Ty.isUnspecifiedParameter()) {
1188 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1189 isPrototyped = false;
1191 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1192 addType(Arg, DIType(Ty));
1193 if (DIType(Ty).isArtificial())
1194 addFlag(Arg, dwarf::DW_AT_artificial);
1197 // Add prototype flag if we're dealing with a C language and the
1198 // function has been prototyped.
1199 uint16_t Language = getLanguage();
1201 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1202 Language == dwarf::DW_LANG_ObjC))
1203 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1205 if (CTy.isLValueReference())
1206 addFlag(&Buffer, dwarf::DW_AT_reference);
1208 if (CTy.isRValueReference())
1209 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1211 case dwarf::DW_TAG_structure_type:
1212 case dwarf::DW_TAG_union_type:
1213 case dwarf::DW_TAG_class_type: {
1214 // Add elements to structure type.
1215 DIArray Elements = CTy.getTypeArray();
1216 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1217 DIDescriptor Element = Elements.getElement(i);
1218 DIE *ElemDie = NULL;
1219 if (Element.isSubprogram())
1220 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1221 else if (Element.isDerivedType()) {
1222 DIDerivedType DDTy(Element);
1223 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1224 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1225 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1226 dwarf::DW_AT_friend);
1227 } else if (DDTy.isStaticMember()) {
1228 getOrCreateStaticMemberDIE(DDTy);
1230 constructMemberDIE(Buffer, DDTy);
1232 } else if (Element.isObjCProperty()) {
1233 DIObjCProperty Property(Element);
1234 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1235 StringRef PropertyName = Property.getObjCPropertyName();
1236 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1237 if (Property.getType())
1238 addType(ElemDie, Property.getType());
1239 addSourceLine(ElemDie, Property);
1240 StringRef GetterName = Property.getObjCPropertyGetterName();
1241 if (!GetterName.empty())
1242 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1243 StringRef SetterName = Property.getObjCPropertySetterName();
1244 if (!SetterName.empty())
1245 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1246 unsigned PropertyAttributes = 0;
1247 if (Property.isReadOnlyObjCProperty())
1248 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1249 if (Property.isReadWriteObjCProperty())
1250 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1251 if (Property.isAssignObjCProperty())
1252 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1253 if (Property.isRetainObjCProperty())
1254 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1255 if (Property.isCopyObjCProperty())
1256 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1257 if (Property.isNonAtomicObjCProperty())
1258 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1259 if (PropertyAttributes)
1260 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1261 PropertyAttributes);
1263 DIEEntry *Entry = getDIEEntry(Element);
1265 Entry = createDIEEntry(ElemDie);
1266 insertDIEEntry(Element, Entry);
1272 if (CTy.isAppleBlockExtension())
1273 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1275 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1277 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1278 getOrCreateTypeDIE(ContainingType));
1280 if (CTy.isObjcClassComplete())
1281 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1283 // Add template parameters to a class, structure or union types.
1284 // FIXME: The support isn't in the metadata for this yet.
1285 if (Tag == dwarf::DW_TAG_class_type ||
1286 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1287 addTemplateParams(Buffer, CTy.getTemplateParams());
1295 // Add name if not anonymous or intermediate type.
1297 addString(&Buffer, dwarf::DW_AT_name, Name);
1299 if (Tag == dwarf::DW_TAG_enumeration_type ||
1300 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1301 Tag == dwarf::DW_TAG_union_type) {
1302 // Add size if non-zero (derived types might be zero-sized.)
1303 // TODO: Do we care about size for enum forward declarations?
1305 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1306 else if (!CTy.isForwardDecl())
1307 // Add zero size if it is not a forward declaration.
1308 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1310 // If we're a forward decl, say so.
1311 if (CTy.isForwardDecl())
1312 addFlag(&Buffer, dwarf::DW_AT_declaration);
1314 // Add source line info if available.
1315 if (!CTy.isForwardDecl())
1316 addSourceLine(&Buffer, CTy);
1318 // No harm in adding the runtime language to the declaration.
1319 unsigned RLang = CTy.getRunTimeLang();
1321 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1326 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1327 /// DITemplateTypeParameter.
1328 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1329 DITemplateTypeParameter TP) {
1331 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1332 // Add the type if it exists, it could be void and therefore no type.
1334 addType(ParamDIE, resolve(TP.getType()));
1335 if (!TP.getName().empty())
1336 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1339 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1340 /// DITemplateValueParameter.
1342 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1343 DITemplateValueParameter VP) {
1344 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1346 // Add the type if there is one, template template and template parameter
1347 // packs will not have a type.
1348 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1349 addType(ParamDIE, resolve(VP.getType()));
1350 if (!VP.getName().empty())
1351 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1352 if (Value *Val = VP.getValue()) {
1353 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1354 addConstantValue(ParamDIE, CI,
1355 isUnsignedDIType(DD, resolve(VP.getType())));
1356 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1357 // For declaration non-type template parameters (such as global values and
1359 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1360 addOpAddress(Block, Asm->getSymbol(GV));
1361 // Emit DW_OP_stack_value to use the address as the immediate value of the
1362 // parameter, rather than a pointer to it.
1363 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1364 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1365 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1366 assert(isa<MDString>(Val));
1367 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1368 cast<MDString>(Val)->getString());
1369 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1370 assert(isa<MDNode>(Val));
1371 DIArray A(cast<MDNode>(Val));
1372 addTemplateParams(*ParamDIE, A);
1377 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1378 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1379 // Construct the context before querying for the existence of the DIE in case
1380 // such construction creates the DIE.
1381 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1383 DIE *NDie = getDIE(NS);
1386 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1388 if (!NS.getName().empty()) {
1389 addString(NDie, dwarf::DW_AT_name, NS.getName());
1390 addAccelNamespace(NS.getName(), NDie);
1391 addGlobalName(NS.getName(), NDie, NS.getContext());
1393 addAccelNamespace("(anonymous namespace)", NDie);
1394 addSourceLine(NDie, NS);
1398 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1399 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1400 // Construct the context before querying for the existence of the DIE in case
1401 // such construction creates the DIE (as is the case for member function
1403 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1405 DIE *SPDie = getDIE(SP);
1409 DISubprogram SPDecl = SP.getFunctionDeclaration();
1410 if (SPDecl.isSubprogram())
1411 // Add subprogram definitions to the CU die directly.
1412 ContextDIE = UnitDie.get();
1414 // DW_TAG_inlined_subroutine may refer to this DIE.
1415 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1417 DIE *DeclDie = NULL;
1418 if (SPDecl.isSubprogram())
1419 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1421 // Add function template parameters.
1422 addTemplateParams(*SPDie, SP.getTemplateParams());
1424 // If this DIE is going to refer declaration info using AT_specification
1425 // then there is no need to add other attributes.
1427 // Refer function declaration directly.
1428 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1433 // Add the linkage name if we have one.
1434 StringRef LinkageName = SP.getLinkageName();
1435 if (!LinkageName.empty())
1436 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1437 GlobalValue::getRealLinkageName(LinkageName));
1439 // Constructors and operators for anonymous aggregates do not have names.
1440 if (!SP.getName().empty())
1441 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1443 addSourceLine(SPDie, SP);
1445 // Add the prototype if we have a prototype and we have a C like
1447 uint16_t Language = getLanguage();
1448 if (SP.isPrototyped() &&
1449 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1450 Language == dwarf::DW_LANG_ObjC))
1451 addFlag(SPDie, dwarf::DW_AT_prototyped);
1453 DICompositeType SPTy = SP.getType();
1454 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1455 "the type of a subprogram should be a subroutine");
1457 DIArray Args = SPTy.getTypeArray();
1458 // Add a return type. If this is a type like a C/C++ void type we don't add a
1460 if (Args.getElement(0))
1461 addType(SPDie, DIType(Args.getElement(0)));
1463 unsigned VK = SP.getVirtuality();
1465 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1466 DIEBlock *Block = getDIEBlock();
1467 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1468 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1469 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1470 ContainingTypeMap.insert(
1471 std::make_pair(SPDie, resolve(SP.getContainingType())));
1474 if (!SP.isDefinition()) {
1475 addFlag(SPDie, dwarf::DW_AT_declaration);
1477 // Add arguments. Do not add arguments for subprogram definition. They will
1478 // be handled while processing variables.
1479 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1480 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1481 DIType ATy(Args.getElement(i));
1483 if (ATy.isArtificial())
1484 addFlag(Arg, dwarf::DW_AT_artificial);
1488 if (SP.isArtificial())
1489 addFlag(SPDie, dwarf::DW_AT_artificial);
1491 if (!SP.isLocalToUnit())
1492 addFlag(SPDie, dwarf::DW_AT_external);
1494 if (SP.isOptimized())
1495 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1497 if (unsigned isa = Asm->getISAEncoding()) {
1498 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1501 if (SP.isLValueReference())
1502 addFlag(SPDie, dwarf::DW_AT_reference);
1504 if (SP.isRValueReference())
1505 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1507 if (SP.isProtected())
1508 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1509 dwarf::DW_ACCESS_protected);
1510 else if (SP.isPrivate())
1511 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1512 dwarf::DW_ACCESS_private);
1514 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1515 dwarf::DW_ACCESS_public);
1517 if (SP.isExplicit())
1518 addFlag(SPDie, dwarf::DW_AT_explicit);
1523 // Return const expression if value is a GEP to access merged global
1525 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1526 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1527 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1528 if (!CE || CE->getNumOperands() != 3 ||
1529 CE->getOpcode() != Instruction::GetElementPtr)
1532 // First operand points to a global struct.
1533 Value *Ptr = CE->getOperand(0);
1534 if (!isa<GlobalValue>(Ptr) ||
1535 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1538 // Second operand is zero.
1539 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1540 if (!CI || !CI->isZero())
1543 // Third operand is offset.
1544 if (!isa<ConstantInt>(CE->getOperand(2)))
1550 /// createGlobalVariableDIE - create global variable DIE.
1551 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1552 // Check for pre-existence.
1556 assert(GV.isGlobalVariable());
1558 DIScope GVContext = GV.getContext();
1559 DIType GTy = GV.getType();
1561 // If this is a static data member definition, some attributes belong
1562 // to the declaration DIE.
1563 DIE *VariableDIE = NULL;
1564 bool IsStaticMember = false;
1565 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1566 if (SDMDecl.Verify()) {
1567 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1568 // We need the declaration DIE that is in the static member's class.
1569 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1570 IsStaticMember = true;
1573 // If this is not a static data member definition, create the variable
1574 // DIE and add the initial set of attributes to it.
1576 // Construct the context before querying for the existence of the DIE in
1577 // case such construction creates the DIE.
1578 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1581 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1583 // Add name and type.
1584 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1585 addType(VariableDIE, GTy);
1587 // Add scoping info.
1588 if (!GV.isLocalToUnit())
1589 addFlag(VariableDIE, dwarf::DW_AT_external);
1591 // Add line number info.
1592 addSourceLine(VariableDIE, GV);
1596 bool addToAccelTable = false;
1597 DIE *VariableSpecDIE = NULL;
1598 bool isGlobalVariable = GV.getGlobal() != NULL;
1599 if (isGlobalVariable) {
1600 addToAccelTable = true;
1601 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1602 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1603 if (GV.getGlobal()->isThreadLocal()) {
1604 // FIXME: Make this work with -gsplit-dwarf.
1605 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1606 assert((PointerSize == 4 || PointerSize == 8) &&
1607 "Add support for other sizes if necessary");
1608 const MCExpr *Expr =
1609 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1610 // Based on GCC's support for TLS:
1611 if (!DD->useSplitDwarf()) {
1612 // 1) Start with a constNu of the appropriate pointer size
1613 addUInt(Block, dwarf::DW_FORM_data1,
1614 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1615 // 2) containing the (relocated) offset of the TLS variable
1616 // within the module's TLS block.
1617 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1619 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1620 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1622 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1623 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1625 DD->addArangeLabel(SymbolCU(this, Sym));
1626 addOpAddress(Block, Sym);
1628 // Do not create specification DIE if context is either compile unit
1630 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1631 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1632 // Create specification DIE.
1633 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1634 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1635 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1636 // A static member's declaration is already flagged as such.
1637 if (!SDMDecl.Verify())
1638 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1640 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1642 // Add the linkage name.
1643 StringRef LinkageName = GV.getLinkageName();
1644 if (!LinkageName.empty())
1645 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1646 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1648 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1650 dwarf::DW_AT_MIPS_linkage_name,
1651 GlobalValue::getRealLinkageName(LinkageName));
1652 } else if (const ConstantInt *CI =
1653 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1654 // AT_const_value was added when the static member was created. To avoid
1655 // emitting AT_const_value multiple times, we only add AT_const_value when
1656 // it is not a static member.
1657 if (!IsStaticMember)
1658 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1659 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1660 addToAccelTable = true;
1661 // GV is a merged global.
1662 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1663 Value *Ptr = CE->getOperand(0);
1664 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1665 DD->addArangeLabel(SymbolCU(this, Sym));
1666 addOpAddress(Block, Sym);
1667 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1668 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1669 addUInt(Block, dwarf::DW_FORM_udata,
1670 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1671 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1672 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1675 if (addToAccelTable) {
1676 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1677 addAccelName(GV.getName(), AddrDIE);
1679 // If the linkage name is different than the name, go ahead and output
1680 // that as well into the name table.
1681 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1682 addAccelName(GV.getLinkageName(), AddrDIE);
1685 if (!GV.isLocalToUnit())
1686 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1690 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1691 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1692 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1693 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1695 // The LowerBound value defines the lower bounds which is typically zero for
1696 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1697 // Count == -1 then the array is unbounded and we do not emit
1698 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1699 // Count == 0, then the array has zero elements in which case we do not emit
1701 int64_t LowerBound = SR.getLo();
1702 int64_t DefaultLowerBound = getDefaultLowerBound();
1703 int64_t Count = SR.getCount();
1705 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1706 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1708 if (Count != -1 && Count != 0)
1709 // FIXME: An unbounded array should reference the expression that defines
1711 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1712 LowerBound + Count - 1);
1715 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1716 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1718 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1720 // Emit the element type.
1721 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1723 // Get an anonymous type for index type.
1724 // FIXME: This type should be passed down from the front end
1725 // as different languages may have different sizes for indexes.
1726 DIE *IdxTy = getIndexTyDie();
1728 // Construct an anonymous type for index type.
1729 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1730 addString(IdxTy, dwarf::DW_AT_name, "int");
1731 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1732 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1733 dwarf::DW_ATE_signed);
1734 setIndexTyDie(IdxTy);
1737 // Add subranges to array type.
1738 DIArray Elements = CTy.getTypeArray();
1739 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1740 DIDescriptor Element = Elements.getElement(i);
1741 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1742 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1746 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1747 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1748 DIArray Elements = CTy.getTypeArray();
1750 // Add enumerators to enumeration type.
1751 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1752 DIEnumerator Enum(Elements.getElement(i));
1753 if (Enum.isEnumerator()) {
1754 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1755 StringRef Name = Enum.getName();
1756 addString(Enumerator, dwarf::DW_AT_name, Name);
1757 int64_t Value = Enum.getEnumValue();
1758 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1762 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1764 addType(&Buffer, DTy);
1765 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1769 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1771 void DwarfUnit::constructContainingTypeDIEs() {
1772 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1773 CE = ContainingTypeMap.end();
1775 DIE *SPDie = CI->first;
1776 DIDescriptor D(CI->second);
1779 DIE *NDie = getDIE(D);
1782 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1786 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1787 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1788 StringRef Name = DV.getName();
1790 // Define variable debug information entry.
1791 DIE *VariableDie = new DIE(DV.getTag());
1792 DbgVariable *AbsVar = DV.getAbstractVariable();
1793 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1795 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1798 addString(VariableDie, dwarf::DW_AT_name, Name);
1799 addSourceLine(VariableDie, DV.getVariable());
1800 addType(VariableDie, DV.getType());
1803 if (DV.isArtificial())
1804 addFlag(VariableDie, dwarf::DW_AT_artificial);
1806 if (isScopeAbstract) {
1807 DV.setDIE(VariableDie);
1811 // Add variable address.
1813 unsigned Offset = DV.getDotDebugLocOffset();
1814 if (Offset != ~0U) {
1815 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1816 Asm->GetTempSymbol("debug_loc", Offset));
1817 DV.setDIE(VariableDie);
1821 // Check if variable is described by a DBG_VALUE instruction.
1822 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1823 assert(DVInsn->getNumOperands() == 3);
1824 if (DVInsn->getOperand(0).isReg()) {
1825 const MachineOperand RegOp = DVInsn->getOperand(0);
1826 // If the second operand is an immediate, this is an indirect value.
1827 if (DVInsn->getOperand(1).isImm()) {
1828 MachineLocation Location(RegOp.getReg(),
1829 DVInsn->getOperand(1).getImm());
1830 addVariableAddress(DV, VariableDie, Location);
1831 } else if (RegOp.getReg())
1832 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1833 } else if (DVInsn->getOperand(0).isImm())
1834 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1835 else if (DVInsn->getOperand(0).isFPImm())
1836 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1837 else if (DVInsn->getOperand(0).isCImm())
1838 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1839 isUnsignedDIType(DD, DV.getType()));
1841 DV.setDIE(VariableDie);
1844 // .. else use frame index.
1845 int FI = DV.getFrameIndex();
1847 unsigned FrameReg = 0;
1848 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1849 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1850 MachineLocation Location(FrameReg, Offset);
1851 addVariableAddress(DV, VariableDie, Location);
1855 DV.setDIE(VariableDie);
1859 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1860 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1861 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1862 StringRef Name = DT.getName();
1864 addString(MemberDie, dwarf::DW_AT_name, Name);
1866 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1868 addSourceLine(MemberDie, DT);
1870 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1872 // For C++, virtual base classes are not at fixed offset. Use following
1873 // expression to extract appropriate offset from vtable.
1874 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1876 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1877 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1878 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1879 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1880 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1881 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1882 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1883 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1885 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1887 uint64_t Size = DT.getSizeInBits();
1888 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1889 uint64_t OffsetInBytes;
1891 if (Size != FieldSize) {
1893 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1894 getBaseTypeSize(DD, DT) >> 3);
1895 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1897 uint64_t Offset = DT.getOffsetInBits();
1898 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1899 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1900 uint64_t FieldOffset = (HiMark - FieldSize);
1901 Offset -= FieldOffset;
1903 // Maybe we need to work from the other end.
1904 if (Asm->getDataLayout().isLittleEndian())
1905 Offset = FieldSize - (Offset + Size);
1906 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1908 // Here DW_AT_data_member_location points to the anonymous
1909 // field that includes this bit field.
1910 OffsetInBytes = FieldOffset >> 3;
1912 // This is not a bitfield.
1913 OffsetInBytes = DT.getOffsetInBits() >> 3;
1915 if (DD->getDwarfVersion() <= 2) {
1916 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1917 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1918 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1919 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1921 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1925 if (DT.isProtected())
1926 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1927 dwarf::DW_ACCESS_protected);
1928 else if (DT.isPrivate())
1929 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1930 dwarf::DW_ACCESS_private);
1931 // Otherwise C++ member and base classes are considered public.
1933 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1934 dwarf::DW_ACCESS_public);
1936 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1937 dwarf::DW_VIRTUALITY_virtual);
1939 // Objective-C properties.
1940 if (MDNode *PNode = DT.getObjCProperty())
1941 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1942 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1945 if (DT.isArtificial())
1946 addFlag(MemberDie, dwarf::DW_AT_artificial);
1949 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1950 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1954 // Construct the context before querying for the existence of the DIE in case
1955 // such construction creates the DIE.
1956 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1957 assert(dwarf::isType(ContextDIE->getTag()) &&
1958 "Static member should belong to a type.");
1960 DIE *StaticMemberDIE = getDIE(DT);
1961 if (StaticMemberDIE)
1962 return StaticMemberDIE;
1964 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1966 DIType Ty = resolve(DT.getTypeDerivedFrom());
1968 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1969 addType(StaticMemberDIE, Ty);
1970 addSourceLine(StaticMemberDIE, DT);
1971 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1972 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1974 // FIXME: We could omit private if the parent is a class_type, and
1975 // public if the parent is something else.
1976 if (DT.isProtected())
1977 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1978 dwarf::DW_ACCESS_protected);
1979 else if (DT.isPrivate())
1980 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1981 dwarf::DW_ACCESS_private);
1983 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1984 dwarf::DW_ACCESS_public);
1986 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1987 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1988 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1989 addConstantFPValue(StaticMemberDIE, CFP);
1991 return StaticMemberDIE;
1994 void DwarfUnit::emitHeader(const MCSection *ASection,
1995 const MCSymbol *ASectionSym) const {
1996 Asm->OutStreamer.AddComment("DWARF version number");
1997 Asm->EmitInt16(DD->getDwarfVersion());
1998 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1999 // We share one abbreviations table across all units so it's always at the
2000 // start of the section. Use a relocatable offset where needed to ensure
2001 // linking doesn't invalidate that offset.
2002 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2003 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2004 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2007 DwarfCompileUnit::~DwarfCompileUnit() {}
2008 DwarfTypeUnit::~DwarfTypeUnit() {}
2010 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
2011 const MCSymbol *ASectionSym) const {
2012 DwarfUnit::emitHeader(ASection, ASectionSym);
2013 Asm->OutStreamer.AddComment("Type Signature");
2014 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2015 Asm->OutStreamer.AddComment("Type DIE Offset");
2016 // In a skeleton type unit there is no type DIE so emit a zero offset.
2017 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2018 sizeof(Ty->getOffset()));
2021 void DwarfTypeUnit::initSection(const MCSection *Section) {
2022 assert(!this->Section);
2023 this->Section = Section;
2024 // Since each type unit is contained in its own COMDAT section, the begin
2025 // label and the section label are the same. Using the begin label emission in
2026 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2027 // the only other alternative of lazily constructing start-of-section labels
2028 // and storing a mapping in DwarfDebug (or AsmPrinter).
2029 this->SectionSym = this->LabelBegin =
2030 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2032 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2033 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());