1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for constructing a dwarf compile unit.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
16 #include "DwarfUnit.h"
17 #include "DwarfAccelTable.h"
18 #include "DwarfDebug.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/DIBuilder.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCSection.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/Target/Mangler.h"
29 #include "llvm/Target/TargetFrameLowering.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Support/CommandLine.h"
38 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
39 cl::desc("Generate DWARF4 type units."),
42 /// Unit - Unit constructor.
43 DwarfUnit::DwarfUnit(unsigned UID, DIE *D, DICompileUnit Node, AsmPrinter *A,
44 DwarfDebug *DW, DwarfFile *DWU)
45 : UniqueID(UID), Node(Node), UnitDie(D), DebugInfoOffset(0), Asm(A), DD(DW),
46 DU(DWU), IndexTyDie(0), Section(0), Skeleton(0) {
47 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
50 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
51 AsmPrinter *A, DwarfDebug *DW,
53 : DwarfUnit(UID, D, Node, A, DW, DWU) {
57 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DIE *D, uint16_t Language,
58 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
59 : DwarfUnit(UID, D, DICompileUnit(), A, DW, DWU), Language(Language) {}
61 /// ~Unit - Destructor for compile unit.
62 DwarfUnit::~DwarfUnit() {
63 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
64 DIEBlocks[j]->~DIEBlock();
67 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
68 /// information entry.
69 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) {
70 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
74 /// getDefaultLowerBound - Return the default lower bound for an array. If the
75 /// DWARF version doesn't handle the language, return -1.
76 int64_t DwarfUnit::getDefaultLowerBound() const {
77 switch (getLanguage()) {
81 case dwarf::DW_LANG_C89:
82 case dwarf::DW_LANG_C99:
83 case dwarf::DW_LANG_C:
84 case dwarf::DW_LANG_C_plus_plus:
85 case dwarf::DW_LANG_ObjC:
86 case dwarf::DW_LANG_ObjC_plus_plus:
89 case dwarf::DW_LANG_Fortran77:
90 case dwarf::DW_LANG_Fortran90:
91 case dwarf::DW_LANG_Fortran95:
94 // The languages below have valid values only if the DWARF version >= 4.
95 case dwarf::DW_LANG_Java:
96 case dwarf::DW_LANG_Python:
97 case dwarf::DW_LANG_UPC:
98 case dwarf::DW_LANG_D:
99 if (dwarf::DWARF_VERSION >= 4)
103 case dwarf::DW_LANG_Ada83:
104 case dwarf::DW_LANG_Ada95:
105 case dwarf::DW_LANG_Cobol74:
106 case dwarf::DW_LANG_Cobol85:
107 case dwarf::DW_LANG_Modula2:
108 case dwarf::DW_LANG_Pascal83:
109 case dwarf::DW_LANG_PLI:
110 if (dwarf::DWARF_VERSION >= 4)
118 /// Check whether the DIE for this MDNode can be shared across CUs.
119 static bool isShareableAcrossCUs(DIDescriptor D) {
120 // When the MDNode can be part of the type system, the DIE can be shared
122 // Combining type units and cross-CU DIE sharing is lower value (since
123 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
124 // level already) but may be implementable for some value in projects
125 // building multiple independent libraries with LTO and then linking those
127 return (D.isType() ||
128 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
129 !GenerateDwarfTypeUnits;
132 /// getDIE - Returns the debug information entry map slot for the
133 /// specified debug variable. We delegate the request to DwarfDebug
134 /// when the DIE for this MDNode can be shared across CUs. The mappings
135 /// will be kept in DwarfDebug for shareable DIEs.
136 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
137 if (isShareableAcrossCUs(D))
138 return DD->getDIE(D);
139 return MDNodeToDieMap.lookup(D);
142 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
143 /// when the DIE for this MDNode can be shared across CUs. The mappings
144 /// will be kept in DwarfDebug for shareable DIEs.
145 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
146 if (isShareableAcrossCUs(Desc)) {
147 DD->insertDIE(Desc, D);
150 MDNodeToDieMap.insert(std::make_pair(Desc, D));
153 /// addFlag - Add a flag that is true.
154 void DwarfUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
155 if (DD->getDwarfVersion() >= 4)
156 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
158 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
161 /// addUInt - Add an unsigned integer attribute data and value.
163 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
164 Optional<dwarf::Form> Form, uint64_t Integer) {
166 Form = DIEInteger::BestForm(false, Integer);
167 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
169 Die->addValue(Attribute, *Form, Value);
172 void DwarfUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
173 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
176 /// addSInt - Add an signed integer attribute data and value.
178 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
179 Optional<dwarf::Form> Form, int64_t Integer) {
181 Form = DIEInteger::BestForm(true, Integer);
182 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
183 Die->addValue(Attribute, *Form, Value);
186 void DwarfUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form,
188 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
191 /// addString - Add a string attribute data and value. We always emit a
192 /// reference to the string pool instead of immediate strings so that DIEs have
193 /// more predictable sizes. In the case of split dwarf we emit an index
194 /// into another table which gets us the static offset into the string
196 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute,
199 if (!DD->useSplitDwarf())
200 return addLocalString(Die, Attribute, String);
202 unsigned idx = DU->getStringPoolIndex(String);
203 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
204 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
205 Die->addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
208 /// addLocalString - Add a string attribute data and value. This is guaranteed
209 /// to be in the local string pool instead of indirected.
210 void DwarfUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
212 MCSymbol *Symb = DU->getStringPoolEntry(String);
214 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
215 Value = new (DIEValueAllocator) DIELabel(Symb);
217 MCSymbol *StringPool = DU->getStringPoolSym();
218 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
220 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
221 Die->addValue(Attribute, dwarf::DW_FORM_strp, Str);
224 /// addExpr - Add a Dwarf expression attribute data and value.
226 void DwarfUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
227 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
228 Die->addValue((dwarf::Attribute)0, Form, Value);
231 /// addLabel - Add a Dwarf label attribute data and value.
233 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
234 const MCSymbol *Label) {
235 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
236 Die->addValue(Attribute, Form, Value);
239 void DwarfUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
240 const MCSymbol *Label) {
241 addLabel(Die, (dwarf::Attribute)0, Form, Label);
244 /// addSectionLabel - Add a Dwarf section label attribute data and value.
246 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
247 const MCSymbol *Label) {
248 if (DD->getDwarfVersion() >= 4)
249 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
251 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
254 /// addSectionOffset - Add an offset into a section attribute data and value.
256 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
258 if (DD->getDwarfVersion() >= 4)
259 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
261 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
264 /// addLabelAddress - Add a dwarf label attribute data and value using
265 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
267 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
270 DD->addArangeLabel(SymbolCU(this, Label));
272 if (!DD->useSplitDwarf()) {
274 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
275 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
277 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
278 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
281 unsigned idx = DU->getAddrPoolIndex(Label);
282 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
283 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
287 /// addOpAddress - Add a dwarf op address data and value using the
288 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
290 void DwarfUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
291 if (!DD->useSplitDwarf()) {
292 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
293 addLabel(Die, dwarf::DW_FORM_udata, Sym);
295 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
296 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
300 /// addSectionDelta - Add a section label delta attribute data and value.
302 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
303 const MCSymbol *Hi, const MCSymbol *Lo) {
304 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
305 if (DD->getDwarfVersion() >= 4)
306 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
308 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
311 /// addDIEEntry - Add a DIE attribute data and value.
313 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
314 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
317 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
318 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
319 new (DIEValueAllocator) DIETypeSignature(Type));
322 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
324 const DIE *DieCU = Die->getUnitOrNull();
325 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
327 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
328 DieCU = getUnitDie();
330 EntryCU = getUnitDie();
331 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
332 : dwarf::DW_FORM_ref_addr,
336 /// Create a DIE with the given Tag, add the DIE to its parent, and
337 /// call insertDIE if MD is not null.
338 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
339 DIE *Die = new DIE(Tag);
340 Parent.addChild(Die);
346 /// addBlock - Add block data.
348 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
350 Block->ComputeSize(Asm);
351 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
352 Die->addValue(Attribute, Block->BestForm(), Block);
355 /// addSourceLine - Add location information to specified debug information
357 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
362 unsigned Line = V.getLineNumber();
366 DD->getOrCreateSourceID(V.getContext().getFilename(),
367 V.getContext().getDirectory(), getUniqueID());
368 assert(FileID && "Invalid file id");
369 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
370 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
373 /// addSourceLine - Add location information to specified debug information
375 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
376 // Verify global variable.
377 if (!G.isGlobalVariable())
380 unsigned Line = G.getLineNumber();
384 DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(), getUniqueID());
385 assert(FileID && "Invalid file id");
386 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
387 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
390 /// addSourceLine - Add location information to specified debug information
392 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
393 // Verify subprogram.
394 if (!SP.isSubprogram())
397 // If the line number is 0, don't add it.
398 unsigned Line = SP.getLineNumber();
402 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
404 assert(FileID && "Invalid file id");
405 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
406 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
409 /// addSourceLine - Add location information to specified debug information
411 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
416 unsigned Line = Ty.getLineNumber();
419 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.getDirectory(),
421 assert(FileID && "Invalid file id");
422 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
423 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
426 /// addSourceLine - Add location information to specified debug information
428 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
430 if (!Ty.isObjCProperty())
433 unsigned Line = Ty.getLineNumber();
436 DIFile File = Ty.getFile();
437 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
438 File.getDirectory(), getUniqueID());
439 assert(FileID && "Invalid file id");
440 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
441 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
444 /// addSourceLine - Add location information to specified debug information
446 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
451 unsigned Line = NS.getLineNumber();
454 StringRef FN = NS.getFilename();
457 DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
458 assert(FileID && "Invalid file id");
459 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
460 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
463 /// addVariableAddress - Add DW_AT_location attribute for a
464 /// DbgVariable based on provided MachineLocation.
465 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
466 MachineLocation Location) {
467 if (DV.variableHasComplexAddress())
468 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
469 else if (DV.isBlockByrefVariable())
470 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
472 addAddress(Die, dwarf::DW_AT_location, Location,
473 DV.getVariable().isIndirect());
476 /// addRegisterOp - Add register operand.
477 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
478 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
479 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
481 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
483 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
484 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
488 /// addRegisterOffset - Add register offset.
489 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
491 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
492 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
493 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
494 if (Reg == TRI->getFrameRegister(*Asm->MF))
495 // If variable offset is based in frame register then use fbreg.
496 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
498 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
500 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
501 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
503 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
506 /// addAddress - Add an address attribute to a die based on the location
508 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
509 const MachineLocation &Location, bool Indirect) {
510 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
512 if (Location.isReg() && !Indirect)
513 addRegisterOp(Block, Location.getReg());
515 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
516 if (Indirect && !Location.isReg()) {
517 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
521 // Now attach the location information to the DIE.
522 addBlock(Die, Attribute, Block);
525 /// addComplexAddress - Start with the address based on the location provided,
526 /// and generate the DWARF information necessary to find the actual variable
527 /// given the extra address information encoded in the DbgVariable, starting
528 /// from the starting location. Add the DWARF information to the die.
530 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
531 dwarf::Attribute Attribute,
532 const MachineLocation &Location) {
533 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
534 unsigned N = DV.getNumAddrElements();
536 if (Location.isReg()) {
537 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
538 // If first address element is OpPlus then emit
539 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
540 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
543 addRegisterOp(Block, Location.getReg());
545 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
548 uint64_t Element = DV.getAddrElement(i);
549 if (Element == DIBuilder::OpPlus) {
550 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
551 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
552 } else if (Element == DIBuilder::OpDeref) {
553 if (!Location.isReg())
554 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
556 llvm_unreachable("unknown DIBuilder Opcode");
559 // Now attach the location information to the DIE.
560 addBlock(Die, Attribute, Block);
563 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
564 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
565 gives the variable VarName either the struct, or a pointer to the struct, as
566 its type. This is necessary for various behind-the-scenes things the
567 compiler needs to do with by-reference variables in Blocks.
569 However, as far as the original *programmer* is concerned, the variable
570 should still have type 'SomeType', as originally declared.
572 The function getBlockByrefType dives into the __Block_byref_x_VarName
573 struct to find the original type of the variable, which is then assigned to
574 the variable's Debug Information Entry as its real type. So far, so good.
575 However now the debugger will expect the variable VarName to have the type
576 SomeType. So we need the location attribute for the variable to be an
577 expression that explains to the debugger how to navigate through the
578 pointers and struct to find the actual variable of type SomeType.
580 The following function does just that. We start by getting
581 the "normal" location for the variable. This will be the location
582 of either the struct __Block_byref_x_VarName or the pointer to the
583 struct __Block_byref_x_VarName.
585 The struct will look something like:
587 struct __Block_byref_x_VarName {
589 struct __Block_byref_x_VarName *forwarding;
590 ... <various other fields>
592 ... <maybe more fields>
595 If we are given the struct directly (as our starting point) we
596 need to tell the debugger to:
598 1). Add the offset of the forwarding field.
600 2). Follow that pointer to get the real __Block_byref_x_VarName
601 struct to use (the real one may have been copied onto the heap).
603 3). Add the offset for the field VarName, to find the actual variable.
605 If we started with a pointer to the struct, then we need to
606 dereference that pointer first, before the other steps.
607 Translating this into DWARF ops, we will need to append the following
608 to the current location description for the variable:
610 DW_OP_deref -- optional, if we start with a pointer
611 DW_OP_plus_uconst <forward_fld_offset>
613 DW_OP_plus_uconst <varName_fld_offset>
615 That is what this function does. */
617 /// addBlockByrefAddress - Start with the address based on the location
618 /// provided, and generate the DWARF information necessary to find the
619 /// actual Block variable (navigating the Block struct) based on the
620 /// starting location. Add the DWARF information to the die. For
621 /// more information, read large comment just above here.
623 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
624 dwarf::Attribute Attribute,
625 const MachineLocation &Location) {
626 DIType Ty = DV.getType();
628 uint16_t Tag = Ty.getTag();
629 bool isPointer = false;
631 StringRef varName = DV.getName();
633 if (Tag == dwarf::DW_TAG_pointer_type) {
634 DIDerivedType DTy(Ty);
635 TmpTy = resolve(DTy.getTypeDerivedFrom());
639 DICompositeType blockStruct(TmpTy);
641 // Find the __forwarding field and the variable field in the __Block_byref
643 DIArray Fields = blockStruct.getTypeArray();
644 DIDerivedType varField;
645 DIDerivedType forwardingField;
647 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
648 DIDerivedType DT(Fields.getElement(i));
649 StringRef fieldName = DT.getName();
650 if (fieldName == "__forwarding")
651 forwardingField = DT;
652 else if (fieldName == varName)
656 // Get the offsets for the forwarding field and the variable field.
657 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
658 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
660 // Decode the original location, and use that as the start of the byref
661 // variable's location.
662 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
664 if (Location.isReg())
665 addRegisterOp(Block, Location.getReg());
667 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
669 // If we started with a pointer to the __Block_byref... struct, then
670 // the first thing we need to do is dereference the pointer (DW_OP_deref).
672 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
674 // Next add the offset for the '__forwarding' field:
675 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
676 // adding the offset if it's 0.
677 if (forwardingFieldOffset > 0) {
678 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
679 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
682 // Now dereference the __forwarding field to get to the real __Block_byref
683 // struct: DW_OP_deref.
684 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
686 // Now that we've got the real __Block_byref... struct, add the offset
687 // for the variable's field to get to the location of the actual variable:
688 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
689 if (varFieldOffset > 0) {
690 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
691 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
694 // Now attach the location information to the DIE.
695 addBlock(Die, Attribute, Block);
698 /// isTypeSigned - Return true if the type is signed.
699 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
700 if (Ty.isDerivedType())
701 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
703 if (Ty.isBasicType())
704 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
705 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
706 *SizeInBits = Ty.getSizeInBits();
712 /// Return true if type encoding is unsigned.
713 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
714 DIDerivedType DTy(Ty);
715 if (DTy.isDerivedType())
716 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
719 if (BTy.isBasicType()) {
720 unsigned Encoding = BTy.getEncoding();
721 if (Encoding == dwarf::DW_ATE_unsigned ||
722 Encoding == dwarf::DW_ATE_unsigned_char ||
723 Encoding == dwarf::DW_ATE_boolean)
729 /// If this type is derived from a base type then return base type size.
730 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
731 unsigned Tag = Ty.getTag();
733 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
734 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
735 Tag != dwarf::DW_TAG_restrict_type)
736 return Ty.getSizeInBits();
738 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
740 // If this type is not derived from any type then take conservative approach.
741 if (!BaseType.isValid())
742 return Ty.getSizeInBits();
744 // If this is a derived type, go ahead and get the base type, unless it's a
745 // reference then it's just the size of the field. Pointer types have no need
746 // of this since they're a different type of qualification on the type.
747 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
748 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
749 return Ty.getSizeInBits();
751 if (BaseType.isDerivedType())
752 return getBaseTypeSize(DD, DIDerivedType(BaseType));
754 return BaseType.getSizeInBits();
757 /// addConstantValue - Add constant value entry in variable DIE.
758 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
760 // FIXME: This is a bit conservative/simple - it emits negative values at
761 // their maximum bit width which is a bit unfortunate (& doesn't prefer
762 // udata/sdata over dataN as suggested by the DWARF spec)
763 assert(MO.isImm() && "Invalid machine operand!");
765 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
768 // If we're a signed constant definitely use sdata.
769 if (SignedConstant) {
770 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
774 // Else use data for now unless it's larger than we can deal with.
775 switch (SizeInBits) {
777 Form = dwarf::DW_FORM_data1;
780 Form = dwarf::DW_FORM_data2;
783 Form = dwarf::DW_FORM_data4;
786 Form = dwarf::DW_FORM_data8;
789 Form = dwarf::DW_FORM_udata;
790 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
793 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
796 /// addConstantFPValue - Add constant value entry in variable DIE.
797 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
798 assert(MO.isFPImm() && "Invalid machine operand!");
799 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
800 APFloat FPImm = MO.getFPImm()->getValueAPF();
802 // Get the raw data form of the floating point.
803 const APInt FltVal = FPImm.bitcastToAPInt();
804 const char *FltPtr = (const char *)FltVal.getRawData();
806 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
807 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
808 int Incr = (LittleEndian ? 1 : -1);
809 int Start = (LittleEndian ? 0 : NumBytes - 1);
810 int Stop = (LittleEndian ? NumBytes : -1);
812 // Output the constant to DWARF one byte at a time.
813 for (; Start != Stop; Start += Incr)
814 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
816 addBlock(Die, dwarf::DW_AT_const_value, Block);
819 /// addConstantFPValue - Add constant value entry in variable DIE.
820 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
821 // Pass this down to addConstantValue as an unsigned bag of bits.
822 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
825 /// addConstantValue - Add constant value entry in variable DIE.
826 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
828 addConstantValue(Die, CI->getValue(), Unsigned);
831 // addConstantValue - Add constant value entry in variable DIE.
832 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
833 unsigned CIBitWidth = Val.getBitWidth();
834 if (CIBitWidth <= 64) {
835 // If we're a signed constant definitely use sdata.
837 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
842 // Else use data for now unless it's larger than we can deal with.
844 switch (CIBitWidth) {
846 Form = dwarf::DW_FORM_data1;
849 Form = dwarf::DW_FORM_data2;
852 Form = dwarf::DW_FORM_data4;
855 Form = dwarf::DW_FORM_data8;
858 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
862 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
866 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
868 // Get the raw data form of the large APInt.
869 const uint64_t *Ptr64 = Val.getRawData();
871 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
872 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
874 // Output the constant to DWARF one byte at a time.
875 for (int i = 0; i < NumBytes; i++) {
878 c = Ptr64[i / 8] >> (8 * (i & 7));
880 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
881 addUInt(Block, dwarf::DW_FORM_data1, c);
884 addBlock(Die, dwarf::DW_AT_const_value, Block);
887 /// addTemplateParams - Add template parameters into buffer.
888 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
889 // Add template parameters.
890 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
891 DIDescriptor Element = TParams.getElement(i);
892 if (Element.isTemplateTypeParameter())
893 constructTemplateTypeParameterDIE(Buffer,
894 DITemplateTypeParameter(Element));
895 else if (Element.isTemplateValueParameter())
896 constructTemplateValueParameterDIE(Buffer,
897 DITemplateValueParameter(Element));
901 /// getOrCreateContextDIE - Get context owner's DIE.
902 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
903 if (!Context || Context.isFile())
905 if (Context.isType())
906 return getOrCreateTypeDIE(DIType(Context));
907 if (Context.isNameSpace())
908 return getOrCreateNameSpace(DINameSpace(Context));
909 if (Context.isSubprogram())
910 return getOrCreateSubprogramDIE(DISubprogram(Context));
911 return getDIE(Context);
914 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
915 DIScope Context = resolve(Ty.getContext());
916 DIE *ContextDIE = getOrCreateContextDIE(Context);
918 DIE *TyDIE = getDIE(Ty);
923 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
925 constructTypeDIE(*TyDIE, Ty);
927 updateAcceleratorTables(Context, Ty, TyDIE);
931 /// Return true if the type is appropriately scoped to be contained inside
932 /// its own type unit.
933 static bool isDwarfTypeUnitScoped(DIType Ty, const DwarfDebug *DD) {
934 DIScope Parent = DD->resolve(Ty.getContext());
936 // Don't generate a hash for anything scoped inside a function.
937 if (Parent.isSubprogram())
939 Parent = DD->resolve(Parent.getContext());
944 /// Return true if the type should be split out into a type unit.
945 static bool shouldCreateDwarfTypeUnit(DICompositeType CTy,
946 const DwarfDebug *DD) {
947 if (!GenerateDwarfTypeUnits)
950 uint16_t Tag = CTy.getTag();
953 case dwarf::DW_TAG_structure_type:
954 case dwarf::DW_TAG_union_type:
955 case dwarf::DW_TAG_enumeration_type:
956 case dwarf::DW_TAG_class_type:
957 // If this is a class, structure, union, or enumeration type
958 // that is a definition (not a declaration), and not scoped
959 // inside a function then separate this out as a type unit.
960 return !CTy.isForwardDecl() && isDwarfTypeUnitScoped(CTy, DD);
966 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
968 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
975 // Construct the context before querying for the existence of the DIE in case
976 // such construction creates the DIE.
977 DIScope Context = resolve(Ty.getContext());
978 DIE *ContextDIE = getOrCreateContextDIE(Context);
981 DIE *TyDIE = getDIE(Ty);
986 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
988 if (Ty.isBasicType())
989 constructTypeDIE(*TyDIE, DIBasicType(Ty));
990 else if (Ty.isCompositeType()) {
991 DICompositeType CTy(Ty);
992 if (shouldCreateDwarfTypeUnit(CTy, DD)) {
993 DD->addDwarfTypeUnitType(getLanguage(), TyDIE, CTy);
994 // Skip updating the accellerator tables since this is not the full type
997 constructTypeDIE(*TyDIE, CTy);
999 assert(Ty.isDerivedType() && "Unknown kind of DIType");
1000 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
1003 updateAcceleratorTables(Context, Ty, TyDIE);
1008 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1010 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1011 bool IsImplementation = 0;
1012 if (Ty.isCompositeType()) {
1013 DICompositeType CT(Ty);
1014 // A runtime language of 0 actually means C/C++ and that any
1015 // non-negative value is some version of Objective-C/C++.
1016 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1018 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1019 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
1021 if (!Context || Context.isCompileUnit() || Context.isFile() ||
1022 Context.isNameSpace())
1023 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1027 /// addType - Add a new type attribute to the specified entity.
1028 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
1029 assert(Ty && "Trying to add a type that doesn't exist?");
1031 // Check for pre-existence.
1032 DIEEntry *Entry = getDIEEntry(Ty);
1033 // If it exists then use the existing value.
1035 addDIEEntry(Entity, Attribute, Entry);
1040 DIE *Buffer = getOrCreateTypeDIE(Ty);
1043 Entry = createDIEEntry(Buffer);
1044 insertDIEEntry(Ty, Entry);
1045 addDIEEntry(Entity, Attribute, Entry);
1048 // Accelerator table mutators - add each name along with its companion
1049 // DIE to the proper table while ensuring that the name that we're going
1050 // to reference is in the string table. We do this since the names we
1051 // add may not only be identical to the names in the DIE.
1052 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
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 DU->getStringPoolEntry(Name);
1060 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1061 DIEs.push_back(Die);
1064 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1065 DU->getStringPoolEntry(Name);
1066 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1067 DIEs.push_back(Die);
1070 void DwarfUnit::addAccelType(StringRef Name,
1071 std::pair<const DIE *, unsigned> Die) {
1072 DU->getStringPoolEntry(Name);
1073 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1074 DIEs.push_back(Die);
1077 /// addGlobalName - Add a new global name to the compile unit.
1078 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1079 std::string FullName = getParentContextString(Context) + Name.str();
1080 GlobalNames[FullName] = Die;
1083 /// getParentContextString - Walks the metadata parent chain in a language
1084 /// specific manner (using the compile unit language) and returns
1085 /// it as a string. This is done at the metadata level because DIEs may
1086 /// not currently have been added to the parent context and walking the
1087 /// DIEs looking for names is more expensive than walking the metadata.
1088 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1092 // FIXME: Decide whether to implement this for non-C++ languages.
1093 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1097 SmallVector<DIScope, 1> Parents;
1098 while (!Context.isCompileUnit()) {
1099 Parents.push_back(Context);
1100 if (Context.getContext())
1101 Context = resolve(Context.getContext());
1103 // Structure, etc types will have a NULL context if they're at the top
1108 // Reverse iterate over our list to go from the outermost construct to the
1110 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1114 StringRef Name = Ctx.getName();
1115 if (!Name.empty()) {
1123 /// constructTypeDIE - Construct basic type die from DIBasicType.
1124 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1125 // Get core information.
1126 StringRef Name = BTy.getName();
1127 // Add name if not anonymous or intermediate type.
1129 addString(&Buffer, dwarf::DW_AT_name, Name);
1131 // An unspecified type only has a name attribute.
1132 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1135 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1138 uint64_t Size = BTy.getSizeInBits() >> 3;
1139 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1142 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1143 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1144 // Get core information.
1145 StringRef Name = DTy.getName();
1146 uint64_t Size = DTy.getSizeInBits() >> 3;
1147 uint16_t Tag = Buffer.getTag();
1149 // Map to main type, void will not have a type.
1150 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1152 addType(&Buffer, FromTy);
1154 // Add name if not anonymous or intermediate type.
1156 addString(&Buffer, dwarf::DW_AT_name, Name);
1158 // Add size if non-zero (derived types might be zero-sized.)
1159 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1160 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1162 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1163 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1164 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1165 // Add source line info if available and TyDesc is not a forward declaration.
1166 if (!DTy.isForwardDecl())
1167 addSourceLine(&Buffer, DTy);
1170 /// constructTypeDIE - Construct type DIE from DICompositeType.
1171 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1172 // Add name if not anonymous or intermediate type.
1173 StringRef Name = CTy.getName();
1175 uint64_t Size = CTy.getSizeInBits() >> 3;
1176 uint16_t Tag = Buffer.getTag();
1179 case dwarf::DW_TAG_array_type:
1180 constructArrayTypeDIE(Buffer, CTy);
1182 case dwarf::DW_TAG_enumeration_type:
1183 constructEnumTypeDIE(Buffer, CTy);
1185 case dwarf::DW_TAG_subroutine_type: {
1186 // Add return type. A void return won't have a type.
1187 DIArray Elements = CTy.getTypeArray();
1188 DIType RTy(Elements.getElement(0));
1190 addType(&Buffer, RTy);
1192 bool isPrototyped = true;
1194 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1195 DIDescriptor Ty = Elements.getElement(i);
1196 if (Ty.isUnspecifiedParameter()) {
1197 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1198 isPrototyped = false;
1200 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1201 addType(Arg, DIType(Ty));
1202 if (DIType(Ty).isArtificial())
1203 addFlag(Arg, dwarf::DW_AT_artificial);
1206 // Add prototype flag if we're dealing with a C language and the
1207 // function has been prototyped.
1208 uint16_t Language = getLanguage();
1210 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1211 Language == dwarf::DW_LANG_ObjC))
1212 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1214 if (CTy.isLValueReference())
1215 addFlag(&Buffer, dwarf::DW_AT_reference);
1217 if (CTy.isRValueReference())
1218 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1220 case dwarf::DW_TAG_structure_type:
1221 case dwarf::DW_TAG_union_type:
1222 case dwarf::DW_TAG_class_type: {
1223 // Add elements to structure type.
1224 DIArray Elements = CTy.getTypeArray();
1225 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1226 DIDescriptor Element = Elements.getElement(i);
1227 DIE *ElemDie = NULL;
1228 if (Element.isSubprogram()) {
1229 DISubprogram SP(Element);
1230 ElemDie = getOrCreateSubprogramDIE(SP);
1231 if (SP.isProtected())
1232 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1233 dwarf::DW_ACCESS_protected);
1234 else if (SP.isPrivate())
1235 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1236 dwarf::DW_ACCESS_private);
1238 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1239 dwarf::DW_ACCESS_public);
1240 if (SP.isExplicit())
1241 addFlag(ElemDie, dwarf::DW_AT_explicit);
1242 } else if (Element.isDerivedType()) {
1243 DIDerivedType DDTy(Element);
1244 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1245 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1246 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1247 dwarf::DW_AT_friend);
1248 } else if (DDTy.isStaticMember()) {
1249 getOrCreateStaticMemberDIE(DDTy);
1251 constructMemberDIE(Buffer, DDTy);
1253 } else if (Element.isObjCProperty()) {
1254 DIObjCProperty Property(Element);
1255 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1256 StringRef PropertyName = Property.getObjCPropertyName();
1257 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1258 addType(ElemDie, Property.getType());
1259 addSourceLine(ElemDie, Property);
1260 StringRef GetterName = Property.getObjCPropertyGetterName();
1261 if (!GetterName.empty())
1262 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1263 StringRef SetterName = Property.getObjCPropertySetterName();
1264 if (!SetterName.empty())
1265 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1266 unsigned PropertyAttributes = 0;
1267 if (Property.isReadOnlyObjCProperty())
1268 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1269 if (Property.isReadWriteObjCProperty())
1270 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1271 if (Property.isAssignObjCProperty())
1272 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1273 if (Property.isRetainObjCProperty())
1274 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1275 if (Property.isCopyObjCProperty())
1276 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1277 if (Property.isNonAtomicObjCProperty())
1278 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1279 if (PropertyAttributes)
1280 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1281 PropertyAttributes);
1283 DIEEntry *Entry = getDIEEntry(Element);
1285 Entry = createDIEEntry(ElemDie);
1286 insertDIEEntry(Element, Entry);
1292 if (CTy.isAppleBlockExtension())
1293 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1295 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1297 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1298 getOrCreateTypeDIE(ContainingType));
1300 if (CTy.isObjcClassComplete())
1301 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1303 // Add template parameters to a class, structure or union types.
1304 // FIXME: The support isn't in the metadata for this yet.
1305 if (Tag == dwarf::DW_TAG_class_type ||
1306 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1307 addTemplateParams(Buffer, CTy.getTemplateParams());
1315 // Add name if not anonymous or intermediate type.
1317 addString(&Buffer, dwarf::DW_AT_name, Name);
1319 if (Tag == dwarf::DW_TAG_enumeration_type ||
1320 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1321 Tag == dwarf::DW_TAG_union_type) {
1322 // Add size if non-zero (derived types might be zero-sized.)
1323 // TODO: Do we care about size for enum forward declarations?
1325 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1326 else if (!CTy.isForwardDecl())
1327 // Add zero size if it is not a forward declaration.
1328 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1330 // If we're a forward decl, say so.
1331 if (CTy.isForwardDecl())
1332 addFlag(&Buffer, dwarf::DW_AT_declaration);
1334 // Add source line info if available.
1335 if (!CTy.isForwardDecl())
1336 addSourceLine(&Buffer, CTy);
1338 // No harm in adding the runtime language to the declaration.
1339 unsigned RLang = CTy.getRunTimeLang();
1341 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1346 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1347 /// DITemplateTypeParameter.
1348 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1349 DITemplateTypeParameter TP) {
1351 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1352 // Add the type if it exists, it could be void and therefore no type.
1354 addType(ParamDIE, resolve(TP.getType()));
1355 if (!TP.getName().empty())
1356 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1359 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1360 /// DITemplateValueParameter.
1362 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1363 DITemplateValueParameter VP) {
1364 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1366 // Add the type if there is one, template template and template parameter
1367 // packs will not have a type.
1368 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1369 addType(ParamDIE, resolve(VP.getType()));
1370 if (!VP.getName().empty())
1371 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1372 if (Value *Val = VP.getValue()) {
1373 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1374 addConstantValue(ParamDIE, CI,
1375 isUnsignedDIType(DD, resolve(VP.getType())));
1376 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1377 // For declaration non-type template parameters (such as global values and
1379 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1380 addOpAddress(Block, Asm->getSymbol(GV));
1381 // Emit DW_OP_stack_value to use the address as the immediate value of the
1382 // parameter, rather than a pointer to it.
1383 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1384 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1385 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1386 assert(isa<MDString>(Val));
1387 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1388 cast<MDString>(Val)->getString());
1389 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1390 assert(isa<MDNode>(Val));
1391 DIArray A(cast<MDNode>(Val));
1392 addTemplateParams(*ParamDIE, A);
1397 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1398 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1399 // Construct the context before querying for the existence of the DIE in case
1400 // such construction creates the DIE.
1401 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1403 DIE *NDie = getDIE(NS);
1406 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1408 if (!NS.getName().empty()) {
1409 addString(NDie, dwarf::DW_AT_name, NS.getName());
1410 addAccelNamespace(NS.getName(), NDie);
1411 addGlobalName(NS.getName(), NDie, NS.getContext());
1413 addAccelNamespace("(anonymous namespace)", NDie);
1414 addSourceLine(NDie, NS);
1418 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1419 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1420 // Construct the context before querying for the existence of the DIE in case
1421 // such construction creates the DIE (as is the case for member function
1423 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1425 DIE *SPDie = getDIE(SP);
1429 DISubprogram SPDecl = SP.getFunctionDeclaration();
1430 if (SPDecl.isSubprogram())
1431 // Add subprogram definitions to the CU die directly.
1432 ContextDIE = UnitDie.get();
1434 // DW_TAG_inlined_subroutine may refer to this DIE.
1435 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1437 DIE *DeclDie = NULL;
1438 if (SPDecl.isSubprogram())
1439 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1441 // Add function template parameters.
1442 addTemplateParams(*SPDie, SP.getTemplateParams());
1444 // If this DIE is going to refer declaration info using AT_specification
1445 // then there is no need to add other attributes.
1447 // Refer function declaration directly.
1448 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1453 // Add the linkage name if we have one.
1454 StringRef LinkageName = SP.getLinkageName();
1455 if (!LinkageName.empty())
1456 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1457 GlobalValue::getRealLinkageName(LinkageName));
1459 // Constructors and operators for anonymous aggregates do not have names.
1460 if (!SP.getName().empty())
1461 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1463 addSourceLine(SPDie, SP);
1465 // Add the prototype if we have a prototype and we have a C like
1467 uint16_t Language = getLanguage();
1468 if (SP.isPrototyped() &&
1469 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1470 Language == dwarf::DW_LANG_ObjC))
1471 addFlag(SPDie, dwarf::DW_AT_prototyped);
1473 DICompositeType SPTy = SP.getType();
1474 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1475 "the type of a subprogram should be a subroutine");
1477 DIArray Args = SPTy.getTypeArray();
1478 // Add a return type. If this is a type like a C/C++ void type we don't add a
1480 if (Args.getElement(0))
1481 addType(SPDie, DIType(Args.getElement(0)));
1483 unsigned VK = SP.getVirtuality();
1485 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1486 DIEBlock *Block = getDIEBlock();
1487 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1488 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1489 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1490 ContainingTypeMap.insert(
1491 std::make_pair(SPDie, resolve(SP.getContainingType())));
1494 if (!SP.isDefinition()) {
1495 addFlag(SPDie, dwarf::DW_AT_declaration);
1497 // Add arguments. Do not add arguments for subprogram definition. They will
1498 // be handled while processing variables.
1499 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1500 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1501 DIType ATy(Args.getElement(i));
1503 if (ATy.isArtificial())
1504 addFlag(Arg, dwarf::DW_AT_artificial);
1508 if (SP.isArtificial())
1509 addFlag(SPDie, dwarf::DW_AT_artificial);
1511 if (!SP.isLocalToUnit())
1512 addFlag(SPDie, dwarf::DW_AT_external);
1514 if (SP.isOptimized())
1515 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1517 if (unsigned isa = Asm->getISAEncoding()) {
1518 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1521 if (SP.isLValueReference())
1522 addFlag(SPDie, dwarf::DW_AT_reference);
1524 if (SP.isRValueReference())
1525 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1530 // Return const expression if value is a GEP to access merged global
1532 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1533 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1534 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1535 if (!CE || CE->getNumOperands() != 3 ||
1536 CE->getOpcode() != Instruction::GetElementPtr)
1539 // First operand points to a global struct.
1540 Value *Ptr = CE->getOperand(0);
1541 if (!isa<GlobalValue>(Ptr) ||
1542 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1545 // Second operand is zero.
1546 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1547 if (!CI || !CI->isZero())
1550 // Third operand is offset.
1551 if (!isa<ConstantInt>(CE->getOperand(2)))
1557 /// createGlobalVariableDIE - create global variable DIE.
1558 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1559 // Check for pre-existence.
1563 if (!GV.isGlobalVariable())
1566 DIScope GVContext = GV.getContext();
1567 DIType GTy = GV.getType();
1569 // If this is a static data member definition, some attributes belong
1570 // to the declaration DIE.
1571 DIE *VariableDIE = NULL;
1572 bool IsStaticMember = false;
1573 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1574 if (SDMDecl.Verify()) {
1575 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1576 // We need the declaration DIE that is in the static member's class.
1577 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1578 IsStaticMember = true;
1581 // If this is not a static data member definition, create the variable
1582 // DIE and add the initial set of attributes to it.
1584 // Construct the context before querying for the existence of the DIE in
1585 // case such construction creates the DIE.
1586 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1589 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1591 // Add name and type.
1592 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1593 addType(VariableDIE, GTy);
1595 // Add scoping info.
1596 if (!GV.isLocalToUnit())
1597 addFlag(VariableDIE, dwarf::DW_AT_external);
1599 // Add line number info.
1600 addSourceLine(VariableDIE, GV);
1604 bool addToAccelTable = false;
1605 DIE *VariableSpecDIE = NULL;
1606 bool isGlobalVariable = GV.getGlobal() != NULL;
1607 if (isGlobalVariable) {
1608 addToAccelTable = true;
1609 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1610 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1611 if (GV.getGlobal()->isThreadLocal()) {
1612 // FIXME: Make this work with -gsplit-dwarf.
1613 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1614 assert((PointerSize == 4 || PointerSize == 8) &&
1615 "Add support for other sizes if necessary");
1616 const MCExpr *Expr =
1617 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1618 // Based on GCC's support for TLS:
1619 if (!DD->useSplitDwarf()) {
1620 // 1) Start with a constNu of the appropriate pointer size
1621 addUInt(Block, dwarf::DW_FORM_data1,
1622 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1623 // 2) containing the (relocated) offset of the TLS variable
1624 // within the module's TLS block.
1625 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1627 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1628 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1630 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1631 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1633 DD->addArangeLabel(SymbolCU(this, Sym));
1634 addOpAddress(Block, Sym);
1636 // Do not create specification DIE if context is either compile unit
1638 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1639 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1640 // Create specification DIE.
1641 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1642 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1643 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1644 // A static member's declaration is already flagged as such.
1645 if (!SDMDecl.Verify())
1646 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1648 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1650 // Add the linkage name.
1651 StringRef LinkageName = GV.getLinkageName();
1652 if (!LinkageName.empty())
1653 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1654 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1656 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1658 dwarf::DW_AT_MIPS_linkage_name,
1659 GlobalValue::getRealLinkageName(LinkageName));
1660 } else if (const ConstantInt *CI =
1661 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1662 // AT_const_value was added when the static member was created. To avoid
1663 // emitting AT_const_value multiple times, we only add AT_const_value when
1664 // it is not a static member.
1665 if (!IsStaticMember)
1666 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1667 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1668 addToAccelTable = true;
1669 // GV is a merged global.
1670 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1671 Value *Ptr = CE->getOperand(0);
1672 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1673 DD->addArangeLabel(SymbolCU(this, Sym));
1674 addOpAddress(Block, Sym);
1675 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1676 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1677 addUInt(Block, dwarf::DW_FORM_udata,
1678 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1679 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1680 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1683 if (addToAccelTable) {
1684 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1685 addAccelName(GV.getName(), AddrDIE);
1687 // If the linkage name is different than the name, go ahead and output
1688 // that as well into the name table.
1689 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1690 addAccelName(GV.getLinkageName(), AddrDIE);
1693 if (!GV.isLocalToUnit())
1694 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1698 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1699 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1700 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1701 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1703 // The LowerBound value defines the lower bounds which is typically zero for
1704 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1705 // Count == -1 then the array is unbounded and we do not emit
1706 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1707 // Count == 0, then the array has zero elements in which case we do not emit
1709 int64_t LowerBound = SR.getLo();
1710 int64_t DefaultLowerBound = getDefaultLowerBound();
1711 int64_t Count = SR.getCount();
1713 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1714 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1716 if (Count != -1 && Count != 0)
1717 // FIXME: An unbounded array should reference the expression that defines
1719 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1720 LowerBound + Count - 1);
1723 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1724 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1726 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1728 // Emit the element type.
1729 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1731 // Get an anonymous type for index type.
1732 // FIXME: This type should be passed down from the front end
1733 // as different languages may have different sizes for indexes.
1734 DIE *IdxTy = getIndexTyDie();
1736 // Construct an anonymous type for index type.
1737 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1738 addString(IdxTy, dwarf::DW_AT_name, "int");
1739 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1740 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1741 dwarf::DW_ATE_signed);
1742 setIndexTyDie(IdxTy);
1745 // Add subranges to array type.
1746 DIArray Elements = CTy.getTypeArray();
1747 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1748 DIDescriptor Element = Elements.getElement(i);
1749 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1750 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1754 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1755 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1756 DIArray Elements = CTy.getTypeArray();
1758 // Add enumerators to enumeration type.
1759 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1760 DIEnumerator Enum(Elements.getElement(i));
1761 if (Enum.isEnumerator()) {
1762 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1763 StringRef Name = Enum.getName();
1764 addString(Enumerator, dwarf::DW_AT_name, Name);
1765 int64_t Value = Enum.getEnumValue();
1766 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1769 // Add the enumerator to the __apple_names accelerator table.
1770 addAccelName(Name, Enumerator);
1773 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1775 addType(&Buffer, DTy);
1776 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1780 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1782 void DwarfUnit::constructContainingTypeDIEs() {
1783 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1784 CE = ContainingTypeMap.end();
1786 DIE *SPDie = CI->first;
1787 DIDescriptor D(CI->second);
1790 DIE *NDie = getDIE(D);
1793 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1797 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1798 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1799 StringRef Name = DV.getName();
1801 // Define variable debug information entry.
1802 DIE *VariableDie = new DIE(DV.getTag());
1803 DbgVariable *AbsVar = DV.getAbstractVariable();
1804 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1806 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1809 addString(VariableDie, dwarf::DW_AT_name, Name);
1810 addSourceLine(VariableDie, DV.getVariable());
1811 addType(VariableDie, DV.getType());
1814 if (DV.isArtificial())
1815 addFlag(VariableDie, dwarf::DW_AT_artificial);
1817 if (isScopeAbstract) {
1818 DV.setDIE(VariableDie);
1822 // Add variable address.
1824 unsigned Offset = DV.getDotDebugLocOffset();
1825 if (Offset != ~0U) {
1826 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1827 Asm->GetTempSymbol("debug_loc", Offset));
1828 DV.setDIE(VariableDie);
1832 // Check if variable is described by a DBG_VALUE instruction.
1833 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1834 assert(DVInsn->getNumOperands() == 3);
1835 if (DVInsn->getOperand(0).isReg()) {
1836 const MachineOperand RegOp = DVInsn->getOperand(0);
1837 // If the second operand is an immediate, this is an indirect value.
1838 if (DVInsn->getOperand(1).isImm()) {
1839 MachineLocation Location(RegOp.getReg(),
1840 DVInsn->getOperand(1).getImm());
1841 addVariableAddress(DV, VariableDie, Location);
1842 } else if (RegOp.getReg())
1843 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1844 } else if (DVInsn->getOperand(0).isImm())
1845 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1846 else if (DVInsn->getOperand(0).isFPImm())
1847 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1848 else if (DVInsn->getOperand(0).isCImm())
1849 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1850 isUnsignedDIType(DD, DV.getType()));
1852 DV.setDIE(VariableDie);
1855 // .. else use frame index.
1856 int FI = DV.getFrameIndex();
1858 unsigned FrameReg = 0;
1859 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1860 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1861 MachineLocation Location(FrameReg, Offset);
1862 addVariableAddress(DV, VariableDie, Location);
1866 DV.setDIE(VariableDie);
1870 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1871 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1872 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1873 StringRef Name = DT.getName();
1875 addString(MemberDie, dwarf::DW_AT_name, Name);
1877 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1879 addSourceLine(MemberDie, DT);
1881 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1882 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1884 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1886 // For C++, virtual base classes are not at fixed offset. Use following
1887 // expression to extract appropriate offset from vtable.
1888 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1890 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1891 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1892 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1893 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1894 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1895 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1896 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1897 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1899 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1901 uint64_t Size = DT.getSizeInBits();
1902 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1903 uint64_t OffsetInBytes;
1905 if (Size != FieldSize) {
1907 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1908 getBaseTypeSize(DD, DT) >> 3);
1909 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1911 uint64_t Offset = DT.getOffsetInBits();
1912 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1913 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1914 uint64_t FieldOffset = (HiMark - FieldSize);
1915 Offset -= FieldOffset;
1917 // Maybe we need to work from the other end.
1918 if (Asm->getDataLayout().isLittleEndian())
1919 Offset = FieldSize - (Offset + Size);
1920 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1922 // Here WD_AT_data_member_location points to the anonymous
1923 // field that includes this bit field.
1924 OffsetInBytes = FieldOffset >> 3;
1926 // This is not a bitfield.
1927 OffsetInBytes = DT.getOffsetInBits() >> 3;
1928 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None, OffsetInBytes);
1931 if (DT.isProtected())
1932 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1933 dwarf::DW_ACCESS_protected);
1934 else if (DT.isPrivate())
1935 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1936 dwarf::DW_ACCESS_private);
1937 // Otherwise C++ member and base classes are considered public.
1939 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1940 dwarf::DW_ACCESS_public);
1942 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1943 dwarf::DW_VIRTUALITY_virtual);
1945 // Objective-C properties.
1946 if (MDNode *PNode = DT.getObjCProperty())
1947 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1948 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1951 if (DT.isArtificial())
1952 addFlag(MemberDie, dwarf::DW_AT_artificial);
1955 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1956 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1960 // Construct the context before querying for the existence of the DIE in case
1961 // such construction creates the DIE.
1962 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1963 assert(dwarf::isType(ContextDIE->getTag()) &&
1964 "Static member should belong to a type.");
1966 DIE *StaticMemberDIE = getDIE(DT);
1967 if (StaticMemberDIE)
1968 return StaticMemberDIE;
1970 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1972 DIType Ty = resolve(DT.getTypeDerivedFrom());
1974 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1975 addType(StaticMemberDIE, Ty);
1976 addSourceLine(StaticMemberDIE, DT);
1977 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1978 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1980 // FIXME: We could omit private if the parent is a class_type, and
1981 // public if the parent is something else.
1982 if (DT.isProtected())
1983 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1984 dwarf::DW_ACCESS_protected);
1985 else if (DT.isPrivate())
1986 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1987 dwarf::DW_ACCESS_private);
1989 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1990 dwarf::DW_ACCESS_public);
1992 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1993 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1994 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1995 addConstantFPValue(StaticMemberDIE, CFP);
1997 return StaticMemberDIE;
2000 void DwarfUnit::emitHeader(const MCSection *ASection,
2001 const MCSymbol *ASectionSym) const {
2002 Asm->OutStreamer.AddComment("DWARF version number");
2003 Asm->EmitInt16(DD->getDwarfVersion());
2004 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2005 // We share one abbreviations table across all units so it's always at the
2006 // start of the section. Use a relocatable offset where needed to ensure
2007 // linking doesn't invalidate that offset.
2008 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2009 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2010 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2013 DwarfCompileUnit::~DwarfCompileUnit() {}
2014 DwarfTypeUnit::~DwarfTypeUnit() {}
2016 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
2017 const MCSymbol *ASectionSym) const {
2018 DwarfUnit::emitHeader(ASection, ASectionSym);
2019 Asm->OutStreamer.AddComment("Type Signature");
2020 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2021 Asm->OutStreamer.AddComment("Type DIE Offset");
2022 Asm->OutStreamer.EmitIntValue(Ty->getOffset(), sizeof(Ty->getOffset()));
2025 void DwarfTypeUnit::initSection(const MCSection *Section) {
2026 assert(!this->Section);
2027 this->Section = Section;
2028 // Since each type unit is contained in its own COMDAT section, the begin
2029 // label and the section label are the same. Using the begin label emission in
2030 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2031 // the only other alternative of lazily constructing start-of-section labels
2032 // and storing a mapping in DwarfDebug (or AsmPrinter).
2033 this->SectionSym = this->LabelBegin =
2034 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2036 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2037 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());