1 //===-- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Unit ------------===//
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 "DwarfCompileUnit.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/MCSection.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/Target/Mangler.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Support/CommandLine.h"
36 static cl::opt<bool> GenerateTypeUnits("generate-type-units", cl::Hidden,
37 cl::desc("Generate DWARF4 type units."),
40 /// CompileUnit - Compile unit constructor.
41 CompileUnit::CompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
42 AsmPrinter *A, DwarfDebug *DW, DwarfUnits *DWU)
43 : UniqueID(UID), Node(Node), CUDie(D), Asm(A), DD(DW), DU(DWU),
44 IndexTyDie(0), Language(Node.getLanguage()) {
45 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
49 CompileUnit::CompileUnit(unsigned UID, DIE *D, uint16_t Language, AsmPrinter *A,
50 DwarfDebug *DD, DwarfUnits *DU)
51 : UniqueID(UID), Node(NULL), CUDie(D), Asm(A), DD(DD), DU(DU),
52 IndexTyDie(0), Language(Language) {
53 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
56 /// ~CompileUnit - Destructor for compile unit.
57 CompileUnit::~CompileUnit() {
58 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
59 DIEBlocks[j]->~DIEBlock();
62 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
63 /// information entry.
64 DIEEntry *CompileUnit::createDIEEntry(DIE *Entry) {
65 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
69 /// getDefaultLowerBound - Return the default lower bound for an array. If the
70 /// DWARF version doesn't handle the language, return -1.
71 int64_t CompileUnit::getDefaultLowerBound() const {
72 switch (getLanguage()) {
76 case dwarf::DW_LANG_C89:
77 case dwarf::DW_LANG_C99:
78 case dwarf::DW_LANG_C:
79 case dwarf::DW_LANG_C_plus_plus:
80 case dwarf::DW_LANG_ObjC:
81 case dwarf::DW_LANG_ObjC_plus_plus:
84 case dwarf::DW_LANG_Fortran77:
85 case dwarf::DW_LANG_Fortran90:
86 case dwarf::DW_LANG_Fortran95:
89 // The languages below have valid values only if the DWARF version >= 4.
90 case dwarf::DW_LANG_Java:
91 case dwarf::DW_LANG_Python:
92 case dwarf::DW_LANG_UPC:
93 case dwarf::DW_LANG_D:
94 if (dwarf::DWARF_VERSION >= 4)
98 case dwarf::DW_LANG_Ada83:
99 case dwarf::DW_LANG_Ada95:
100 case dwarf::DW_LANG_Cobol74:
101 case dwarf::DW_LANG_Cobol85:
102 case dwarf::DW_LANG_Modula2:
103 case dwarf::DW_LANG_Pascal83:
104 case dwarf::DW_LANG_PLI:
105 if (dwarf::DWARF_VERSION >= 4)
113 /// Check whether the DIE for this MDNode can be shared across CUs.
114 static bool isShareableAcrossCUs(DIDescriptor D) {
115 // When the MDNode can be part of the type system, the DIE can be
116 // shared across CUs.
117 return (D.isType() ||
118 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
122 /// getDIE - Returns the debug information entry map slot for the
123 /// specified debug variable. We delegate the request to DwarfDebug
124 /// when the DIE for this MDNode can be shared across CUs. The mappings
125 /// will be kept in DwarfDebug for shareable DIEs.
126 DIE *CompileUnit::getDIE(DIDescriptor D) const {
127 if (isShareableAcrossCUs(D))
128 return DD->getDIE(D);
129 return MDNodeToDieMap.lookup(D);
132 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
133 /// when the DIE for this MDNode can be shared across CUs. The mappings
134 /// will be kept in DwarfDebug for shareable DIEs.
135 void CompileUnit::insertDIE(DIDescriptor Desc, DIE *D) {
136 if (isShareableAcrossCUs(Desc)) {
137 DD->insertDIE(Desc, D);
140 MDNodeToDieMap.insert(std::make_pair(Desc, D));
143 /// addFlag - Add a flag that is true.
144 void CompileUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
145 if (DD->getDwarfVersion() >= 4)
146 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
148 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
151 /// addUInt - Add an unsigned integer attribute data and value.
153 void CompileUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
154 Optional<dwarf::Form> Form, uint64_t Integer) {
156 Form = DIEInteger::BestForm(false, Integer);
157 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
159 Die->addValue(Attribute, *Form, Value);
162 void CompileUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
163 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
166 /// addSInt - Add an signed integer attribute data and value.
168 void CompileUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
169 Optional<dwarf::Form> Form, int64_t Integer) {
171 Form = DIEInteger::BestForm(true, Integer);
172 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
173 Die->addValue(Attribute, *Form, Value);
176 void CompileUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form,
178 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
181 /// addString - Add a string attribute data and value. We always emit a
182 /// reference to the string pool instead of immediate strings so that DIEs have
183 /// more predictable sizes. In the case of split dwarf we emit an index
184 /// into another table which gets us the static offset into the string
186 void CompileUnit::addString(DIE *Die, dwarf::Attribute Attribute,
190 if (!DD->useSplitDwarf()) {
191 MCSymbol *Symb = DU->getStringPoolEntry(String);
192 if (Asm->needsRelocationsForDwarfStringPool())
193 Value = new (DIEValueAllocator) DIELabel(Symb);
195 MCSymbol *StringPool = DU->getStringPoolSym();
196 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
198 Form = dwarf::DW_FORM_strp;
200 unsigned idx = DU->getStringPoolIndex(String);
201 Value = new (DIEValueAllocator) DIEInteger(idx);
202 Form = dwarf::DW_FORM_GNU_str_index;
204 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
205 Die->addValue(Attribute, Form, 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 CompileUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
212 MCSymbol *Symb = DU->getStringPoolEntry(String);
214 if (Asm->needsRelocationsForDwarfStringPool())
215 Value = new (DIEValueAllocator) DIELabel(Symb);
217 MCSymbol *StringPool = DU->getStringPoolSym();
218 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
220 Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
223 /// addExpr - Add a Dwarf expression attribute data and value.
225 void CompileUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
226 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
227 Die->addValue((dwarf::Attribute)0, Form, Value);
230 /// addLabel - Add a Dwarf label attribute data and value.
232 void CompileUnit::addLabel(DIE *Die, dwarf::Attribute Attribute,
233 dwarf::Form Form, const MCSymbol *Label) {
234 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
235 Die->addValue(Attribute, Form, Value);
238 void CompileUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
239 const MCSymbol *Label) {
240 addLabel(Die, (dwarf::Attribute)0, Form, Label);
243 /// addLabelAddress - Add a dwarf label attribute data and value using
244 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
246 void CompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
249 DD->addArangeLabel(SymbolCU(this, Label));
251 if (!DD->useSplitDwarf()) {
253 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
254 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
256 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
257 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
260 unsigned idx = DU->getAddrPoolIndex(Label);
261 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
262 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
266 /// addOpAddress - Add a dwarf op address data and value using the
267 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
269 void CompileUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
270 DD->addArangeLabel(SymbolCU(this, Sym));
271 if (!DD->useSplitDwarf()) {
272 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
273 addLabel(Die, dwarf::DW_FORM_udata, Sym);
275 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
276 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
280 /// addDelta - Add a label delta attribute data and value.
282 void CompileUnit::addDelta(DIE *Die, dwarf::Attribute Attribute,
283 dwarf::Form Form, const MCSymbol *Hi,
284 const MCSymbol *Lo) {
285 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
286 Die->addValue(Attribute, Form, Value);
289 /// addDIEEntry - Add a DIE attribute data and value.
291 void CompileUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
293 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
296 void CompileUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
298 const DIE *DieCU = Die->getUnitOrNull();
299 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
301 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
304 EntryCU = getCUDie();
305 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
306 : dwarf::DW_FORM_ref_addr,
310 /// Create a DIE with the given Tag, add the DIE to its parent, and
311 /// call insertDIE if MD is not null.
312 DIE *CompileUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
313 DIE *Die = new DIE(Tag);
314 Parent.addChild(Die);
320 /// addBlock - Add block data.
322 void CompileUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
324 Block->ComputeSize(Asm);
325 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
326 Die->addValue(Attribute, Block->BestForm(), Block);
329 /// addSourceLine - Add location information to specified debug information
331 void CompileUnit::addSourceLine(DIE *Die, DIVariable V) {
336 unsigned Line = V.getLineNumber();
340 DD->getOrCreateSourceID(V.getContext().getFilename(),
341 V.getContext().getDirectory(), getUniqueID());
342 assert(FileID && "Invalid file id");
343 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
344 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
347 /// addSourceLine - Add location information to specified debug information
349 void CompileUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
350 // Verify global variable.
351 if (!G.isGlobalVariable())
354 unsigned Line = G.getLineNumber();
358 DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(), getUniqueID());
359 assert(FileID && "Invalid file id");
360 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
361 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
364 /// addSourceLine - Add location information to specified debug information
366 void CompileUnit::addSourceLine(DIE *Die, DISubprogram SP) {
367 // Verify subprogram.
368 if (!SP.isSubprogram())
371 // If the line number is 0, don't add it.
372 unsigned Line = SP.getLineNumber();
376 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
378 assert(FileID && "Invalid file id");
379 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
380 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
383 /// addSourceLine - Add location information to specified debug information
385 void CompileUnit::addSourceLine(DIE *Die, DIType Ty) {
390 unsigned Line = Ty.getLineNumber();
393 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.getDirectory(),
395 assert(FileID && "Invalid file id");
396 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
397 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
400 /// addSourceLine - Add location information to specified debug information
402 void CompileUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
404 if (!Ty.isObjCProperty())
407 unsigned Line = Ty.getLineNumber();
410 DIFile File = Ty.getFile();
411 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
412 File.getDirectory(), getUniqueID());
413 assert(FileID && "Invalid file id");
414 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
415 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
418 /// addSourceLine - Add location information to specified debug information
420 void CompileUnit::addSourceLine(DIE *Die, DINameSpace NS) {
425 unsigned Line = NS.getLineNumber();
428 StringRef FN = NS.getFilename();
431 DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
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 /// addVariableAddress - Add DW_AT_location attribute for a
438 /// DbgVariable based on provided MachineLocation.
439 void CompileUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
440 MachineLocation Location) {
441 if (DV.variableHasComplexAddress())
442 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
443 else if (DV.isBlockByrefVariable())
444 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
446 addAddress(Die, dwarf::DW_AT_location, Location,
447 DV.getVariable().isIndirect());
450 /// addRegisterOp - Add register operand.
451 void CompileUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
452 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
453 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
455 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
457 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
458 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
462 /// addRegisterOffset - Add register offset.
463 void CompileUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
465 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
466 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
467 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
468 if (Reg == TRI->getFrameRegister(*Asm->MF))
469 // If variable offset is based in frame register then use fbreg.
470 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
472 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
474 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
475 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
477 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
480 /// addAddress - Add an address attribute to a die based on the location
482 void CompileUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
483 const MachineLocation &Location, bool Indirect) {
484 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
486 if (Location.isReg() && !Indirect)
487 addRegisterOp(Block, Location.getReg());
489 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
490 if (Indirect && !Location.isReg()) {
491 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
495 // Now attach the location information to the DIE.
496 addBlock(Die, Attribute, Block);
499 /// addComplexAddress - Start with the address based on the location provided,
500 /// and generate the DWARF information necessary to find the actual variable
501 /// given the extra address information encoded in the DIVariable, starting from
502 /// the starting location. Add the DWARF information to the die.
504 void CompileUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
505 dwarf::Attribute Attribute,
506 const MachineLocation &Location) {
507 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
508 unsigned N = DV.getNumAddrElements();
510 if (Location.isReg()) {
511 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
512 // If first address element is OpPlus then emit
513 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
514 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
517 addRegisterOp(Block, Location.getReg());
519 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
522 uint64_t Element = DV.getAddrElement(i);
523 if (Element == DIBuilder::OpPlus) {
524 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
525 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
526 } else if (Element == DIBuilder::OpDeref) {
527 if (!Location.isReg())
528 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
530 llvm_unreachable("unknown DIBuilder Opcode");
533 // Now attach the location information to the DIE.
534 addBlock(Die, Attribute, Block);
537 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
538 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
539 gives the variable VarName either the struct, or a pointer to the struct, as
540 its type. This is necessary for various behind-the-scenes things the
541 compiler needs to do with by-reference variables in Blocks.
543 However, as far as the original *programmer* is concerned, the variable
544 should still have type 'SomeType', as originally declared.
546 The function getBlockByrefType dives into the __Block_byref_x_VarName
547 struct to find the original type of the variable, which is then assigned to
548 the variable's Debug Information Entry as its real type. So far, so good.
549 However now the debugger will expect the variable VarName to have the type
550 SomeType. So we need the location attribute for the variable to be an
551 expression that explains to the debugger how to navigate through the
552 pointers and struct to find the actual variable of type SomeType.
554 The following function does just that. We start by getting
555 the "normal" location for the variable. This will be the location
556 of either the struct __Block_byref_x_VarName or the pointer to the
557 struct __Block_byref_x_VarName.
559 The struct will look something like:
561 struct __Block_byref_x_VarName {
563 struct __Block_byref_x_VarName *forwarding;
564 ... <various other fields>
566 ... <maybe more fields>
569 If we are given the struct directly (as our starting point) we
570 need to tell the debugger to:
572 1). Add the offset of the forwarding field.
574 2). Follow that pointer to get the real __Block_byref_x_VarName
575 struct to use (the real one may have been copied onto the heap).
577 3). Add the offset for the field VarName, to find the actual variable.
579 If we started with a pointer to the struct, then we need to
580 dereference that pointer first, before the other steps.
581 Translating this into DWARF ops, we will need to append the following
582 to the current location description for the variable:
584 DW_OP_deref -- optional, if we start with a pointer
585 DW_OP_plus_uconst <forward_fld_offset>
587 DW_OP_plus_uconst <varName_fld_offset>
589 That is what this function does. */
591 /// addBlockByrefAddress - Start with the address based on the location
592 /// provided, and generate the DWARF information necessary to find the
593 /// actual Block variable (navigating the Block struct) based on the
594 /// starting location. Add the DWARF information to the die. For
595 /// more information, read large comment just above here.
597 void CompileUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
598 dwarf::Attribute Attribute,
599 const MachineLocation &Location) {
600 DIType Ty = DV.getType();
602 uint16_t Tag = Ty.getTag();
603 bool isPointer = false;
605 StringRef varName = DV.getName();
607 if (Tag == dwarf::DW_TAG_pointer_type) {
608 DIDerivedType DTy(Ty);
609 TmpTy = resolve(DTy.getTypeDerivedFrom());
613 DICompositeType blockStruct(TmpTy);
615 // Find the __forwarding field and the variable field in the __Block_byref
617 DIArray Fields = blockStruct.getTypeArray();
618 DIDerivedType varField;
619 DIDerivedType forwardingField;
621 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
622 DIDerivedType DT(Fields.getElement(i));
623 StringRef fieldName = DT.getName();
624 if (fieldName == "__forwarding")
625 forwardingField = DT;
626 else if (fieldName == varName)
630 // Get the offsets for the forwarding field and the variable field.
631 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
632 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
634 // Decode the original location, and use that as the start of the byref
635 // variable's location.
636 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
638 if (Location.isReg())
639 addRegisterOp(Block, Location.getReg());
641 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
643 // If we started with a pointer to the __Block_byref... struct, then
644 // the first thing we need to do is dereference the pointer (DW_OP_deref).
646 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
648 // Next add the offset for the '__forwarding' field:
649 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
650 // adding the offset if it's 0.
651 if (forwardingFieldOffset > 0) {
652 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
653 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
656 // Now dereference the __forwarding field to get to the real __Block_byref
657 // struct: DW_OP_deref.
658 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
660 // Now that we've got the real __Block_byref... struct, add the offset
661 // for the variable's field to get to the location of the actual variable:
662 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
663 if (varFieldOffset > 0) {
664 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
665 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
668 // Now attach the location information to the DIE.
669 addBlock(Die, Attribute, Block);
672 /// isTypeSigned - Return true if the type is signed.
673 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
674 if (Ty.isDerivedType())
675 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
677 if (Ty.isBasicType())
678 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
679 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
680 *SizeInBits = Ty.getSizeInBits();
686 /// Return true if type encoding is unsigned.
687 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
688 DIDerivedType DTy(Ty);
689 if (DTy.isDerivedType())
690 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
693 if (BTy.isBasicType()) {
694 unsigned Encoding = BTy.getEncoding();
695 if (Encoding == dwarf::DW_ATE_unsigned ||
696 Encoding == dwarf::DW_ATE_unsigned_char ||
697 Encoding == dwarf::DW_ATE_boolean)
703 /// If this type is derived from a base type then return base type size.
704 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
705 unsigned Tag = Ty.getTag();
707 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
708 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
709 Tag != dwarf::DW_TAG_restrict_type)
710 return Ty.getSizeInBits();
712 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
714 // If this type is not derived from any type then take conservative approach.
715 if (!BaseType.isValid())
716 return Ty.getSizeInBits();
718 // If this is a derived type, go ahead and get the base type, unless it's a
719 // reference then it's just the size of the field. Pointer types have no need
720 // of this since they're a different type of qualification on the type.
721 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
722 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
723 return Ty.getSizeInBits();
725 if (BaseType.isDerivedType())
726 return getBaseTypeSize(DD, DIDerivedType(BaseType));
728 return BaseType.getSizeInBits();
731 /// addConstantValue - Add constant value entry in variable DIE.
732 void CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
734 // FIXME: This is a bit conservative/simple - it emits negative values at
735 // their maximum bit width which is a bit unfortunate (& doesn't prefer
736 // udata/sdata over dataN as suggested by the DWARF spec)
737 assert(MO.isImm() && "Invalid machine operand!");
739 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
742 // If we're a signed constant definitely use sdata.
743 if (SignedConstant) {
744 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
748 // Else use data for now unless it's larger than we can deal with.
749 switch (SizeInBits) {
751 Form = dwarf::DW_FORM_data1;
754 Form = dwarf::DW_FORM_data2;
757 Form = dwarf::DW_FORM_data4;
760 Form = dwarf::DW_FORM_data8;
763 Form = dwarf::DW_FORM_udata;
764 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
767 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
770 /// addConstantFPValue - Add constant value entry in variable DIE.
771 void CompileUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
772 assert(MO.isFPImm() && "Invalid machine operand!");
773 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
774 APFloat FPImm = MO.getFPImm()->getValueAPF();
776 // Get the raw data form of the floating point.
777 const APInt FltVal = FPImm.bitcastToAPInt();
778 const char *FltPtr = (const char *)FltVal.getRawData();
780 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
781 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
782 int Incr = (LittleEndian ? 1 : -1);
783 int Start = (LittleEndian ? 0 : NumBytes - 1);
784 int Stop = (LittleEndian ? NumBytes : -1);
786 // Output the constant to DWARF one byte at a time.
787 for (; Start != Stop; Start += Incr)
788 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
790 addBlock(Die, dwarf::DW_AT_const_value, Block);
793 /// addConstantFPValue - Add constant value entry in variable DIE.
794 void CompileUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
795 // Pass this down to addConstantValue as an unsigned bag of bits.
796 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
799 /// addConstantValue - Add constant value entry in variable DIE.
800 void CompileUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
802 addConstantValue(Die, CI->getValue(), Unsigned);
805 // addConstantValue - Add constant value entry in variable DIE.
806 void CompileUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
807 unsigned CIBitWidth = Val.getBitWidth();
808 if (CIBitWidth <= 64) {
809 // If we're a signed constant definitely use sdata.
811 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
816 // Else use data for now unless it's larger than we can deal with.
818 switch (CIBitWidth) {
820 Form = dwarf::DW_FORM_data1;
823 Form = dwarf::DW_FORM_data2;
826 Form = dwarf::DW_FORM_data4;
829 Form = dwarf::DW_FORM_data8;
832 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
836 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
840 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
842 // Get the raw data form of the large APInt.
843 const uint64_t *Ptr64 = Val.getRawData();
845 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
846 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
848 // Output the constant to DWARF one byte at a time.
849 for (int i = 0; i < NumBytes; i++) {
852 c = Ptr64[i / 8] >> (8 * (i & 7));
854 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
855 addUInt(Block, dwarf::DW_FORM_data1, c);
858 addBlock(Die, dwarf::DW_AT_const_value, Block);
861 /// addTemplateParams - Add template parameters into buffer.
862 void CompileUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
863 // Add template parameters.
864 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
865 DIDescriptor Element = TParams.getElement(i);
866 if (Element.isTemplateTypeParameter())
867 constructTemplateTypeParameterDIE(Buffer,
868 DITemplateTypeParameter(Element));
869 else if (Element.isTemplateValueParameter())
870 constructTemplateValueParameterDIE(Buffer,
871 DITemplateValueParameter(Element));
875 /// getOrCreateContextDIE - Get context owner's DIE.
876 DIE *CompileUnit::getOrCreateContextDIE(DIScope Context) {
877 if (!Context || Context.isFile())
879 if (Context.isType())
880 return getOrCreateTypeDIE(DIType(Context));
881 if (Context.isNameSpace())
882 return getOrCreateNameSpace(DINameSpace(Context));
883 if (Context.isSubprogram())
884 return getOrCreateSubprogramDIE(DISubprogram(Context));
885 return getDIE(Context);
888 DIE *CompileUnit::createTypeDIE(DICompositeType Ty) {
889 DIE *ContextDIE = getOrCreateContextDIE(resolve(Ty.getContext()));
891 DIE *TyDIE = getDIE(Ty);
896 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
898 constructTypeDIEImpl(*TyDIE, Ty);
900 updateAcceleratorTables(Ty, TyDIE);
904 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
906 DIE *CompileUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
913 // Construct the context before querying for the existence of the DIE in case
914 // such construction creates the DIE.
915 DIE *ContextDIE = getOrCreateContextDIE(resolve(Ty.getContext()));
918 DIE *TyDIE = getDIE(Ty);
923 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
925 if (Ty.isBasicType())
926 constructTypeDIE(*TyDIE, DIBasicType(Ty));
927 else if (Ty.isCompositeType())
928 constructTypeDIE(*TyDIE, DICompositeType(Ty));
930 assert(Ty.isDerivedType() && "Unknown kind of DIType");
931 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
934 updateAcceleratorTables(Ty, TyDIE);
939 void CompileUnit::updateAcceleratorTables(DIType Ty, const DIE *TyDIE) {
940 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
941 bool IsImplementation = 0;
942 if (Ty.isCompositeType()) {
943 DICompositeType CT(Ty);
944 // A runtime language of 0 actually means C/C++ and that any
945 // non-negative value is some version of Objective-C/C++.
946 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
948 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
949 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
953 /// addType - Add a new type attribute to the specified entity.
954 void CompileUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
955 assert(Ty && "Trying to add a type that doesn't exist?");
957 // Check for pre-existence.
958 DIEEntry *Entry = getDIEEntry(Ty);
959 // If it exists then use the existing value.
961 addDIEEntry(Entity, Attribute, Entry);
966 DIE *Buffer = getOrCreateTypeDIE(Ty);
969 Entry = createDIEEntry(Buffer);
970 insertDIEEntry(Ty, Entry);
971 addDIEEntry(Entity, Attribute, Entry);
973 // If this is a complete composite type then include it in the
974 // list of global types.
978 // Accelerator table mutators - add each name along with its companion
979 // DIE to the proper table while ensuring that the name that we're going
980 // to reference is in the string table. We do this since the names we
981 // add may not only be identical to the names in the DIE.
982 void CompileUnit::addAccelName(StringRef Name, const DIE *Die) {
983 DU->getStringPoolEntry(Name);
984 std::vector<const DIE *> &DIEs = AccelNames[Name];
988 void CompileUnit::addAccelObjC(StringRef Name, const DIE *Die) {
989 DU->getStringPoolEntry(Name);
990 std::vector<const DIE *> &DIEs = AccelObjC[Name];
994 void CompileUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
995 DU->getStringPoolEntry(Name);
996 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1000 void CompileUnit::addAccelType(StringRef Name,
1001 std::pair<const DIE *, unsigned> Die) {
1002 DU->getStringPoolEntry(Name);
1003 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1004 DIEs.push_back(Die);
1007 /// addGlobalName - Add a new global name to the compile unit.
1008 void CompileUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1009 std::string FullName = getParentContextString(Context) + Name.str();
1010 GlobalNames[FullName] = Die;
1013 /// addGlobalType - Add a new global type to the compile unit.
1015 void CompileUnit::addGlobalType(DIType Ty) {
1016 DIScope Context = resolve(Ty.getContext());
1017 if (!Ty.getName().empty() && !Ty.isForwardDecl() &&
1018 (!Context || Context.isCompileUnit() || Context.isFile() ||
1019 Context.isNameSpace()))
1020 if (DIEEntry *Entry = getDIEEntry(Ty)) {
1021 std::string FullName =
1022 getParentContextString(Context) + Ty.getName().str();
1023 GlobalTypes[FullName] = Entry->getEntry();
1027 /// getParentContextString - Walks the metadata parent chain in a language
1028 /// specific manner (using the compile unit language) and returns
1029 /// it as a string. This is done at the metadata level because DIEs may
1030 /// not currently have been added to the parent context and walking the
1031 /// DIEs looking for names is more expensive than walking the metadata.
1032 std::string CompileUnit::getParentContextString(DIScope Context) const {
1036 // FIXME: Decide whether to implement this for non-C++ languages.
1037 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1041 SmallVector<DIScope, 1> Parents;
1042 while (!Context.isCompileUnit()) {
1043 Parents.push_back(Context);
1044 if (Context.getContext())
1045 Context = resolve(Context.getContext());
1047 // Structure, etc types will have a NULL context if they're at the top
1052 // Reverse iterate over our list to go from the outermost construct to the
1054 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1058 StringRef Name = Ctx.getName();
1059 if (!Name.empty()) {
1067 /// addPubTypes - Add subprogram argument types for pubtypes section.
1068 void CompileUnit::addPubTypes(DISubprogram SP) {
1069 DICompositeType SPTy = SP.getType();
1070 uint16_t SPTag = SPTy.getTag();
1071 if (SPTag != dwarf::DW_TAG_subroutine_type)
1074 DIArray Args = SPTy.getTypeArray();
1075 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1076 DIType ATy(Args.getElement(i));
1083 /// constructTypeDIE - Construct basic type die from DIBasicType.
1084 void CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1085 // Get core information.
1086 StringRef Name = BTy.getName();
1087 // Add name if not anonymous or intermediate type.
1089 addString(&Buffer, dwarf::DW_AT_name, Name);
1091 // An unspecified type only has a name attribute.
1092 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1095 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1098 uint64_t Size = BTy.getSizeInBits() >> 3;
1099 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1102 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1103 void CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1104 // Get core information.
1105 StringRef Name = DTy.getName();
1106 uint64_t Size = DTy.getSizeInBits() >> 3;
1107 uint16_t Tag = Buffer.getTag();
1109 // Map to main type, void will not have a type.
1110 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1112 addType(&Buffer, FromTy);
1114 // Add name if not anonymous or intermediate type.
1116 addString(&Buffer, dwarf::DW_AT_name, Name);
1118 // Add size if non-zero (derived types might be zero-sized.)
1119 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1120 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1122 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1123 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1124 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1125 // Add source line info if available and TyDesc is not a forward declaration.
1126 if (!DTy.isForwardDecl())
1127 addSourceLine(&Buffer, DTy);
1130 /// Return true if the type is appropriately scoped to be contained inside
1131 /// its own type unit.
1132 static bool isTypeUnitScoped(DIType Ty, const DwarfDebug *DD) {
1133 DIScope Parent = DD->resolve(Ty.getContext());
1135 // Don't generate a hash for anything scoped inside a function.
1136 if (Parent.isSubprogram())
1138 Parent = DD->resolve(Parent.getContext());
1143 /// Return true if the type should be split out into a type unit.
1144 static bool shouldCreateTypeUnit(DICompositeType CTy, const DwarfDebug *DD) {
1145 if (!GenerateTypeUnits)
1148 uint16_t Tag = CTy.getTag();
1151 case dwarf::DW_TAG_structure_type:
1152 case dwarf::DW_TAG_union_type:
1153 case dwarf::DW_TAG_enumeration_type:
1154 case dwarf::DW_TAG_class_type:
1155 // If this is a class, structure, union, or enumeration type
1156 // that is a definition (not a declaration), and not scoped
1157 // inside a function then separate this out as a type unit.
1158 return !CTy.isForwardDecl() && isTypeUnitScoped(CTy, DD);
1164 /// constructTypeDIE - Construct type DIE from DICompositeType.
1165 void CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1166 // If this is a type applicable to a type unit it then add it to the
1167 // list of types we'll compute a hash for later.
1168 if (shouldCreateTypeUnit(CTy, DD))
1169 DD->addTypeUnitType(&Buffer, CTy);
1171 constructTypeDIEImpl(Buffer, CTy);
1174 void CompileUnit::constructTypeDIEImpl(DIE &Buffer, DICompositeType CTy) {
1175 // Add name if not anonymous or intermediate type.
1176 StringRef Name = CTy.getName();
1178 uint64_t Size = CTy.getSizeInBits() >> 3;
1179 uint16_t Tag = Buffer.getTag();
1182 case dwarf::DW_TAG_array_type:
1183 constructArrayTypeDIE(Buffer, CTy);
1185 case dwarf::DW_TAG_enumeration_type:
1186 constructEnumTypeDIE(Buffer, CTy);
1188 case dwarf::DW_TAG_subroutine_type: {
1189 // Add return type. A void return won't have a type.
1190 DIArray Elements = CTy.getTypeArray();
1191 DIType RTy(Elements.getElement(0));
1193 addType(&Buffer, RTy);
1195 bool isPrototyped = true;
1197 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1198 DIDescriptor Ty = Elements.getElement(i);
1199 if (Ty.isUnspecifiedParameter()) {
1200 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1201 isPrototyped = false;
1203 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1204 addType(Arg, DIType(Ty));
1205 if (DIType(Ty).isArtificial())
1206 addFlag(Arg, dwarf::DW_AT_artificial);
1209 // Add prototype flag if we're dealing with a C language and the
1210 // function has been prototyped.
1211 uint16_t Language = getLanguage();
1213 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1214 Language == dwarf::DW_LANG_ObjC))
1215 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1217 case dwarf::DW_TAG_structure_type:
1218 case dwarf::DW_TAG_union_type:
1219 case dwarf::DW_TAG_class_type: {
1220 // Add elements to structure type.
1221 DIArray Elements = CTy.getTypeArray();
1222 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1223 DIDescriptor Element = Elements.getElement(i);
1224 DIE *ElemDie = NULL;
1225 if (Element.isSubprogram()) {
1226 DISubprogram SP(Element);
1227 ElemDie = getOrCreateSubprogramDIE(SP);
1228 if (SP.isProtected())
1229 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1230 dwarf::DW_ACCESS_protected);
1231 else if (SP.isPrivate())
1232 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1233 dwarf::DW_ACCESS_private);
1235 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1236 dwarf::DW_ACCESS_public);
1237 if (SP.isExplicit())
1238 addFlag(ElemDie, dwarf::DW_AT_explicit);
1239 } else if (Element.isDerivedType()) {
1240 DIDerivedType DDTy(Element);
1241 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1242 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1243 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1244 dwarf::DW_AT_friend);
1245 } else if (DDTy.isStaticMember()) {
1246 getOrCreateStaticMemberDIE(DDTy);
1248 constructMemberDIE(Buffer, DDTy);
1250 } else if (Element.isObjCProperty()) {
1251 DIObjCProperty Property(Element);
1252 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1253 StringRef PropertyName = Property.getObjCPropertyName();
1254 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1255 addType(ElemDie, Property.getType());
1256 addSourceLine(ElemDie, Property);
1257 StringRef GetterName = Property.getObjCPropertyGetterName();
1258 if (!GetterName.empty())
1259 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1260 StringRef SetterName = Property.getObjCPropertySetterName();
1261 if (!SetterName.empty())
1262 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1263 unsigned PropertyAttributes = 0;
1264 if (Property.isReadOnlyObjCProperty())
1265 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1266 if (Property.isReadWriteObjCProperty())
1267 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1268 if (Property.isAssignObjCProperty())
1269 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1270 if (Property.isRetainObjCProperty())
1271 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1272 if (Property.isCopyObjCProperty())
1273 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1274 if (Property.isNonAtomicObjCProperty())
1275 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1276 if (PropertyAttributes)
1277 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1278 PropertyAttributes);
1280 DIEEntry *Entry = getDIEEntry(Element);
1282 Entry = createDIEEntry(ElemDie);
1283 insertDIEEntry(Element, Entry);
1289 if (CTy.isAppleBlockExtension())
1290 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1292 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1294 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1295 getOrCreateTypeDIE(ContainingType));
1297 if (CTy.isObjcClassComplete())
1298 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1300 // Add template parameters to a class, structure or union types.
1301 // FIXME: The support isn't in the metadata for this yet.
1302 if (Tag == dwarf::DW_TAG_class_type ||
1303 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1304 addTemplateParams(Buffer, CTy.getTemplateParams());
1312 // Add name if not anonymous or intermediate type.
1314 addString(&Buffer, dwarf::DW_AT_name, Name);
1316 if (Tag == dwarf::DW_TAG_enumeration_type ||
1317 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1318 Tag == dwarf::DW_TAG_union_type) {
1319 // Add size if non-zero (derived types might be zero-sized.)
1320 // TODO: Do we care about size for enum forward declarations?
1322 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1323 else if (!CTy.isForwardDecl())
1324 // Add zero size if it is not a forward declaration.
1325 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1327 // If we're a forward decl, say so.
1328 if (CTy.isForwardDecl())
1329 addFlag(&Buffer, dwarf::DW_AT_declaration);
1331 // Add source line info if available.
1332 if (!CTy.isForwardDecl())
1333 addSourceLine(&Buffer, CTy);
1335 // No harm in adding the runtime language to the declaration.
1336 unsigned RLang = CTy.getRunTimeLang();
1338 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1343 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1344 /// DITemplateTypeParameter.
1346 CompileUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1347 DITemplateTypeParameter TP) {
1349 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1350 // Add the type if it exists, it could be void and therefore no type.
1352 addType(ParamDIE, resolve(TP.getType()));
1353 if (!TP.getName().empty())
1354 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1357 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1358 /// DITemplateValueParameter.
1360 CompileUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1361 DITemplateValueParameter VP) {
1362 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1364 // Add the type if there is one, template template and template parameter
1365 // packs will not have a type.
1366 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1367 addType(ParamDIE, resolve(VP.getType()));
1368 if (!VP.getName().empty())
1369 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1370 if (Value *Val = VP.getValue()) {
1371 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1372 addConstantValue(ParamDIE, CI,
1373 isUnsignedDIType(DD, resolve(VP.getType())));
1374 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1375 // For declaration non-type template parameters (such as global values and
1377 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1378 addOpAddress(Block, Asm->getSymbol(GV));
1379 // Emit DW_OP_stack_value to use the address as the immediate value of the
1380 // parameter, rather than a pointer to it.
1381 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1382 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1383 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1384 assert(isa<MDString>(Val));
1385 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1386 cast<MDString>(Val)->getString());
1387 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1388 assert(isa<MDNode>(Val));
1389 DIArray A(cast<MDNode>(Val));
1390 addTemplateParams(*ParamDIE, A);
1395 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1396 DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
1397 // Construct the context before querying for the existence of the DIE in case
1398 // such construction creates the DIE.
1399 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1401 DIE *NDie = getDIE(NS);
1404 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1406 if (!NS.getName().empty()) {
1407 addString(NDie, dwarf::DW_AT_name, NS.getName());
1408 addAccelNamespace(NS.getName(), NDie);
1409 addGlobalName(NS.getName(), NDie, NS.getContext());
1411 addAccelNamespace("(anonymous namespace)", NDie);
1412 addSourceLine(NDie, NS);
1416 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1417 DIE *CompileUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1418 // Construct the context before querying for the existence of the DIE in case
1419 // such construction creates the DIE (as is the case for member function
1421 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1423 DIE *SPDie = getDIE(SP);
1427 DISubprogram SPDecl = SP.getFunctionDeclaration();
1428 if (SPDecl.isSubprogram())
1429 // Add subprogram definitions to the CU die directly.
1430 ContextDIE = CUDie.get();
1432 // DW_TAG_inlined_subroutine may refer to this DIE.
1433 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1435 DIE *DeclDie = NULL;
1436 if (SPDecl.isSubprogram())
1437 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1439 // Add function template parameters.
1440 addTemplateParams(*SPDie, SP.getTemplateParams());
1442 // If this DIE is going to refer declaration info using AT_specification
1443 // then there is no need to add other attributes.
1445 // Refer function declaration directly.
1446 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1451 // Add the linkage name if we have one.
1452 StringRef LinkageName = SP.getLinkageName();
1453 if (!LinkageName.empty())
1454 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1455 GlobalValue::getRealLinkageName(LinkageName));
1457 // Constructors and operators for anonymous aggregates do not have names.
1458 if (!SP.getName().empty())
1459 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1461 addSourceLine(SPDie, SP);
1463 // Add the prototype if we have a prototype and we have a C like
1465 uint16_t Language = getLanguage();
1466 if (SP.isPrototyped() &&
1467 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1468 Language == dwarf::DW_LANG_ObjC))
1469 addFlag(SPDie, dwarf::DW_AT_prototyped);
1471 DICompositeType SPTy = SP.getType();
1472 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1473 "the type of a subprogram should be a subroutine");
1475 DIArray Args = SPTy.getTypeArray();
1476 // Add a return type. If this is a type like a C/C++ void type we don't add a
1478 if (Args.getElement(0))
1479 addType(SPDie, DIType(Args.getElement(0)));
1481 unsigned VK = SP.getVirtuality();
1483 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1484 DIEBlock *Block = getDIEBlock();
1485 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1486 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1487 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1488 ContainingTypeMap.insert(
1489 std::make_pair(SPDie, resolve(SP.getContainingType())));
1492 if (!SP.isDefinition()) {
1493 addFlag(SPDie, dwarf::DW_AT_declaration);
1495 // Add arguments. Do not add arguments for subprogram definition. They will
1496 // be handled while processing variables.
1497 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1498 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1499 DIType ATy(Args.getElement(i));
1501 if (ATy.isArtificial())
1502 addFlag(Arg, dwarf::DW_AT_artificial);
1506 if (SP.isArtificial())
1507 addFlag(SPDie, dwarf::DW_AT_artificial);
1509 if (!SP.isLocalToUnit())
1510 addFlag(SPDie, dwarf::DW_AT_external);
1512 if (SP.isOptimized())
1513 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1515 if (unsigned isa = Asm->getISAEncoding()) {
1516 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1522 // Return const expression if value is a GEP to access merged global
1524 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1525 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1526 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1527 if (!CE || CE->getNumOperands() != 3 ||
1528 CE->getOpcode() != Instruction::GetElementPtr)
1531 // First operand points to a global struct.
1532 Value *Ptr = CE->getOperand(0);
1533 if (!isa<GlobalValue>(Ptr) ||
1534 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1537 // Second operand is zero.
1538 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1539 if (!CI || !CI->isZero())
1542 // Third operand is offset.
1543 if (!isa<ConstantInt>(CE->getOperand(2)))
1549 /// createGlobalVariableDIE - create global variable DIE.
1550 void CompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1551 // Check for pre-existence.
1555 if (!GV.isGlobalVariable())
1558 DIScope GVContext = GV.getContext();
1559 DIType GTy = GV.getType();
1561 // If this is a static data member definition, some attributes belong
1562 // to the declaration DIE.
1563 DIE *VariableDIE = NULL;
1564 bool IsStaticMember = false;
1565 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1566 if (SDMDecl.Verify()) {
1567 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1568 // We need the declaration DIE that is in the static member's class.
1569 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1570 IsStaticMember = true;
1573 // If this is not a static data member definition, create the variable
1574 // DIE and add the initial set of attributes to it.
1576 // Construct the context before querying for the existence of the DIE in
1577 // case such construction creates the DIE.
1578 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1581 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1583 // Add name and type.
1584 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1585 addType(VariableDIE, GTy);
1587 // Add scoping info.
1588 if (!GV.isLocalToUnit())
1589 addFlag(VariableDIE, dwarf::DW_AT_external);
1591 // Add line number info.
1592 addSourceLine(VariableDIE, GV);
1596 bool addToAccelTable = false;
1597 DIE *VariableSpecDIE = NULL;
1598 bool isGlobalVariable = GV.getGlobal() != NULL;
1599 if (isGlobalVariable) {
1600 addToAccelTable = true;
1601 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1602 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1603 if (GV.getGlobal()->isThreadLocal()) {
1604 // FIXME: Make this work with -gsplit-dwarf.
1605 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1606 assert((PointerSize == 4 || PointerSize == 8) &&
1607 "Add support for other sizes if necessary");
1608 const MCExpr *Expr =
1609 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1610 // Based on GCC's support for TLS:
1611 if (!DD->useSplitDwarf()) {
1612 // 1) Start with a constNu of the appropriate pointer size
1613 addUInt(Block, dwarf::DW_FORM_data1,
1614 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1615 // 2) containing the (relocated) offset of the TLS variable
1616 // within the module's TLS block.
1617 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1619 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1620 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1622 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1623 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1625 addOpAddress(Block, Sym);
1626 // Do not create specification DIE if context is either compile unit
1628 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1629 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1630 // Create specification DIE.
1631 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *CUDie);
1632 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1633 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1634 // A static member's declaration is already flagged as such.
1635 if (!SDMDecl.Verify())
1636 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1638 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1640 // Add the linkage name.
1641 StringRef LinkageName = GV.getLinkageName();
1642 if (!LinkageName.empty())
1643 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1644 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1646 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1648 dwarf::DW_AT_MIPS_linkage_name,
1649 GlobalValue::getRealLinkageName(LinkageName));
1650 } else if (const ConstantInt *CI =
1651 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1652 // AT_const_value was added when the static member was created. To avoid
1653 // emitting AT_const_value multiple times, we only add AT_const_value when
1654 // it is not a static member.
1655 if (!IsStaticMember)
1656 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1657 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1658 addToAccelTable = true;
1659 // GV is a merged global.
1660 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1661 Value *Ptr = CE->getOperand(0);
1662 addOpAddress(Block, Asm->getSymbol(cast<GlobalValue>(Ptr)));
1663 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1664 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1665 addUInt(Block, dwarf::DW_FORM_udata,
1666 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1667 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1668 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1671 if (addToAccelTable) {
1672 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1673 addAccelName(GV.getName(), AddrDIE);
1675 // If the linkage name is different than the name, go ahead and output
1676 // that as well into the name table.
1677 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1678 addAccelName(GV.getLinkageName(), AddrDIE);
1681 if (!GV.isLocalToUnit())
1682 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1686 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1687 void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR,
1689 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1690 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1692 // The LowerBound value defines the lower bounds which is typically zero for
1693 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1694 // Count == -1 then the array is unbounded and we do not emit
1695 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1696 // Count == 0, then the array has zero elements in which case we do not emit
1698 int64_t LowerBound = SR.getLo();
1699 int64_t DefaultLowerBound = getDefaultLowerBound();
1700 int64_t Count = SR.getCount();
1702 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1703 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1705 if (Count != -1 && Count != 0)
1706 // FIXME: An unbounded array should reference the expression that defines
1708 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1709 LowerBound + Count - 1);
1712 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1713 void CompileUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1715 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1717 // Emit the element type.
1718 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1720 // Get an anonymous type for index type.
1721 // FIXME: This type should be passed down from the front end
1722 // as different languages may have different sizes for indexes.
1723 DIE *IdxTy = getIndexTyDie();
1725 // Construct an anonymous type for index type.
1726 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *CUDie.get());
1727 addString(IdxTy, dwarf::DW_AT_name, "int");
1728 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1729 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1730 dwarf::DW_ATE_signed);
1731 setIndexTyDie(IdxTy);
1734 // Add subranges to array type.
1735 DIArray Elements = CTy.getTypeArray();
1736 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1737 DIDescriptor Element = Elements.getElement(i);
1738 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1739 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1743 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1744 void CompileUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1745 DIArray Elements = CTy.getTypeArray();
1747 // Add enumerators to enumeration type.
1748 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1749 DIEnumerator Enum(Elements.getElement(i));
1750 if (Enum.isEnumerator()) {
1751 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1752 StringRef Name = Enum.getName();
1753 addString(Enumerator, dwarf::DW_AT_name, Name);
1754 int64_t Value = Enum.getEnumValue();
1755 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1759 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1761 addType(&Buffer, DTy);
1762 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1766 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1768 void CompileUnit::constructContainingTypeDIEs() {
1769 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1770 CE = ContainingTypeMap.end();
1772 DIE *SPDie = CI->first;
1773 DIDescriptor D(CI->second);
1776 DIE *NDie = getDIE(D);
1779 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1783 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1784 DIE *CompileUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1785 StringRef Name = DV.getName();
1787 // Define variable debug information entry.
1788 DIE *VariableDie = new DIE(DV.getTag());
1789 DbgVariable *AbsVar = DV.getAbstractVariable();
1790 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1792 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1795 addString(VariableDie, dwarf::DW_AT_name, Name);
1796 addSourceLine(VariableDie, DV.getVariable());
1797 addType(VariableDie, DV.getType());
1800 if (DV.isArtificial())
1801 addFlag(VariableDie, dwarf::DW_AT_artificial);
1803 if (isScopeAbstract) {
1804 DV.setDIE(VariableDie);
1808 // Add variable address.
1810 unsigned Offset = DV.getDotDebugLocOffset();
1811 if (Offset != ~0U) {
1812 addLabel(VariableDie, dwarf::DW_AT_location,
1813 DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1814 : dwarf::DW_FORM_data4,
1815 Asm->GetTempSymbol("debug_loc", Offset));
1816 DV.setDIE(VariableDie);
1820 // Check if variable is described by a DBG_VALUE instruction.
1821 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1822 assert(DVInsn->getNumOperands() == 3);
1823 if (DVInsn->getOperand(0).isReg()) {
1824 const MachineOperand RegOp = DVInsn->getOperand(0);
1825 // If the second operand is an immediate, this is an indirect value.
1826 if (DVInsn->getOperand(1).isImm()) {
1827 MachineLocation Location(RegOp.getReg(),
1828 DVInsn->getOperand(1).getImm());
1829 addVariableAddress(DV, VariableDie, Location);
1830 } else if (RegOp.getReg())
1831 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1832 } else if (DVInsn->getOperand(0).isImm())
1833 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1834 else if (DVInsn->getOperand(0).isFPImm())
1835 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1836 else if (DVInsn->getOperand(0).isCImm())
1837 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1838 isUnsignedDIType(DD, DV.getType()));
1840 DV.setDIE(VariableDie);
1843 // .. else use frame index.
1844 int FI = DV.getFrameIndex();
1846 unsigned FrameReg = 0;
1847 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1848 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1849 MachineLocation Location(FrameReg, Offset);
1850 addVariableAddress(DV, VariableDie, Location);
1854 DV.setDIE(VariableDie);
1858 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1859 void CompileUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1860 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1861 StringRef Name = DT.getName();
1863 addString(MemberDie, dwarf::DW_AT_name, Name);
1865 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1867 addSourceLine(MemberDie, DT);
1869 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1870 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1872 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1874 // For C++, virtual base classes are not at fixed offset. Use following
1875 // expression to extract appropriate offset from vtable.
1876 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1878 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1879 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1880 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1881 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1882 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1883 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1884 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1885 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1887 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1889 uint64_t Size = DT.getSizeInBits();
1890 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1891 uint64_t OffsetInBytes;
1893 if (Size != FieldSize) {
1895 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1896 getBaseTypeSize(DD, DT) >> 3);
1897 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1899 uint64_t Offset = DT.getOffsetInBits();
1900 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1901 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1902 uint64_t FieldOffset = (HiMark - FieldSize);
1903 Offset -= FieldOffset;
1905 // Maybe we need to work from the other end.
1906 if (Asm->getDataLayout().isLittleEndian())
1907 Offset = FieldSize - (Offset + Size);
1908 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1910 // Here WD_AT_data_member_location points to the anonymous
1911 // field that includes this bit field.
1912 OffsetInBytes = FieldOffset >> 3;
1914 // This is not a bitfield.
1915 OffsetInBytes = DT.getOffsetInBits() >> 3;
1916 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None, OffsetInBytes);
1919 if (DT.isProtected())
1920 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1921 dwarf::DW_ACCESS_protected);
1922 else if (DT.isPrivate())
1923 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1924 dwarf::DW_ACCESS_private);
1925 // Otherwise C++ member and base classes are considered public.
1927 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1928 dwarf::DW_ACCESS_public);
1930 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1931 dwarf::DW_VIRTUALITY_virtual);
1933 // Objective-C properties.
1934 if (MDNode *PNode = DT.getObjCProperty())
1935 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1936 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1939 if (DT.isArtificial())
1940 addFlag(MemberDie, dwarf::DW_AT_artificial);
1943 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1944 DIE *CompileUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1948 // Construct the context before querying for the existence of the DIE in case
1949 // such construction creates the DIE.
1950 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1951 assert(dwarf::isType(ContextDIE->getTag()) &&
1952 "Static member should belong to a type.");
1954 DIE *StaticMemberDIE = getDIE(DT);
1955 if (StaticMemberDIE)
1956 return StaticMemberDIE;
1958 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1960 DIType Ty = resolve(DT.getTypeDerivedFrom());
1962 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1963 addType(StaticMemberDIE, Ty);
1964 addSourceLine(StaticMemberDIE, DT);
1965 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1966 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1968 // FIXME: We could omit private if the parent is a class_type, and
1969 // public if the parent is something else.
1970 if (DT.isProtected())
1971 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1972 dwarf::DW_ACCESS_protected);
1973 else if (DT.isPrivate())
1974 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1975 dwarf::DW_ACCESS_private);
1977 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1978 dwarf::DW_ACCESS_public);
1980 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1981 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1982 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1983 addConstantFPValue(StaticMemberDIE, CFP);
1985 return StaticMemberDIE;
1988 void CompileUnit::emitHeader(const MCSection *ASection,
1989 const MCSymbol *ASectionSym) {
1990 Asm->OutStreamer.AddComment("DWARF version number");
1991 Asm->EmitInt16(DD->getDwarfVersion());
1992 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1993 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1995 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1996 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());