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/MCSection.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Target/TargetFrameLowering.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetRegisterInfo.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), CUNode(Node), UnitDie(D), DebugInfoOffset(0), Asm(A),
46 DD(DW), 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, DICompileUnit CUNode,
58 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
59 : DwarfUnit(UID, D, CUNode, A, DW, DWU) {}
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,
269 if (!DD->useSplitDwarf())
270 return addLocalLabelAddress(Die, Attribute, Label);
273 DD->addArangeLabel(SymbolCU(this, Label));
275 unsigned idx = DU->getAddrPoolIndex(Label);
276 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
277 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
280 /// addLocalLabelAddress - Add a dwarf label attribute data and value using
281 /// DW_FORM_addr only.
283 void DwarfCompileUnit::addLocalLabelAddress(DIE *Die,
284 dwarf::Attribute Attribute,
287 DD->addArangeLabel(SymbolCU(this, Label));
290 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
291 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
293 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
294 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
298 /// addOpAddress - Add a dwarf op address data and value using the
299 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
301 void DwarfUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
302 if (!DD->useSplitDwarf()) {
303 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
304 addLabel(Die, dwarf::DW_FORM_udata, Sym);
306 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
307 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
311 /// addSectionDelta - Add a section label delta attribute data and value.
313 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
314 const MCSymbol *Hi, const MCSymbol *Lo) {
315 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
316 if (DD->getDwarfVersion() >= 4)
317 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
319 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
322 /// addDIEEntry - Add a DIE attribute data and value.
324 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
325 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
328 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
329 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
330 new (DIEValueAllocator) DIETypeSignature(Type));
333 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
335 const DIE *DieCU = Die->getUnitOrNull();
336 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
338 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
339 DieCU = getUnitDie();
341 EntryCU = getUnitDie();
342 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
343 : dwarf::DW_FORM_ref_addr,
347 /// Create a DIE with the given Tag, add the DIE to its parent, and
348 /// call insertDIE if MD is not null.
349 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
350 DIE *Die = new DIE(Tag);
351 Parent.addChild(Die);
357 /// addBlock - Add block data.
359 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
361 Block->ComputeSize(Asm);
362 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
363 Die->addValue(Attribute, Block->BestForm(), Block);
366 /// addSourceLine - Add location information to specified debug information
368 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
373 unsigned Line = V.getLineNumber();
377 DD->getOrCreateSourceID(V.getContext().getFilename(),
378 V.getContext().getDirectory(), getUniqueID());
379 assert(FileID && "Invalid file id");
380 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
381 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
384 /// addSourceLine - Add location information to specified debug information
386 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
387 // Verify global variable.
388 if (!G.isGlobalVariable())
391 unsigned Line = G.getLineNumber();
395 DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(), getUniqueID());
396 assert(FileID && "Invalid file id");
397 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
398 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
401 /// addSourceLine - Add location information to specified debug information
403 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
404 // Verify subprogram.
405 if (!SP.isSubprogram())
408 // If the line number is 0, don't add it.
409 unsigned Line = SP.getLineNumber();
413 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
415 assert(FileID && "Invalid file id");
416 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
417 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
420 /// addSourceLine - Add location information to specified debug information
422 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
427 unsigned Line = Ty.getLineNumber();
430 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.getDirectory(),
432 assert(FileID && "Invalid file id");
433 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
434 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
437 /// addSourceLine - Add location information to specified debug information
439 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
441 if (!Ty.isObjCProperty())
444 unsigned Line = Ty.getLineNumber();
447 DIFile File = Ty.getFile();
448 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
449 File.getDirectory(), getUniqueID());
450 assert(FileID && "Invalid file id");
451 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
452 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
455 /// addSourceLine - Add location information to specified debug information
457 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
462 unsigned Line = NS.getLineNumber();
465 StringRef FN = NS.getFilename();
468 DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
469 assert(FileID && "Invalid file id");
470 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
471 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
474 /// addVariableAddress - Add DW_AT_location attribute for a
475 /// DbgVariable based on provided MachineLocation.
476 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
477 MachineLocation Location) {
478 if (DV.variableHasComplexAddress())
479 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
480 else if (DV.isBlockByrefVariable())
481 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
483 addAddress(Die, dwarf::DW_AT_location, Location,
484 DV.getVariable().isIndirect());
487 /// addRegisterOp - Add register operand.
488 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
489 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
490 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
492 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
494 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
495 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
499 /// addRegisterOffset - Add register offset.
500 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
502 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
503 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
504 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
505 if (Reg == TRI->getFrameRegister(*Asm->MF))
506 // If variable offset is based in frame register then use fbreg.
507 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
509 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
511 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
512 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
514 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
517 /// addAddress - Add an address attribute to a die based on the location
519 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
520 const MachineLocation &Location, bool Indirect) {
521 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
523 if (Location.isReg() && !Indirect)
524 addRegisterOp(Block, Location.getReg());
526 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
527 if (Indirect && !Location.isReg()) {
528 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
532 // Now attach the location information to the DIE.
533 addBlock(Die, Attribute, Block);
536 /// addComplexAddress - Start with the address based on the location provided,
537 /// and generate the DWARF information necessary to find the actual variable
538 /// given the extra address information encoded in the DbgVariable, starting
539 /// from the starting location. Add the DWARF information to the die.
541 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
542 dwarf::Attribute Attribute,
543 const MachineLocation &Location) {
544 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
545 unsigned N = DV.getNumAddrElements();
547 if (Location.isReg()) {
548 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
549 // If first address element is OpPlus then emit
550 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
551 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
554 addRegisterOp(Block, Location.getReg());
556 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
559 uint64_t Element = DV.getAddrElement(i);
560 if (Element == DIBuilder::OpPlus) {
561 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
562 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
563 } else if (Element == DIBuilder::OpDeref) {
564 if (!Location.isReg())
565 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
567 llvm_unreachable("unknown DIBuilder Opcode");
570 // Now attach the location information to the DIE.
571 addBlock(Die, Attribute, Block);
574 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
575 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
576 gives the variable VarName either the struct, or a pointer to the struct, as
577 its type. This is necessary for various behind-the-scenes things the
578 compiler needs to do with by-reference variables in Blocks.
580 However, as far as the original *programmer* is concerned, the variable
581 should still have type 'SomeType', as originally declared.
583 The function getBlockByrefType dives into the __Block_byref_x_VarName
584 struct to find the original type of the variable, which is then assigned to
585 the variable's Debug Information Entry as its real type. So far, so good.
586 However now the debugger will expect the variable VarName to have the type
587 SomeType. So we need the location attribute for the variable to be an
588 expression that explains to the debugger how to navigate through the
589 pointers and struct to find the actual variable of type SomeType.
591 The following function does just that. We start by getting
592 the "normal" location for the variable. This will be the location
593 of either the struct __Block_byref_x_VarName or the pointer to the
594 struct __Block_byref_x_VarName.
596 The struct will look something like:
598 struct __Block_byref_x_VarName {
600 struct __Block_byref_x_VarName *forwarding;
601 ... <various other fields>
603 ... <maybe more fields>
606 If we are given the struct directly (as our starting point) we
607 need to tell the debugger to:
609 1). Add the offset of the forwarding field.
611 2). Follow that pointer to get the real __Block_byref_x_VarName
612 struct to use (the real one may have been copied onto the heap).
614 3). Add the offset for the field VarName, to find the actual variable.
616 If we started with a pointer to the struct, then we need to
617 dereference that pointer first, before the other steps.
618 Translating this into DWARF ops, we will need to append the following
619 to the current location description for the variable:
621 DW_OP_deref -- optional, if we start with a pointer
622 DW_OP_plus_uconst <forward_fld_offset>
624 DW_OP_plus_uconst <varName_fld_offset>
626 That is what this function does. */
628 /// addBlockByrefAddress - Start with the address based on the location
629 /// provided, and generate the DWARF information necessary to find the
630 /// actual Block variable (navigating the Block struct) based on the
631 /// starting location. Add the DWARF information to the die. For
632 /// more information, read large comment just above here.
634 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
635 dwarf::Attribute Attribute,
636 const MachineLocation &Location) {
637 DIType Ty = DV.getType();
639 uint16_t Tag = Ty.getTag();
640 bool isPointer = false;
642 StringRef varName = DV.getName();
644 if (Tag == dwarf::DW_TAG_pointer_type) {
645 DIDerivedType DTy(Ty);
646 TmpTy = resolve(DTy.getTypeDerivedFrom());
650 DICompositeType blockStruct(TmpTy);
652 // Find the __forwarding field and the variable field in the __Block_byref
654 DIArray Fields = blockStruct.getTypeArray();
655 DIDerivedType varField;
656 DIDerivedType forwardingField;
658 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
659 DIDerivedType DT(Fields.getElement(i));
660 StringRef fieldName = DT.getName();
661 if (fieldName == "__forwarding")
662 forwardingField = DT;
663 else if (fieldName == varName)
667 // Get the offsets for the forwarding field and the variable field.
668 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
669 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
671 // Decode the original location, and use that as the start of the byref
672 // variable's location.
673 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
675 if (Location.isReg())
676 addRegisterOp(Block, Location.getReg());
678 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
680 // If we started with a pointer to the __Block_byref... struct, then
681 // the first thing we need to do is dereference the pointer (DW_OP_deref).
683 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
685 // Next add the offset for the '__forwarding' field:
686 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
687 // adding the offset if it's 0.
688 if (forwardingFieldOffset > 0) {
689 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
690 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
693 // Now dereference the __forwarding field to get to the real __Block_byref
694 // struct: DW_OP_deref.
695 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
697 // Now that we've got the real __Block_byref... struct, add the offset
698 // for the variable's field to get to the location of the actual variable:
699 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
700 if (varFieldOffset > 0) {
701 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
702 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
705 // Now attach the location information to the DIE.
706 addBlock(Die, Attribute, Block);
709 /// isTypeSigned - Return true if the type is signed.
710 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
711 if (Ty.isDerivedType())
712 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
714 if (Ty.isBasicType())
715 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
716 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
717 *SizeInBits = Ty.getSizeInBits();
723 /// Return true if type encoding is unsigned.
724 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
725 DIDerivedType DTy(Ty);
726 if (DTy.isDerivedType())
727 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
730 if (BTy.isBasicType()) {
731 unsigned Encoding = BTy.getEncoding();
732 if (Encoding == dwarf::DW_ATE_unsigned ||
733 Encoding == dwarf::DW_ATE_unsigned_char ||
734 Encoding == dwarf::DW_ATE_boolean)
740 /// If this type is derived from a base type then return base type size.
741 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
742 unsigned Tag = Ty.getTag();
744 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
745 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
746 Tag != dwarf::DW_TAG_restrict_type)
747 return Ty.getSizeInBits();
749 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
751 // If this type is not derived from any type then take conservative approach.
752 if (!BaseType.isValid())
753 return Ty.getSizeInBits();
755 // If this is a derived type, go ahead and get the base type, unless it's a
756 // reference then it's just the size of the field. Pointer types have no need
757 // of this since they're a different type of qualification on the type.
758 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
759 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
760 return Ty.getSizeInBits();
762 if (BaseType.isDerivedType())
763 return getBaseTypeSize(DD, DIDerivedType(BaseType));
765 return BaseType.getSizeInBits();
768 /// addConstantValue - Add constant value entry in variable DIE.
769 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
771 // FIXME: This is a bit conservative/simple - it emits negative values at
772 // their maximum bit width which is a bit unfortunate (& doesn't prefer
773 // udata/sdata over dataN as suggested by the DWARF spec)
774 assert(MO.isImm() && "Invalid machine operand!");
776 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
779 // If we're a signed constant definitely use sdata.
780 if (SignedConstant) {
781 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
785 // Else use data for now unless it's larger than we can deal with.
786 switch (SizeInBits) {
788 Form = dwarf::DW_FORM_data1;
791 Form = dwarf::DW_FORM_data2;
794 Form = dwarf::DW_FORM_data4;
797 Form = dwarf::DW_FORM_data8;
800 Form = dwarf::DW_FORM_udata;
801 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
804 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
807 /// addConstantFPValue - Add constant value entry in variable DIE.
808 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
809 assert(MO.isFPImm() && "Invalid machine operand!");
810 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
811 APFloat FPImm = MO.getFPImm()->getValueAPF();
813 // Get the raw data form of the floating point.
814 const APInt FltVal = FPImm.bitcastToAPInt();
815 const char *FltPtr = (const char *)FltVal.getRawData();
817 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
818 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
819 int Incr = (LittleEndian ? 1 : -1);
820 int Start = (LittleEndian ? 0 : NumBytes - 1);
821 int Stop = (LittleEndian ? NumBytes : -1);
823 // Output the constant to DWARF one byte at a time.
824 for (; Start != Stop; Start += Incr)
825 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
827 addBlock(Die, dwarf::DW_AT_const_value, Block);
830 /// addConstantFPValue - Add constant value entry in variable DIE.
831 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
832 // Pass this down to addConstantValue as an unsigned bag of bits.
833 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
836 /// addConstantValue - Add constant value entry in variable DIE.
837 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
839 addConstantValue(Die, CI->getValue(), Unsigned);
842 // addConstantValue - Add constant value entry in variable DIE.
843 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
844 unsigned CIBitWidth = Val.getBitWidth();
845 if (CIBitWidth <= 64) {
846 // If we're a signed constant definitely use sdata.
848 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
853 // Else use data for now unless it's larger than we can deal with.
855 switch (CIBitWidth) {
857 Form = dwarf::DW_FORM_data1;
860 Form = dwarf::DW_FORM_data2;
863 Form = dwarf::DW_FORM_data4;
866 Form = dwarf::DW_FORM_data8;
869 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
873 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
877 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
879 // Get the raw data form of the large APInt.
880 const uint64_t *Ptr64 = Val.getRawData();
882 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
883 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
885 // Output the constant to DWARF one byte at a time.
886 for (int i = 0; i < NumBytes; i++) {
889 c = Ptr64[i / 8] >> (8 * (i & 7));
891 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
892 addUInt(Block, dwarf::DW_FORM_data1, c);
895 addBlock(Die, dwarf::DW_AT_const_value, Block);
898 /// addTemplateParams - Add template parameters into buffer.
899 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
900 // Add template parameters.
901 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
902 DIDescriptor Element = TParams.getElement(i);
903 if (Element.isTemplateTypeParameter())
904 constructTemplateTypeParameterDIE(Buffer,
905 DITemplateTypeParameter(Element));
906 else if (Element.isTemplateValueParameter())
907 constructTemplateValueParameterDIE(Buffer,
908 DITemplateValueParameter(Element));
912 /// getOrCreateContextDIE - Get context owner's DIE.
913 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
914 if (!Context || Context.isFile())
916 if (Context.isType())
917 return getOrCreateTypeDIE(DIType(Context));
918 if (Context.isNameSpace())
919 return getOrCreateNameSpace(DINameSpace(Context));
920 if (Context.isSubprogram())
921 return getOrCreateSubprogramDIE(DISubprogram(Context));
922 return getDIE(Context);
925 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
926 DIScope Context = resolve(Ty.getContext());
927 DIE *ContextDIE = getOrCreateContextDIE(Context);
929 DIE *TyDIE = getDIE(Ty);
934 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
936 constructTypeDIE(*TyDIE, Ty);
938 updateAcceleratorTables(Context, Ty, TyDIE);
942 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
944 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
951 // Construct the context before querying for the existence of the DIE in case
952 // such construction creates the DIE.
953 DIScope Context = resolve(Ty.getContext());
954 DIE *ContextDIE = getOrCreateContextDIE(Context);
957 DIE *TyDIE = getDIE(Ty);
962 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
964 if (Ty.isBasicType())
965 constructTypeDIE(*TyDIE, DIBasicType(Ty));
966 else if (Ty.isCompositeType()) {
967 DICompositeType CTy(Ty);
968 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
969 if (MDString *TypeId = CTy.getIdentifier()) {
970 DD->addDwarfTypeUnitType(getCUNode(), TypeId->getString(), TyDIE, CTy);
971 // Skip updating the accellerator tables since this is not the full type
974 constructTypeDIE(*TyDIE, CTy);
976 assert(Ty.isDerivedType() && "Unknown kind of DIType");
977 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
980 updateAcceleratorTables(Context, Ty, TyDIE);
985 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
987 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
988 bool IsImplementation = 0;
989 if (Ty.isCompositeType()) {
990 DICompositeType CT(Ty);
991 // A runtime language of 0 actually means C/C++ and that any
992 // non-negative value is some version of Objective-C/C++.
993 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
995 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
996 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
998 if (!Context || Context.isCompileUnit() || Context.isFile() ||
999 Context.isNameSpace())
1000 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1004 /// addType - Add a new type attribute to the specified entity.
1005 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
1006 assert(Ty && "Trying to add a type that doesn't exist?");
1008 // Check for pre-existence.
1009 DIEEntry *Entry = getDIEEntry(Ty);
1010 // If it exists then use the existing value.
1012 addDIEEntry(Entity, Attribute, Entry);
1017 DIE *Buffer = getOrCreateTypeDIE(Ty);
1020 Entry = createDIEEntry(Buffer);
1021 insertDIEEntry(Ty, Entry);
1022 addDIEEntry(Entity, Attribute, Entry);
1025 // Accelerator table mutators - add each name along with its companion
1026 // DIE to the proper table while ensuring that the name that we're going
1027 // to reference is in the string table. We do this since the names we
1028 // add may not only be identical to the names in the DIE.
1029 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1030 DU->getStringPoolEntry(Name);
1031 std::vector<const DIE *> &DIEs = AccelNames[Name];
1032 DIEs.push_back(Die);
1035 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1036 DU->getStringPoolEntry(Name);
1037 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1038 DIEs.push_back(Die);
1041 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1042 DU->getStringPoolEntry(Name);
1043 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1044 DIEs.push_back(Die);
1047 void DwarfUnit::addAccelType(StringRef Name,
1048 std::pair<const DIE *, unsigned> Die) {
1049 DU->getStringPoolEntry(Name);
1050 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1051 DIEs.push_back(Die);
1054 /// addGlobalName - Add a new global name to the compile unit.
1055 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1056 std::string FullName = getParentContextString(Context) + Name.str();
1057 GlobalNames[FullName] = Die;
1060 /// getParentContextString - Walks the metadata parent chain in a language
1061 /// specific manner (using the compile unit language) and returns
1062 /// it as a string. This is done at the metadata level because DIEs may
1063 /// not currently have been added to the parent context and walking the
1064 /// DIEs looking for names is more expensive than walking the metadata.
1065 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1069 // FIXME: Decide whether to implement this for non-C++ languages.
1070 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1074 SmallVector<DIScope, 1> Parents;
1075 while (!Context.isCompileUnit()) {
1076 Parents.push_back(Context);
1077 if (Context.getContext())
1078 Context = resolve(Context.getContext());
1080 // Structure, etc types will have a NULL context if they're at the top
1085 // Reverse iterate over our list to go from the outermost construct to the
1087 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1091 StringRef Name = Ctx.getName();
1092 if (!Name.empty()) {
1100 /// constructTypeDIE - Construct basic type die from DIBasicType.
1101 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1102 // Get core information.
1103 StringRef Name = BTy.getName();
1104 // Add name if not anonymous or intermediate type.
1106 addString(&Buffer, dwarf::DW_AT_name, Name);
1108 // An unspecified type only has a name attribute.
1109 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1112 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1115 uint64_t Size = BTy.getSizeInBits() >> 3;
1116 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1119 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1120 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1121 // Get core information.
1122 StringRef Name = DTy.getName();
1123 uint64_t Size = DTy.getSizeInBits() >> 3;
1124 uint16_t Tag = Buffer.getTag();
1126 // Map to main type, void will not have a type.
1127 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1129 addType(&Buffer, FromTy);
1131 // Add name if not anonymous or intermediate type.
1133 addString(&Buffer, dwarf::DW_AT_name, Name);
1135 // Add size if non-zero (derived types might be zero-sized.)
1136 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1137 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1139 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1140 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1141 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1142 // Add source line info if available and TyDesc is not a forward declaration.
1143 if (!DTy.isForwardDecl())
1144 addSourceLine(&Buffer, DTy);
1147 /// constructTypeDIE - Construct type DIE from DICompositeType.
1148 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1149 // Add name if not anonymous or intermediate type.
1150 StringRef Name = CTy.getName();
1152 uint64_t Size = CTy.getSizeInBits() >> 3;
1153 uint16_t Tag = Buffer.getTag();
1156 case dwarf::DW_TAG_array_type:
1157 constructArrayTypeDIE(Buffer, CTy);
1159 case dwarf::DW_TAG_enumeration_type:
1160 constructEnumTypeDIE(Buffer, CTy);
1162 case dwarf::DW_TAG_subroutine_type: {
1163 // Add return type. A void return won't have a type.
1164 DIArray Elements = CTy.getTypeArray();
1165 DIType RTy(Elements.getElement(0));
1167 addType(&Buffer, RTy);
1169 bool isPrototyped = true;
1171 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1172 DIDescriptor Ty = Elements.getElement(i);
1173 if (Ty.isUnspecifiedParameter()) {
1174 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1175 isPrototyped = false;
1177 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1178 addType(Arg, DIType(Ty));
1179 if (DIType(Ty).isArtificial())
1180 addFlag(Arg, dwarf::DW_AT_artificial);
1183 // Add prototype flag if we're dealing with a C language and the
1184 // function has been prototyped.
1185 uint16_t Language = getLanguage();
1187 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1188 Language == dwarf::DW_LANG_ObjC))
1189 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1191 if (CTy.isLValueReference())
1192 addFlag(&Buffer, dwarf::DW_AT_reference);
1194 if (CTy.isRValueReference())
1195 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1197 case dwarf::DW_TAG_structure_type:
1198 case dwarf::DW_TAG_union_type:
1199 case dwarf::DW_TAG_class_type: {
1200 // Add elements to structure type.
1201 DIArray Elements = CTy.getTypeArray();
1202 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1203 DIDescriptor Element = Elements.getElement(i);
1204 DIE *ElemDie = NULL;
1205 if (Element.isSubprogram())
1206 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1207 else if (Element.isDerivedType()) {
1208 DIDerivedType DDTy(Element);
1209 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1210 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1211 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1212 dwarf::DW_AT_friend);
1213 } else if (DDTy.isStaticMember()) {
1214 getOrCreateStaticMemberDIE(DDTy);
1216 constructMemberDIE(Buffer, DDTy);
1218 } else if (Element.isObjCProperty()) {
1219 DIObjCProperty Property(Element);
1220 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1221 StringRef PropertyName = Property.getObjCPropertyName();
1222 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1223 if (Property.getType())
1224 addType(ElemDie, Property.getType());
1225 addSourceLine(ElemDie, Property);
1226 StringRef GetterName = Property.getObjCPropertyGetterName();
1227 if (!GetterName.empty())
1228 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1229 StringRef SetterName = Property.getObjCPropertySetterName();
1230 if (!SetterName.empty())
1231 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1232 unsigned PropertyAttributes = 0;
1233 if (Property.isReadOnlyObjCProperty())
1234 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1235 if (Property.isReadWriteObjCProperty())
1236 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1237 if (Property.isAssignObjCProperty())
1238 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1239 if (Property.isRetainObjCProperty())
1240 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1241 if (Property.isCopyObjCProperty())
1242 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1243 if (Property.isNonAtomicObjCProperty())
1244 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1245 if (PropertyAttributes)
1246 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1247 PropertyAttributes);
1249 DIEEntry *Entry = getDIEEntry(Element);
1251 Entry = createDIEEntry(ElemDie);
1252 insertDIEEntry(Element, Entry);
1258 if (CTy.isAppleBlockExtension())
1259 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1261 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1263 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1264 getOrCreateTypeDIE(ContainingType));
1266 if (CTy.isObjcClassComplete())
1267 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1269 // Add template parameters to a class, structure or union types.
1270 // FIXME: The support isn't in the metadata for this yet.
1271 if (Tag == dwarf::DW_TAG_class_type ||
1272 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1273 addTemplateParams(Buffer, CTy.getTemplateParams());
1281 // Add name if not anonymous or intermediate type.
1283 addString(&Buffer, dwarf::DW_AT_name, Name);
1285 if (Tag == dwarf::DW_TAG_enumeration_type ||
1286 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1287 Tag == dwarf::DW_TAG_union_type) {
1288 // Add size if non-zero (derived types might be zero-sized.)
1289 // TODO: Do we care about size for enum forward declarations?
1291 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1292 else if (!CTy.isForwardDecl())
1293 // Add zero size if it is not a forward declaration.
1294 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1296 // If we're a forward decl, say so.
1297 if (CTy.isForwardDecl())
1298 addFlag(&Buffer, dwarf::DW_AT_declaration);
1300 // Add source line info if available.
1301 if (!CTy.isForwardDecl())
1302 addSourceLine(&Buffer, CTy);
1304 // No harm in adding the runtime language to the declaration.
1305 unsigned RLang = CTy.getRunTimeLang();
1307 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1312 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1313 /// DITemplateTypeParameter.
1314 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1315 DITemplateTypeParameter TP) {
1317 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1318 // Add the type if it exists, it could be void and therefore no type.
1320 addType(ParamDIE, resolve(TP.getType()));
1321 if (!TP.getName().empty())
1322 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1325 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1326 /// DITemplateValueParameter.
1328 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1329 DITemplateValueParameter VP) {
1330 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1332 // Add the type if there is one, template template and template parameter
1333 // packs will not have a type.
1334 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1335 addType(ParamDIE, resolve(VP.getType()));
1336 if (!VP.getName().empty())
1337 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1338 if (Value *Val = VP.getValue()) {
1339 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1340 addConstantValue(ParamDIE, CI,
1341 isUnsignedDIType(DD, resolve(VP.getType())));
1342 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1343 // For declaration non-type template parameters (such as global values and
1345 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1346 addOpAddress(Block, Asm->getSymbol(GV));
1347 // Emit DW_OP_stack_value to use the address as the immediate value of the
1348 // parameter, rather than a pointer to it.
1349 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1350 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1351 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1352 assert(isa<MDString>(Val));
1353 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1354 cast<MDString>(Val)->getString());
1355 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1356 assert(isa<MDNode>(Val));
1357 DIArray A(cast<MDNode>(Val));
1358 addTemplateParams(*ParamDIE, A);
1363 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1364 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1365 // Construct the context before querying for the existence of the DIE in case
1366 // such construction creates the DIE.
1367 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1369 DIE *NDie = getDIE(NS);
1372 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1374 if (!NS.getName().empty()) {
1375 addString(NDie, dwarf::DW_AT_name, NS.getName());
1376 addAccelNamespace(NS.getName(), NDie);
1377 addGlobalName(NS.getName(), NDie, NS.getContext());
1379 addAccelNamespace("(anonymous namespace)", NDie);
1380 addSourceLine(NDie, NS);
1384 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1385 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1386 // Construct the context before querying for the existence of the DIE in case
1387 // such construction creates the DIE (as is the case for member function
1389 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1391 DIE *SPDie = getDIE(SP);
1395 DISubprogram SPDecl = SP.getFunctionDeclaration();
1396 if (SPDecl.isSubprogram())
1397 // Add subprogram definitions to the CU die directly.
1398 ContextDIE = UnitDie.get();
1400 // DW_TAG_inlined_subroutine may refer to this DIE.
1401 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1403 DIE *DeclDie = NULL;
1404 if (SPDecl.isSubprogram())
1405 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1407 // Add function template parameters.
1408 addTemplateParams(*SPDie, SP.getTemplateParams());
1410 // If this DIE is going to refer declaration info using AT_specification
1411 // then there is no need to add other attributes.
1413 // Refer function declaration directly.
1414 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1419 // Add the linkage name if we have one.
1420 StringRef LinkageName = SP.getLinkageName();
1421 if (!LinkageName.empty())
1422 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1423 GlobalValue::getRealLinkageName(LinkageName));
1425 // Constructors and operators for anonymous aggregates do not have names.
1426 if (!SP.getName().empty())
1427 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1429 addSourceLine(SPDie, SP);
1431 // Add the prototype if we have a prototype and we have a C like
1433 uint16_t Language = getLanguage();
1434 if (SP.isPrototyped() &&
1435 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1436 Language == dwarf::DW_LANG_ObjC))
1437 addFlag(SPDie, dwarf::DW_AT_prototyped);
1439 DICompositeType SPTy = SP.getType();
1440 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1441 "the type of a subprogram should be a subroutine");
1443 DIArray Args = SPTy.getTypeArray();
1444 // Add a return type. If this is a type like a C/C++ void type we don't add a
1446 if (Args.getElement(0))
1447 addType(SPDie, DIType(Args.getElement(0)));
1449 unsigned VK = SP.getVirtuality();
1451 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1452 DIEBlock *Block = getDIEBlock();
1453 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1454 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1455 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1456 ContainingTypeMap.insert(
1457 std::make_pair(SPDie, resolve(SP.getContainingType())));
1460 if (!SP.isDefinition()) {
1461 addFlag(SPDie, dwarf::DW_AT_declaration);
1463 // Add arguments. Do not add arguments for subprogram definition. They will
1464 // be handled while processing variables.
1465 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1466 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1467 DIType ATy(Args.getElement(i));
1469 if (ATy.isArtificial())
1470 addFlag(Arg, dwarf::DW_AT_artificial);
1474 if (SP.isArtificial())
1475 addFlag(SPDie, dwarf::DW_AT_artificial);
1477 if (!SP.isLocalToUnit())
1478 addFlag(SPDie, dwarf::DW_AT_external);
1480 if (SP.isOptimized())
1481 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1483 if (unsigned isa = Asm->getISAEncoding()) {
1484 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1487 if (SP.isLValueReference())
1488 addFlag(SPDie, dwarf::DW_AT_reference);
1490 if (SP.isRValueReference())
1491 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1493 if (SP.isProtected())
1494 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1495 dwarf::DW_ACCESS_protected);
1496 else if (SP.isPrivate())
1497 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1498 dwarf::DW_ACCESS_private);
1500 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1501 dwarf::DW_ACCESS_public);
1503 if (SP.isExplicit())
1504 addFlag(SPDie, dwarf::DW_AT_explicit);
1509 // Return const expression if value is a GEP to access merged global
1511 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1512 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1513 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1514 if (!CE || CE->getNumOperands() != 3 ||
1515 CE->getOpcode() != Instruction::GetElementPtr)
1518 // First operand points to a global struct.
1519 Value *Ptr = CE->getOperand(0);
1520 if (!isa<GlobalValue>(Ptr) ||
1521 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1524 // Second operand is zero.
1525 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1526 if (!CI || !CI->isZero())
1529 // Third operand is offset.
1530 if (!isa<ConstantInt>(CE->getOperand(2)))
1536 /// createGlobalVariableDIE - create global variable DIE.
1537 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1538 // Check for pre-existence.
1542 if (!GV.isGlobalVariable())
1545 DIScope GVContext = GV.getContext();
1546 DIType GTy = GV.getType();
1548 // If this is a static data member definition, some attributes belong
1549 // to the declaration DIE.
1550 DIE *VariableDIE = NULL;
1551 bool IsStaticMember = false;
1552 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1553 if (SDMDecl.Verify()) {
1554 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1555 // We need the declaration DIE that is in the static member's class.
1556 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1557 IsStaticMember = true;
1560 // If this is not a static data member definition, create the variable
1561 // DIE and add the initial set of attributes to it.
1563 // Construct the context before querying for the existence of the DIE in
1564 // case such construction creates the DIE.
1565 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1568 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1570 // Add name and type.
1571 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1572 addType(VariableDIE, GTy);
1574 // Add scoping info.
1575 if (!GV.isLocalToUnit())
1576 addFlag(VariableDIE, dwarf::DW_AT_external);
1578 // Add line number info.
1579 addSourceLine(VariableDIE, GV);
1583 bool addToAccelTable = false;
1584 DIE *VariableSpecDIE = NULL;
1585 bool isGlobalVariable = GV.getGlobal() != NULL;
1586 if (isGlobalVariable) {
1587 addToAccelTable = true;
1588 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1589 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1590 if (GV.getGlobal()->isThreadLocal()) {
1591 // FIXME: Make this work with -gsplit-dwarf.
1592 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1593 assert((PointerSize == 4 || PointerSize == 8) &&
1594 "Add support for other sizes if necessary");
1595 const MCExpr *Expr =
1596 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1597 // Based on GCC's support for TLS:
1598 if (!DD->useSplitDwarf()) {
1599 // 1) Start with a constNu of the appropriate pointer size
1600 addUInt(Block, dwarf::DW_FORM_data1,
1601 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1602 // 2) containing the (relocated) offset of the TLS variable
1603 // within the module's TLS block.
1604 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1606 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1607 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1609 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1610 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1612 DD->addArangeLabel(SymbolCU(this, Sym));
1613 addOpAddress(Block, Sym);
1615 // Do not create specification DIE if context is either compile unit
1617 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1618 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1619 // Create specification DIE.
1620 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1621 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1622 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1623 // A static member's declaration is already flagged as such.
1624 if (!SDMDecl.Verify())
1625 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1627 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1629 // Add the linkage name.
1630 StringRef LinkageName = GV.getLinkageName();
1631 if (!LinkageName.empty())
1632 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1633 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1635 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1637 dwarf::DW_AT_MIPS_linkage_name,
1638 GlobalValue::getRealLinkageName(LinkageName));
1639 } else if (const ConstantInt *CI =
1640 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1641 // AT_const_value was added when the static member was created. To avoid
1642 // emitting AT_const_value multiple times, we only add AT_const_value when
1643 // it is not a static member.
1644 if (!IsStaticMember)
1645 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1646 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1647 addToAccelTable = true;
1648 // GV is a merged global.
1649 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1650 Value *Ptr = CE->getOperand(0);
1651 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1652 DD->addArangeLabel(SymbolCU(this, Sym));
1653 addOpAddress(Block, Sym);
1654 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1655 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1656 addUInt(Block, dwarf::DW_FORM_udata,
1657 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1658 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1659 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1662 if (addToAccelTable) {
1663 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1664 addAccelName(GV.getName(), AddrDIE);
1666 // If the linkage name is different than the name, go ahead and output
1667 // that as well into the name table.
1668 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1669 addAccelName(GV.getLinkageName(), AddrDIE);
1672 if (!GV.isLocalToUnit())
1673 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1677 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1678 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1679 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1680 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1682 // The LowerBound value defines the lower bounds which is typically zero for
1683 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1684 // Count == -1 then the array is unbounded and we do not emit
1685 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1686 // Count == 0, then the array has zero elements in which case we do not emit
1688 int64_t LowerBound = SR.getLo();
1689 int64_t DefaultLowerBound = getDefaultLowerBound();
1690 int64_t Count = SR.getCount();
1692 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1693 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1695 if (Count != -1 && Count != 0)
1696 // FIXME: An unbounded array should reference the expression that defines
1698 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1699 LowerBound + Count - 1);
1702 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1703 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1705 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1707 // Emit the element type.
1708 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1710 // Get an anonymous type for index type.
1711 // FIXME: This type should be passed down from the front end
1712 // as different languages may have different sizes for indexes.
1713 DIE *IdxTy = getIndexTyDie();
1715 // Construct an anonymous type for index type.
1716 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1717 addString(IdxTy, dwarf::DW_AT_name, "int");
1718 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1719 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1720 dwarf::DW_ATE_signed);
1721 setIndexTyDie(IdxTy);
1724 // Add subranges to array type.
1725 DIArray Elements = CTy.getTypeArray();
1726 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1727 DIDescriptor Element = Elements.getElement(i);
1728 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1729 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1733 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1734 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1735 DIArray Elements = CTy.getTypeArray();
1737 // Add enumerators to enumeration type.
1738 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1739 DIEnumerator Enum(Elements.getElement(i));
1740 if (Enum.isEnumerator()) {
1741 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1742 StringRef Name = Enum.getName();
1743 addString(Enumerator, dwarf::DW_AT_name, Name);
1744 int64_t Value = Enum.getEnumValue();
1745 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1749 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1751 addType(&Buffer, DTy);
1752 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1756 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1758 void DwarfUnit::constructContainingTypeDIEs() {
1759 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1760 CE = ContainingTypeMap.end();
1762 DIE *SPDie = CI->first;
1763 DIDescriptor D(CI->second);
1766 DIE *NDie = getDIE(D);
1769 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1773 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1774 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1775 StringRef Name = DV.getName();
1777 // Define variable debug information entry.
1778 DIE *VariableDie = new DIE(DV.getTag());
1779 DbgVariable *AbsVar = DV.getAbstractVariable();
1780 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1782 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1785 addString(VariableDie, dwarf::DW_AT_name, Name);
1786 addSourceLine(VariableDie, DV.getVariable());
1787 addType(VariableDie, DV.getType());
1790 if (DV.isArtificial())
1791 addFlag(VariableDie, dwarf::DW_AT_artificial);
1793 if (isScopeAbstract) {
1794 DV.setDIE(VariableDie);
1798 // Add variable address.
1800 unsigned Offset = DV.getDotDebugLocOffset();
1801 if (Offset != ~0U) {
1802 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1803 Asm->GetTempSymbol("debug_loc", Offset));
1804 DV.setDIE(VariableDie);
1808 // Check if variable is described by a DBG_VALUE instruction.
1809 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1810 assert(DVInsn->getNumOperands() == 3);
1811 if (DVInsn->getOperand(0).isReg()) {
1812 const MachineOperand RegOp = DVInsn->getOperand(0);
1813 // If the second operand is an immediate, this is an indirect value.
1814 if (DVInsn->getOperand(1).isImm()) {
1815 MachineLocation Location(RegOp.getReg(),
1816 DVInsn->getOperand(1).getImm());
1817 addVariableAddress(DV, VariableDie, Location);
1818 } else if (RegOp.getReg())
1819 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1820 } else if (DVInsn->getOperand(0).isImm())
1821 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1822 else if (DVInsn->getOperand(0).isFPImm())
1823 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1824 else if (DVInsn->getOperand(0).isCImm())
1825 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1826 isUnsignedDIType(DD, DV.getType()));
1828 DV.setDIE(VariableDie);
1831 // .. else use frame index.
1832 int FI = DV.getFrameIndex();
1834 unsigned FrameReg = 0;
1835 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1836 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1837 MachineLocation Location(FrameReg, Offset);
1838 addVariableAddress(DV, VariableDie, Location);
1842 DV.setDIE(VariableDie);
1846 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1847 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1848 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1849 StringRef Name = DT.getName();
1851 addString(MemberDie, dwarf::DW_AT_name, Name);
1853 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1855 addSourceLine(MemberDie, DT);
1857 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1859 // For C++, virtual base classes are not at fixed offset. Use following
1860 // expression to extract appropriate offset from vtable.
1861 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1863 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1864 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1865 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1866 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1867 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1868 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1869 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1870 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1872 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1874 uint64_t Size = DT.getSizeInBits();
1875 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1876 uint64_t OffsetInBytes;
1878 if (Size != FieldSize) {
1880 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1881 getBaseTypeSize(DD, DT) >> 3);
1882 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1884 uint64_t Offset = DT.getOffsetInBits();
1885 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1886 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1887 uint64_t FieldOffset = (HiMark - FieldSize);
1888 Offset -= FieldOffset;
1890 // Maybe we need to work from the other end.
1891 if (Asm->getDataLayout().isLittleEndian())
1892 Offset = FieldSize - (Offset + Size);
1893 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1895 // Here WD_AT_data_member_location points to the anonymous
1896 // field that includes this bit field.
1897 OffsetInBytes = FieldOffset >> 3;
1899 // This is not a bitfield.
1900 OffsetInBytes = DT.getOffsetInBits() >> 3;
1902 if (DD->getDwarfVersion() <= 2) {
1903 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1904 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1905 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1906 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1908 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1912 if (DT.isProtected())
1913 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1914 dwarf::DW_ACCESS_protected);
1915 else if (DT.isPrivate())
1916 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1917 dwarf::DW_ACCESS_private);
1918 // Otherwise C++ member and base classes are considered public.
1920 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1921 dwarf::DW_ACCESS_public);
1923 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1924 dwarf::DW_VIRTUALITY_virtual);
1926 // Objective-C properties.
1927 if (MDNode *PNode = DT.getObjCProperty())
1928 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1929 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1932 if (DT.isArtificial())
1933 addFlag(MemberDie, dwarf::DW_AT_artificial);
1936 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1937 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1941 // Construct the context before querying for the existence of the DIE in case
1942 // such construction creates the DIE.
1943 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1944 assert(dwarf::isType(ContextDIE->getTag()) &&
1945 "Static member should belong to a type.");
1947 DIE *StaticMemberDIE = getDIE(DT);
1948 if (StaticMemberDIE)
1949 return StaticMemberDIE;
1951 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1953 DIType Ty = resolve(DT.getTypeDerivedFrom());
1955 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1956 addType(StaticMemberDIE, Ty);
1957 addSourceLine(StaticMemberDIE, DT);
1958 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1959 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1961 // FIXME: We could omit private if the parent is a class_type, and
1962 // public if the parent is something else.
1963 if (DT.isProtected())
1964 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1965 dwarf::DW_ACCESS_protected);
1966 else if (DT.isPrivate())
1967 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1968 dwarf::DW_ACCESS_private);
1970 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1971 dwarf::DW_ACCESS_public);
1973 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1974 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1975 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1976 addConstantFPValue(StaticMemberDIE, CFP);
1978 return StaticMemberDIE;
1981 void DwarfUnit::emitHeader(const MCSection *ASection,
1982 const MCSymbol *ASectionSym) const {
1983 Asm->OutStreamer.AddComment("DWARF version number");
1984 Asm->EmitInt16(DD->getDwarfVersion());
1985 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1986 // We share one abbreviations table across all units so it's always at the
1987 // start of the section. Use a relocatable offset where needed to ensure
1988 // linking doesn't invalidate that offset.
1989 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1990 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1991 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1994 DwarfCompileUnit::~DwarfCompileUnit() {}
1995 DwarfTypeUnit::~DwarfTypeUnit() {}
1997 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
1998 const MCSymbol *ASectionSym) const {
1999 DwarfUnit::emitHeader(ASection, ASectionSym);
2000 Asm->OutStreamer.AddComment("Type Signature");
2001 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2002 Asm->OutStreamer.AddComment("Type DIE Offset");
2003 // In a skeleton type unit there is no type DIE so emit a zero offset.
2004 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2005 sizeof(Ty->getOffset()));
2008 void DwarfTypeUnit::initSection(const MCSection *Section) {
2009 assert(!this->Section);
2010 this->Section = Section;
2011 // Since each type unit is contained in its own COMDAT section, the begin
2012 // label and the section label are the same. Using the begin label emission in
2013 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2014 // the only other alternative of lazily constructing start-of-section labels
2015 // and storing a mapping in DwarfDebug (or AsmPrinter).
2016 this->SectionSym = this->LabelBegin =
2017 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2019 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2020 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());