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/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.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"
35 /// CompileUnit - Compile unit constructor.
36 CompileUnit::CompileUnit(unsigned UID, unsigned L, DIE *D, const MDNode *N,
37 AsmPrinter *A, DwarfDebug *DW, DwarfUnits *DWU)
38 : UniqueID(UID), Language(L), CUDie(D), Asm(A), DD(DW), DU(DWU),
39 IndexTyDie(0), DebugInfoOffset(0) {
40 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
44 /// ~CompileUnit - Destructor for compile unit.
45 CompileUnit::~CompileUnit() {
46 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
47 DIEBlocks[j]->~DIEBlock();
50 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
51 /// information entry.
52 DIEEntry *CompileUnit::createDIEEntry(DIE *Entry) {
53 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
57 /// getDefaultLowerBound - Return the default lower bound for an array. If the
58 /// DWARF version doesn't handle the language, return -1.
59 int64_t CompileUnit::getDefaultLowerBound() const {
64 case dwarf::DW_LANG_C89:
65 case dwarf::DW_LANG_C99:
66 case dwarf::DW_LANG_C:
67 case dwarf::DW_LANG_C_plus_plus:
68 case dwarf::DW_LANG_ObjC:
69 case dwarf::DW_LANG_ObjC_plus_plus:
72 case dwarf::DW_LANG_Fortran77:
73 case dwarf::DW_LANG_Fortran90:
74 case dwarf::DW_LANG_Fortran95:
77 // The languages below have valid values only if the DWARF version >= 4.
78 case dwarf::DW_LANG_Java:
79 case dwarf::DW_LANG_Python:
80 case dwarf::DW_LANG_UPC:
81 case dwarf::DW_LANG_D:
82 if (dwarf::DWARF_VERSION >= 4)
86 case dwarf::DW_LANG_Ada83:
87 case dwarf::DW_LANG_Ada95:
88 case dwarf::DW_LANG_Cobol74:
89 case dwarf::DW_LANG_Cobol85:
90 case dwarf::DW_LANG_Modula2:
91 case dwarf::DW_LANG_Pascal83:
92 case dwarf::DW_LANG_PLI:
93 if (dwarf::DWARF_VERSION >= 4)
101 /// addFlag - Add a flag that is true.
102 void CompileUnit::addFlag(DIE *Die, unsigned Attribute) {
103 if (!DD->useDarwinGDBCompat())
104 Die->addValue(Attribute, dwarf::DW_FORM_flag_present,
107 addUInt(Die, Attribute, dwarf::DW_FORM_flag, 1);
110 /// addUInt - Add an unsigned integer attribute data and value.
112 void CompileUnit::addUInt(DIE *Die, unsigned Attribute,
113 unsigned Form, uint64_t Integer) {
114 if (!Form) Form = DIEInteger::BestForm(false, Integer);
115 DIEValue *Value = Integer == 1 ?
116 DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer);
117 Die->addValue(Attribute, Form, Value);
120 /// addSInt - Add an signed integer attribute data and value.
122 void CompileUnit::addSInt(DIE *Die, unsigned Attribute,
123 unsigned Form, int64_t Integer) {
124 if (!Form) Form = DIEInteger::BestForm(true, Integer);
125 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
126 Die->addValue(Attribute, Form, Value);
129 /// addString - Add a string attribute data and value. We always emit a
130 /// reference to the string pool instead of immediate strings so that DIEs have
131 /// more predictable sizes. In the case of split dwarf we emit an index
132 /// into another table which gets us the static offset into the string
134 void CompileUnit::addString(DIE *Die, unsigned Attribute, StringRef String) {
135 if (!DD->useSplitDwarf()) {
136 MCSymbol *Symb = DU->getStringPoolEntry(String);
138 if (Asm->needsRelocationsForDwarfStringPool())
139 Value = new (DIEValueAllocator) DIELabel(Symb, Asm->OutContext);
141 MCSymbol *StringPool = DU->getStringPoolSym();
142 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
144 Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
146 unsigned idx = DU->getStringPoolIndex(String);
147 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
148 Die->addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Value);
152 /// addLocalString - Add a string attribute data and value. This is guaranteed
153 /// to be in the local string pool instead of indirected.
154 void CompileUnit::addLocalString(DIE *Die, unsigned Attribute,
156 MCSymbol *Symb = DU->getStringPoolEntry(String);
158 if (Asm->needsRelocationsForDwarfStringPool())
159 Value = new (DIEValueAllocator) DIELabel(Symb, Asm->OutContext);
161 MCSymbol *StringPool = DU->getStringPoolSym();
162 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
164 Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
167 /// addLabel - Add a Dwarf label attribute data and value.
169 void CompileUnit::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
170 const MCSymbolRefExpr *Label) {
171 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
172 Die->addValue(Attribute, Form, Value);
175 void CompileUnit::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
176 const MCSymbol *Label) {
177 addLabel(Die, Attribute, Form, MCSymbolRefExpr::Create(Label, Asm->OutContext));
180 /// addLabelAddress - Add a dwarf label attribute data and value using
181 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
183 void CompileUnit::addLabelAddress(DIE *Die, unsigned Attribute,
185 if (!DD->useSplitDwarf()) {
187 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label, Asm->OutContext);
188 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
190 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
191 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
194 unsigned idx = DU->getAddrPoolIndex(Label);
195 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
196 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
200 /// addOpAddress - Add a dwarf op address data and value using the
201 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
203 void CompileUnit::addOpAddress(DIE *Die, const MCSymbol *Sym) {
205 if (!DD->useSplitDwarf()) {
206 addUInt(Die, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
207 addLabel(Die, 0, dwarf::DW_FORM_udata, Sym);
209 unsigned idx = DU->getAddrPoolIndex(Sym);
210 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
211 addUInt(Die, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
212 Die->addValue(0, dwarf::DW_FORM_GNU_addr_index, Value);
216 /// addDelta - Add a label delta attribute data and value.
218 void CompileUnit::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
219 const MCSymbol *Hi, const MCSymbol *Lo) {
220 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
221 Die->addValue(Attribute, Form, Value);
224 /// addDIEEntry - Add a DIE attribute data and value.
226 void CompileUnit::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
228 Die->addValue(Attribute, Form, createDIEEntry(Entry));
231 /// addBlock - Add block data.
233 void CompileUnit::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
235 Block->ComputeSize(Asm);
236 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
237 Die->addValue(Attribute, Block->BestForm(), Block);
240 /// addSourceLine - Add location information to specified debug information
242 void CompileUnit::addSourceLine(DIE *Die, DIVariable V) {
247 unsigned Line = V.getLineNumber();
250 unsigned FileID = DD->getOrCreateSourceID(V.getContext().getFilename(),
251 V.getContext().getDirectory(),
253 assert(FileID && "Invalid file id");
254 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
255 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
258 /// addSourceLine - Add location information to specified debug information
260 void CompileUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
261 // Verify global variable.
265 unsigned Line = G.getLineNumber();
268 unsigned FileID = DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(),
270 assert(FileID && "Invalid file id");
271 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
272 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
275 /// addSourceLine - Add location information to specified debug information
277 void CompileUnit::addSourceLine(DIE *Die, DISubprogram SP) {
278 // Verify subprogram.
282 // If the line number is 0, don't add it.
283 unsigned Line = SP.getLineNumber();
287 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(),
288 SP.getDirectory(), getUniqueID());
289 assert(FileID && "Invalid file id");
290 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
291 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
294 /// addSourceLine - Add location information to specified debug information
296 void CompileUnit::addSourceLine(DIE *Die, DIType Ty) {
301 unsigned Line = Ty.getLineNumber();
304 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(),
305 Ty.getDirectory(), getUniqueID());
306 assert(FileID && "Invalid file id");
307 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
308 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
311 /// addSourceLine - Add location information to specified debug information
313 void CompileUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
318 unsigned Line = Ty.getLineNumber();
321 DIFile File = Ty.getFile();
322 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
323 File.getDirectory(), getUniqueID());
324 assert(FileID && "Invalid file id");
325 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
326 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
329 /// addSourceLine - Add location information to specified debug information
331 void CompileUnit::addSourceLine(DIE *Die, DINameSpace NS) {
336 unsigned Line = NS.getLineNumber();
339 StringRef FN = NS.getFilename();
341 unsigned FileID = DD->getOrCreateSourceID(FN, NS.getDirectory(),
343 assert(FileID && "Invalid file id");
344 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
345 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
348 /// addVariableAddress - Add DW_AT_location attribute for a
349 /// DbgVariable based on provided MachineLocation.
350 void CompileUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
351 MachineLocation Location) {
352 if (DV.variableHasComplexAddress())
353 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
354 else if (DV.isBlockByrefVariable())
355 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
357 addAddress(Die, dwarf::DW_AT_location, Location,
358 DV.getVariable().isIndirect());
361 /// addRegisterOp - Add register operand.
362 void CompileUnit::addRegisterOp(DIE *TheDie, unsigned Reg) {
363 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
364 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
366 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
368 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
369 addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
373 /// addRegisterOffset - Add register offset.
374 void CompileUnit::addRegisterOffset(DIE *TheDie, unsigned Reg,
376 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
377 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
378 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
379 if (Reg == TRI->getFrameRegister(*Asm->MF))
380 // If variable offset is based in frame register then use fbreg.
381 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
383 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
385 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
386 addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
388 addSInt(TheDie, 0, dwarf::DW_FORM_sdata, Offset);
391 /// addAddress - Add an address attribute to a die based on the location
393 void CompileUnit::addAddress(DIE *Die, unsigned Attribute,
394 const MachineLocation &Location, bool Indirect) {
395 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
397 if (Location.isReg() && !Indirect)
398 addRegisterOp(Block, Location.getReg());
400 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
401 if (Indirect && !Location.isReg()) {
402 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
406 // Now attach the location information to the DIE.
407 addBlock(Die, Attribute, 0, Block);
410 /// addComplexAddress - Start with the address based on the location provided,
411 /// and generate the DWARF information necessary to find the actual variable
412 /// given the extra address information encoded in the DIVariable, starting from
413 /// the starting location. Add the DWARF information to the die.
415 void CompileUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
417 const MachineLocation &Location) {
418 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
419 unsigned N = DV.getNumAddrElements();
421 if (Location.isReg()) {
422 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
423 // If first address element is OpPlus then emit
424 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
425 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
428 addRegisterOp(Block, Location.getReg());
431 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
434 uint64_t Element = DV.getAddrElement(i);
435 if (Element == DIBuilder::OpPlus) {
436 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
437 addUInt(Block, 0, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
438 } else if (Element == DIBuilder::OpDeref) {
439 if (!Location.isReg())
440 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
441 } else llvm_unreachable("unknown DIBuilder Opcode");
444 // Now attach the location information to the DIE.
445 addBlock(Die, Attribute, 0, Block);
448 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
449 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
450 gives the variable VarName either the struct, or a pointer to the struct, as
451 its type. This is necessary for various behind-the-scenes things the
452 compiler needs to do with by-reference variables in Blocks.
454 However, as far as the original *programmer* is concerned, the variable
455 should still have type 'SomeType', as originally declared.
457 The function getBlockByrefType dives into the __Block_byref_x_VarName
458 struct to find the original type of the variable, which is then assigned to
459 the variable's Debug Information Entry as its real type. So far, so good.
460 However now the debugger will expect the variable VarName to have the type
461 SomeType. So we need the location attribute for the variable to be an
462 expression that explains to the debugger how to navigate through the
463 pointers and struct to find the actual variable of type SomeType.
465 The following function does just that. We start by getting
466 the "normal" location for the variable. This will be the location
467 of either the struct __Block_byref_x_VarName or the pointer to the
468 struct __Block_byref_x_VarName.
470 The struct will look something like:
472 struct __Block_byref_x_VarName {
474 struct __Block_byref_x_VarName *forwarding;
475 ... <various other fields>
477 ... <maybe more fields>
480 If we are given the struct directly (as our starting point) we
481 need to tell the debugger to:
483 1). Add the offset of the forwarding field.
485 2). Follow that pointer to get the real __Block_byref_x_VarName
486 struct to use (the real one may have been copied onto the heap).
488 3). Add the offset for the field VarName, to find the actual variable.
490 If we started with a pointer to the struct, then we need to
491 dereference that pointer first, before the other steps.
492 Translating this into DWARF ops, we will need to append the following
493 to the current location description for the variable:
495 DW_OP_deref -- optional, if we start with a pointer
496 DW_OP_plus_uconst <forward_fld_offset>
498 DW_OP_plus_uconst <varName_fld_offset>
500 That is what this function does. */
502 /// addBlockByrefAddress - Start with the address based on the location
503 /// provided, and generate the DWARF information necessary to find the
504 /// actual Block variable (navigating the Block struct) based on the
505 /// starting location. Add the DWARF information to the die. For
506 /// more information, read large comment just above here.
508 void CompileUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
510 const MachineLocation &Location) {
511 DIType Ty = DV.getType();
513 unsigned Tag = Ty.getTag();
514 bool isPointer = false;
516 StringRef varName = DV.getName();
518 if (Tag == dwarf::DW_TAG_pointer_type) {
519 DIDerivedType DTy = DIDerivedType(Ty);
520 TmpTy = DTy.getTypeDerivedFrom();
524 DICompositeType blockStruct = DICompositeType(TmpTy);
526 // Find the __forwarding field and the variable field in the __Block_byref
528 DIArray Fields = blockStruct.getTypeArray();
529 DIDescriptor varField = DIDescriptor();
530 DIDescriptor forwardingField = DIDescriptor();
532 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
533 DIDescriptor Element = Fields.getElement(i);
534 DIDerivedType DT = DIDerivedType(Element);
535 StringRef fieldName = DT.getName();
536 if (fieldName == "__forwarding")
537 forwardingField = Element;
538 else if (fieldName == varName)
542 // Get the offsets for the forwarding field and the variable field.
543 unsigned forwardingFieldOffset =
544 DIDerivedType(forwardingField).getOffsetInBits() >> 3;
545 unsigned varFieldOffset =
546 DIDerivedType(varField).getOffsetInBits() >> 3;
548 // Decode the original location, and use that as the start of the byref
549 // variable's location.
550 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
552 if (Location.isReg())
553 addRegisterOp(Block, Location.getReg());
555 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
557 // If we started with a pointer to the __Block_byref... struct, then
558 // the first thing we need to do is dereference the pointer (DW_OP_deref).
560 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
562 // Next add the offset for the '__forwarding' field:
563 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
564 // adding the offset if it's 0.
565 if (forwardingFieldOffset > 0) {
566 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
567 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
570 // Now dereference the __forwarding field to get to the real __Block_byref
571 // struct: DW_OP_deref.
572 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
574 // Now that we've got the real __Block_byref... struct, add the offset
575 // for the variable's field to get to the location of the actual variable:
576 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
577 if (varFieldOffset > 0) {
578 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
579 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
582 // Now attach the location information to the DIE.
583 addBlock(Die, Attribute, 0, Block);
586 /// isTypeSigned - Return true if the type is signed.
587 static bool isTypeSigned(DIType Ty, int *SizeInBits) {
588 if (Ty.isDerivedType())
589 return isTypeSigned(DIDerivedType(Ty).getTypeDerivedFrom(), SizeInBits);
590 if (Ty.isBasicType())
591 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed
592 || DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
593 *SizeInBits = Ty.getSizeInBits();
599 /// addConstantValue - Add constant value entry in variable DIE.
600 bool CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
602 // FIXME: This is a bit conservative/simple - it emits negative values at
603 // their maximum bit width which is a bit unfortunate (& doesn't prefer
604 // udata/sdata over dataN as suggested by the DWARF spec)
605 assert(MO.isImm() && "Invalid machine operand!");
606 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
608 bool SignedConstant = isTypeSigned(Ty, &SizeInBits);
609 unsigned Form = SignedConstant ? dwarf::DW_FORM_sdata : dwarf::DW_FORM_udata;
610 switch (SizeInBits) {
611 case 8: Form = dwarf::DW_FORM_data1; break;
612 case 16: Form = dwarf::DW_FORM_data2; break;
613 case 32: Form = dwarf::DW_FORM_data4; break;
614 case 64: Form = dwarf::DW_FORM_data8; break;
617 SignedConstant ? addSInt(Block, 0, Form, MO.getImm())
618 : addUInt(Block, 0, Form, MO.getImm());
620 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
624 /// addConstantFPValue - Add constant value entry in variable DIE.
625 bool CompileUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
626 assert (MO.isFPImm() && "Invalid machine operand!");
627 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
628 APFloat FPImm = MO.getFPImm()->getValueAPF();
630 // Get the raw data form of the floating point.
631 const APInt FltVal = FPImm.bitcastToAPInt();
632 const char *FltPtr = (const char*)FltVal.getRawData();
634 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
635 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
636 int Incr = (LittleEndian ? 1 : -1);
637 int Start = (LittleEndian ? 0 : NumBytes - 1);
638 int Stop = (LittleEndian ? NumBytes : -1);
640 // Output the constant to DWARF one byte at a time.
641 for (; Start != Stop; Start += Incr)
642 addUInt(Block, 0, dwarf::DW_FORM_data1,
643 (unsigned char)0xFF & FltPtr[Start]);
645 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
649 /// addConstantFPValue - Add constant value entry in variable DIE.
650 bool CompileUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
651 return addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), false);
654 /// addConstantValue - Add constant value entry in variable DIE.
655 bool CompileUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
657 return addConstantValue(Die, CI->getValue(), Unsigned);
660 // addConstantValue - Add constant value entry in variable DIE.
661 bool CompileUnit::addConstantValue(DIE *Die, const APInt &Val,
663 unsigned CIBitWidth = Val.getBitWidth();
664 if (CIBitWidth <= 64) {
666 switch (CIBitWidth) {
667 case 8: form = dwarf::DW_FORM_data1; break;
668 case 16: form = dwarf::DW_FORM_data2; break;
669 case 32: form = dwarf::DW_FORM_data4; break;
670 case 64: form = dwarf::DW_FORM_data8; break;
672 form = Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata;
675 addUInt(Die, dwarf::DW_AT_const_value, form, Val.getZExtValue());
677 addSInt(Die, dwarf::DW_AT_const_value, form, Val.getSExtValue());
681 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
683 // Get the raw data form of the large APInt.
684 const uint64_t *Ptr64 = Val.getRawData();
686 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
687 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
689 // Output the constant to DWARF one byte at a time.
690 for (int i = 0; i < NumBytes; i++) {
693 c = Ptr64[i / 8] >> (8 * (i & 7));
695 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
696 addUInt(Block, 0, dwarf::DW_FORM_data1, c);
699 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
703 /// addTemplateParams - Add template parameters into buffer.
704 void CompileUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
705 // Add template parameters.
706 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
707 DIDescriptor Element = TParams.getElement(i);
708 if (Element.isTemplateTypeParameter())
709 Buffer.addChild(getOrCreateTemplateTypeParameterDIE(
710 DITemplateTypeParameter(Element)));
711 else if (Element.isTemplateValueParameter())
712 Buffer.addChild(getOrCreateTemplateValueParameterDIE(
713 DITemplateValueParameter(Element)));
717 /// getOrCreateContextDIE - Get context owner's DIE.
718 DIE *CompileUnit::getOrCreateContextDIE(DIDescriptor Context) {
719 if (Context.isType())
720 return getOrCreateTypeDIE(DIType(Context));
721 else if (Context.isNameSpace())
722 return getOrCreateNameSpace(DINameSpace(Context));
723 else if (Context.isSubprogram())
724 return getOrCreateSubprogramDIE(DISubprogram(Context));
726 return getDIE(Context);
729 /// addToContextOwner - Add Die into the list of its context owner's children.
730 void CompileUnit::addToContextOwner(DIE *Die, DIDescriptor Context) {
731 if (DIE *ContextDIE = getOrCreateContextDIE(Context))
732 ContextDIE->addChild(Die);
737 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
739 DIE *CompileUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
743 DIE *TyDIE = getDIE(Ty);
748 TyDIE = new DIE(dwarf::DW_TAG_base_type);
749 insertDIE(Ty, TyDIE);
750 if (Ty.isBasicType())
751 constructTypeDIE(*TyDIE, DIBasicType(Ty));
752 else if (Ty.isCompositeType())
753 constructTypeDIE(*TyDIE, DICompositeType(Ty));
755 assert(Ty.isDerivedType() && "Unknown kind of DIType");
756 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
758 // If this is a named finished type then include it in the list of types
759 // for the accelerator tables.
760 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
761 bool IsImplementation = 0;
762 if (Ty.isCompositeType()) {
763 DICompositeType CT(Ty);
764 // A runtime language of 0 actually means C/C++ and that any
765 // non-negative value is some version of Objective-C/C++.
766 IsImplementation = (CT.getRunTimeLang() == 0) ||
767 CT.isObjcClassComplete();
769 unsigned Flags = IsImplementation ?
770 DwarfAccelTable::eTypeFlagClassIsImplementation : 0;
771 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
774 addToContextOwner(TyDIE, Ty.getContext());
778 /// addType - Add a new type attribute to the specified entity.
779 void CompileUnit::addType(DIE *Entity, DIType Ty, unsigned Attribute) {
783 // Check for pre-existence.
784 DIEEntry *Entry = getDIEEntry(Ty);
785 // If it exists then use the existing value.
787 Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
792 DIE *Buffer = getOrCreateTypeDIE(Ty);
795 Entry = createDIEEntry(Buffer);
796 insertDIEEntry(Ty, Entry);
797 Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
799 // If this is a complete composite type then include it in the
800 // list of global types.
804 /// addGlobalType - Add a new global type to the compile unit.
806 void CompileUnit::addGlobalType(DIType Ty) {
807 DIDescriptor Context = Ty.getContext();
808 if (Ty.isCompositeType() && !Ty.getName().empty() && !Ty.isForwardDecl()
809 && (!Context || Context.isCompileUnit() || Context.isFile()
810 || Context.isNameSpace()))
811 if (DIEEntry *Entry = getDIEEntry(Ty))
812 GlobalTypes[Ty.getName()] = Entry->getEntry();
815 /// addPubTypes - Add type for pubtypes section.
816 void CompileUnit::addPubTypes(DISubprogram SP) {
817 DICompositeType SPTy = SP.getType();
818 unsigned SPTag = SPTy.getTag();
819 if (SPTag != dwarf::DW_TAG_subroutine_type)
822 DIArray Args = SPTy.getTypeArray();
823 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
824 DIType ATy(Args.getElement(i));
831 /// constructTypeDIE - Construct basic type die from DIBasicType.
832 void CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
833 // Get core information.
834 StringRef Name = BTy.getName();
835 // Add name if not anonymous or intermediate type.
837 addString(&Buffer, dwarf::DW_AT_name, Name);
839 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type) {
840 Buffer.setTag(dwarf::DW_TAG_unspecified_type);
841 // Unspecified types has only name, nothing else.
845 Buffer.setTag(dwarf::DW_TAG_base_type);
846 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
849 uint64_t Size = BTy.getSizeInBits() >> 3;
850 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
853 /// constructTypeDIE - Construct derived type die from DIDerivedType.
854 void CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
855 // Get core information.
856 StringRef Name = DTy.getName();
857 uint64_t Size = DTy.getSizeInBits() >> 3;
858 unsigned Tag = DTy.getTag();
860 // FIXME - Workaround for templates.
861 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
865 // Map to main type, void will not have a type.
866 DIType FromTy = DTy.getTypeDerivedFrom();
867 addType(&Buffer, FromTy);
869 // Add name if not anonymous or intermediate type.
871 addString(&Buffer, dwarf::DW_AT_name, Name);
873 // Add size if non-zero (derived types might be zero-sized.)
874 if (Size && Tag != dwarf::DW_TAG_pointer_type)
875 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
877 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
878 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
879 getOrCreateTypeDIE(DTy.getClassType()));
880 // Add source line info if available and TyDesc is not a forward declaration.
881 if (!DTy.isForwardDecl())
882 addSourceLine(&Buffer, DTy);
885 /// constructTypeDIE - Construct type DIE from DICompositeType.
886 void CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
887 // Get core information.
888 StringRef Name = CTy.getName();
890 uint64_t Size = CTy.getSizeInBits() >> 3;
891 unsigned Tag = CTy.getTag();
895 case dwarf::DW_TAG_array_type:
896 constructArrayTypeDIE(Buffer, &CTy);
898 case dwarf::DW_TAG_enumeration_type: {
899 DIArray Elements = CTy.getTypeArray();
901 // Add enumerators to enumeration type.
902 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
904 DIDescriptor Enum(Elements.getElement(i));
905 if (Enum.isEnumerator()) {
906 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
907 Buffer.addChild(ElemDie);
910 DIType DTy = CTy.getTypeDerivedFrom();
912 addType(&Buffer, DTy);
913 addUInt(&Buffer, dwarf::DW_AT_enum_class, dwarf::DW_FORM_flag, 1);
917 case dwarf::DW_TAG_subroutine_type: {
919 DIArray Elements = CTy.getTypeArray();
920 DIDescriptor RTy = Elements.getElement(0);
921 addType(&Buffer, DIType(RTy));
923 bool isPrototyped = true;
925 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
926 DIDescriptor Ty = Elements.getElement(i);
927 if (Ty.isUnspecifiedParameter()) {
928 DIE *Arg = new DIE(dwarf::DW_TAG_unspecified_parameters);
929 Buffer.addChild(Arg);
930 isPrototyped = false;
932 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
933 addType(Arg, DIType(Ty));
934 if (DIType(Ty).isArtificial())
935 addFlag(Arg, dwarf::DW_AT_artificial);
936 Buffer.addChild(Arg);
939 // Add prototype flag if we're dealing with a C language and the
940 // function has been prototyped.
942 (Language == dwarf::DW_LANG_C89 ||
943 Language == dwarf::DW_LANG_C99 ||
944 Language == dwarf::DW_LANG_ObjC))
945 addFlag(&Buffer, dwarf::DW_AT_prototyped);
948 case dwarf::DW_TAG_structure_type:
949 case dwarf::DW_TAG_union_type:
950 case dwarf::DW_TAG_class_type: {
951 // Add elements to structure type.
952 DIArray Elements = CTy.getTypeArray();
954 // A forward struct declared type may not have elements available.
955 unsigned N = Elements.getNumElements();
959 // Add elements to structure type.
960 for (unsigned i = 0; i < N; ++i) {
961 DIDescriptor Element = Elements.getElement(i);
963 if (Element.isSubprogram()) {
964 DISubprogram SP(Element);
965 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
966 if (SP.isProtected())
967 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
968 dwarf::DW_ACCESS_protected);
969 else if (SP.isPrivate())
970 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
971 dwarf::DW_ACCESS_private);
973 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
974 dwarf::DW_ACCESS_public);
976 addFlag(ElemDie, dwarf::DW_AT_explicit);
977 } else if (Element.isDerivedType()) {
978 DIDerivedType DDTy(Element);
979 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
980 ElemDie = new DIE(dwarf::DW_TAG_friend);
981 addType(ElemDie, DDTy.getTypeDerivedFrom(), dwarf::DW_AT_friend);
982 } else if (DDTy.isStaticMember())
983 ElemDie = createStaticMemberDIE(DDTy);
985 ElemDie = createMemberDIE(DDTy);
986 } else if (Element.isObjCProperty()) {
987 DIObjCProperty Property(Element);
988 ElemDie = new DIE(Property.getTag());
989 StringRef PropertyName = Property.getObjCPropertyName();
990 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
991 addType(ElemDie, Property.getType());
992 addSourceLine(ElemDie, Property);
993 StringRef GetterName = Property.getObjCPropertyGetterName();
994 if (!GetterName.empty())
995 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
996 StringRef SetterName = Property.getObjCPropertySetterName();
997 if (!SetterName.empty())
998 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
999 unsigned PropertyAttributes = 0;
1000 if (Property.isReadOnlyObjCProperty())
1001 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1002 if (Property.isReadWriteObjCProperty())
1003 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1004 if (Property.isAssignObjCProperty())
1005 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1006 if (Property.isRetainObjCProperty())
1007 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1008 if (Property.isCopyObjCProperty())
1009 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1010 if (Property.isNonAtomicObjCProperty())
1011 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1012 if (PropertyAttributes)
1013 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, 0,
1014 PropertyAttributes);
1016 DIEEntry *Entry = getDIEEntry(Element);
1018 Entry = createDIEEntry(ElemDie);
1019 insertDIEEntry(Element, Entry);
1023 Buffer.addChild(ElemDie);
1026 if (CTy.isAppleBlockExtension())
1027 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1029 DICompositeType ContainingType = CTy.getContainingType();
1030 if (DIDescriptor(ContainingType).isCompositeType())
1031 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1032 getOrCreateTypeDIE(DIType(ContainingType)));
1034 DIDescriptor Context = CTy.getContext();
1035 addToContextOwner(&Buffer, Context);
1038 if (CTy.isObjcClassComplete())
1039 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1041 // Add template parameters to a class, structure or union types.
1042 // FIXME: The support isn't in the metadata for this yet.
1043 if (Tag == dwarf::DW_TAG_class_type ||
1044 Tag == dwarf::DW_TAG_structure_type ||
1045 Tag == dwarf::DW_TAG_union_type)
1046 addTemplateParams(Buffer, CTy.getTemplateParams());
1054 // Add name if not anonymous or intermediate type.
1056 addString(&Buffer, dwarf::DW_AT_name, Name);
1058 if (Tag == dwarf::DW_TAG_enumeration_type ||
1059 Tag == dwarf::DW_TAG_class_type ||
1060 Tag == dwarf::DW_TAG_structure_type ||
1061 Tag == dwarf::DW_TAG_union_type) {
1062 // Add size if non-zero (derived types might be zero-sized.)
1063 // TODO: Do we care about size for enum forward declarations?
1065 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1066 else if (!CTy.isForwardDecl())
1067 // Add zero size if it is not a forward declaration.
1068 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1070 // If we're a forward decl, say so.
1071 if (CTy.isForwardDecl())
1072 addFlag(&Buffer, dwarf::DW_AT_declaration);
1074 // Add source line info if available.
1075 if (!CTy.isForwardDecl())
1076 addSourceLine(&Buffer, CTy);
1078 // No harm in adding the runtime language to the declaration.
1079 unsigned RLang = CTy.getRunTimeLang();
1081 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1082 dwarf::DW_FORM_data1, RLang);
1086 /// getOrCreateTemplateTypeParameterDIE - Find existing DIE or create new DIE
1087 /// for the given DITemplateTypeParameter.
1089 CompileUnit::getOrCreateTemplateTypeParameterDIE(DITemplateTypeParameter TP) {
1090 DIE *ParamDIE = getDIE(TP);
1094 ParamDIE = new DIE(dwarf::DW_TAG_template_type_parameter);
1095 addType(ParamDIE, TP.getType());
1096 if (!TP.getName().empty())
1097 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1101 /// getOrCreateTemplateValueParameterDIE - Find existing DIE or create new DIE
1102 /// for the given DITemplateValueParameter.
1104 CompileUnit::getOrCreateTemplateValueParameterDIE(DITemplateValueParameter TPV){
1105 DIE *ParamDIE = getDIE(TPV);
1109 ParamDIE = new DIE(TPV.getTag());
1110 addType(ParamDIE, TPV.getType());
1111 if (!TPV.getName().empty())
1112 addString(ParamDIE, dwarf::DW_AT_name, TPV.getName());
1113 if (Value *Val = TPV.getValue()) {
1114 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1115 addConstantValue(ParamDIE, CI, TPV.getType().isUnsignedDIType());
1116 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1117 // For declaration non-type template parameters (such as global values and
1119 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1120 addOpAddress(Block, Asm->Mang->getSymbol(GV));
1121 // Emit DW_OP_stack_value to use the address as the immediate value of the
1122 // parameter, rather than a pointer to it.
1123 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1124 addBlock(ParamDIE, dwarf::DW_AT_location, 0, Block);
1125 } else if (TPV.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1126 assert(isa<MDString>(Val));
1127 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1128 cast<MDString>(Val)->getString());
1129 } else if (TPV.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1130 assert(isa<MDNode>(Val));
1131 DIArray A(cast<MDNode>(Val));
1132 addTemplateParams(*ParamDIE, A);
1139 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1140 DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
1141 DIE *NDie = getDIE(NS);
1144 NDie = new DIE(dwarf::DW_TAG_namespace);
1145 insertDIE(NS, NDie);
1146 if (!NS.getName().empty()) {
1147 addString(NDie, dwarf::DW_AT_name, NS.getName());
1148 addAccelNamespace(NS.getName(), NDie);
1150 addAccelNamespace("(anonymous namespace)", NDie);
1151 addSourceLine(NDie, NS);
1152 addToContextOwner(NDie, NS.getContext());
1156 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1157 DIE *CompileUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1158 DIE *SPDie = getDIE(SP);
1162 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1164 // DW_TAG_inlined_subroutine may refer to this DIE.
1165 insertDIE(SP, SPDie);
1167 DISubprogram SPDecl = SP.getFunctionDeclaration();
1168 DIE *DeclDie = NULL;
1169 if (SPDecl.isSubprogram()) {
1170 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1173 // Add to context owner.
1174 addToContextOwner(SPDie, SP.getContext());
1176 // Add function template parameters.
1177 addTemplateParams(*SPDie, SP.getTemplateParams());
1179 // Unfortunately this code needs to stay here instead of below the
1180 // AT_specification code in order to work around a bug in older
1181 // gdbs that requires the linkage name to resolve multiple template
1183 // TODO: Remove this set of code when we get rid of the old gdb
1185 StringRef LinkageName = SP.getLinkageName();
1186 if (!LinkageName.empty() && DD->useDarwinGDBCompat())
1187 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1188 GlobalValue::getRealLinkageName(LinkageName));
1190 // If this DIE is going to refer declaration info using AT_specification
1191 // then there is no need to add other attributes.
1193 // Refer function declaration directly.
1194 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1200 // Add the linkage name if we have one.
1201 if (!LinkageName.empty() && !DD->useDarwinGDBCompat())
1202 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1203 GlobalValue::getRealLinkageName(LinkageName));
1205 // Constructors and operators for anonymous aggregates do not have names.
1206 if (!SP.getName().empty())
1207 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1209 addSourceLine(SPDie, SP);
1211 // Add the prototype if we have a prototype and we have a C like
1213 if (SP.isPrototyped() &&
1214 (Language == dwarf::DW_LANG_C89 ||
1215 Language == dwarf::DW_LANG_C99 ||
1216 Language == dwarf::DW_LANG_ObjC))
1217 addFlag(SPDie, dwarf::DW_AT_prototyped);
1220 DICompositeType SPTy = SP.getType();
1221 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1222 "the type of a subprogram should be a subroutine");
1224 DIArray Args = SPTy.getTypeArray();
1225 addType(SPDie, DIType(Args.getElement(0)));
1227 unsigned VK = SP.getVirtuality();
1229 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1230 DIEBlock *Block = getDIEBlock();
1231 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1232 addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1233 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1234 ContainingTypeMap.insert(std::make_pair(SPDie,
1235 SP.getContainingType()));
1238 if (!SP.isDefinition()) {
1239 addFlag(SPDie, dwarf::DW_AT_declaration);
1241 // Add arguments. Do not add arguments for subprogram definition. They will
1242 // be handled while processing variables.
1243 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1244 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1245 DIType ATy = DIType(Args.getElement(i));
1247 if (ATy.isArtificial())
1248 addFlag(Arg, dwarf::DW_AT_artificial);
1249 SPDie->addChild(Arg);
1253 if (SP.isArtificial())
1254 addFlag(SPDie, dwarf::DW_AT_artificial);
1256 if (!SP.isLocalToUnit())
1257 addFlag(SPDie, dwarf::DW_AT_external);
1259 if (SP.isOptimized())
1260 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1262 if (unsigned isa = Asm->getISAEncoding()) {
1263 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1269 // Return const expression if value is a GEP to access merged global
1271 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1272 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1273 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1274 if (!CE || CE->getNumOperands() != 3 ||
1275 CE->getOpcode() != Instruction::GetElementPtr)
1278 // First operand points to a global struct.
1279 Value *Ptr = CE->getOperand(0);
1280 if (!isa<GlobalValue>(Ptr) ||
1281 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1284 // Second operand is zero.
1285 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1286 if (!CI || !CI->isZero())
1289 // Third operand is offset.
1290 if (!isa<ConstantInt>(CE->getOperand(2)))
1296 /// createGlobalVariableDIE - create global variable DIE.
1297 void CompileUnit::createGlobalVariableDIE(const MDNode *N) {
1298 // Check for pre-existence.
1302 DIGlobalVariable GV(N);
1306 DIDescriptor GVContext = GV.getContext();
1307 DIType GTy = GV.getType();
1309 // If this is a static data member definition, some attributes belong
1310 // to the declaration DIE.
1311 DIE *VariableDIE = NULL;
1312 bool IsStaticMember = false;
1313 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1314 if (SDMDecl.Verify()) {
1315 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1316 // We need the declaration DIE that is in the static member's class.
1317 // But that class might not exist in the DWARF yet.
1318 // Creating the class will create the static member decl DIE.
1319 getOrCreateContextDIE(SDMDecl.getContext());
1320 VariableDIE = getDIE(SDMDecl);
1321 assert(VariableDIE && "Static member decl has no context?");
1322 IsStaticMember = true;
1325 // If this is not a static data member definition, create the variable
1326 // DIE and add the initial set of attributes to it.
1328 VariableDIE = new DIE(GV.getTag());
1330 insertDIE(N, VariableDIE);
1332 // Add name and type.
1333 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1334 addType(VariableDIE, GTy);
1336 // Add scoping info.
1337 if (!GV.isLocalToUnit()) {
1338 addFlag(VariableDIE, dwarf::DW_AT_external);
1339 addGlobalName(GV.getName(), VariableDIE);
1342 // Add line number info.
1343 addSourceLine(VariableDIE, GV);
1344 // Add to context owner.
1345 addToContextOwner(VariableDIE, GVContext);
1349 bool addToAccelTable = false;
1350 DIE *VariableSpecDIE = NULL;
1351 bool isGlobalVariable = GV.getGlobal() != NULL;
1352 if (isGlobalVariable) {
1353 addToAccelTable = true;
1354 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1355 const MCSymbol *Sym = Asm->Mang->getSymbol(GV.getGlobal());
1356 if (GV.getGlobal()->isThreadLocal()) {
1357 // FIXME: Make this work with -gsplit-dwarf.
1358 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1359 assert((PointerSize == 4 || PointerSize == 8) &&
1360 "Add support for other sizes if necessary");
1361 // Based on GCC's support for TLS:
1362 // 1) Start with a constNu of the appropriate pointer size
1363 addUInt(Block, 0, dwarf::DW_FORM_data1,
1364 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1365 // 2) containing the (relocated) address of the TLS variable
1366 addLabel(Block, 0, dwarf::DW_FORM_udata,
1367 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1368 // 3) followed by a custom OP to tell the debugger about TLS (presumably)
1369 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_lo_user);
1371 addOpAddress(Block, Sym);
1372 // Do not create specification DIE if context is either compile unit
1374 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1375 !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1376 // Create specification DIE.
1377 VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1378 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1379 dwarf::DW_FORM_ref4, VariableDIE);
1380 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1381 // A static member's declaration is already flagged as such.
1382 if (!SDMDecl.Verify())
1383 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1384 addDie(VariableSpecDIE);
1386 addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1388 // Add linkage name.
1389 StringRef LinkageName = GV.getLinkageName();
1390 if (!LinkageName.empty()) {
1391 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1392 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1394 addString(IsStaticMember && VariableSpecDIE ?
1395 VariableSpecDIE : VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
1396 GlobalValue::getRealLinkageName(LinkageName));
1397 // In compatibility mode with older gdbs we put the linkage name on both
1398 // the TAG_variable DIE and on the TAG_member DIE.
1399 if (IsStaticMember && VariableSpecDIE && DD->useDarwinGDBCompat())
1400 addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
1401 GlobalValue::getRealLinkageName(LinkageName));
1403 } else if (const ConstantInt *CI =
1404 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1405 // AT_const_value was added when the static member was created. To avoid
1406 // emitting AT_const_value multiple times, we only add AT_const_value when
1407 // it is not a static member.
1408 if (!IsStaticMember)
1409 addConstantValue(VariableDIE, CI, GTy.isUnsignedDIType());
1410 } else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
1411 addToAccelTable = true;
1412 // GV is a merged global.
1413 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1414 Value *Ptr = CE->getOperand(0);
1415 addOpAddress(Block, Asm->Mang->getSymbol(cast<GlobalValue>(Ptr)));
1416 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1417 SmallVector<Value*, 3> Idx(CE->op_begin()+1, CE->op_end());
1418 addUInt(Block, 0, dwarf::DW_FORM_udata,
1419 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1420 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1421 addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1424 if (addToAccelTable) {
1425 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1426 addAccelName(GV.getName(), AddrDIE);
1428 // If the linkage name is different than the name, go ahead and output
1429 // that as well into the name table.
1430 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1431 addAccelName(GV.getLinkageName(), AddrDIE);
1435 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1436 void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR,
1438 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1439 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1441 // The LowerBound value defines the lower bounds which is typically zero for
1442 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1443 // Count == -1 then the array is unbounded and we do not emit
1444 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1445 // Count == 0, then the array has zero elements in which case we do not emit
1447 int64_t LowerBound = SR.getLo();
1448 int64_t DefaultLowerBound = getDefaultLowerBound();
1449 int64_t Count = SR.getCount();
1451 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1452 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, LowerBound);
1454 if (Count != -1 && Count != 0)
1455 // FIXME: An unbounded array should reference the expression that defines
1457 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, LowerBound + Count - 1);
1459 Buffer.addChild(DW_Subrange);
1462 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1463 void CompileUnit::constructArrayTypeDIE(DIE &Buffer,
1464 DICompositeType *CTy) {
1465 Buffer.setTag(dwarf::DW_TAG_array_type);
1466 if (CTy->isVector())
1467 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1469 // Emit derived type.
1470 addType(&Buffer, CTy->getTypeDerivedFrom());
1471 DIArray Elements = CTy->getTypeArray();
1473 // Get an anonymous type for index type.
1474 // FIXME: This type should be passed down from the front end
1475 // as different languages may have different sizes for indexes.
1476 DIE *IdxTy = getIndexTyDie();
1478 // Construct an anonymous type for index type.
1479 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1480 addString(IdxTy, dwarf::DW_AT_name, "int");
1481 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1482 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1483 dwarf::DW_ATE_signed);
1485 setIndexTyDie(IdxTy);
1488 // Add subranges to array type.
1489 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1490 DIDescriptor Element = Elements.getElement(i);
1491 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1492 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1496 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1497 DIE *CompileUnit::constructEnumTypeDIE(DIEnumerator ETy) {
1498 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1499 StringRef Name = ETy.getName();
1500 addString(Enumerator, dwarf::DW_AT_name, Name);
1501 int64_t Value = ETy.getEnumValue();
1502 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1506 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1508 void CompileUnit::constructContainingTypeDIEs() {
1509 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1510 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1511 DIE *SPDie = CI->first;
1512 const MDNode *N = CI->second;
1514 DIE *NDie = getDIE(N);
1515 if (!NDie) continue;
1516 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1520 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1521 DIE *CompileUnit::constructVariableDIE(DbgVariable *DV,
1522 bool isScopeAbstract) {
1523 StringRef Name = DV->getName();
1525 // Translate tag to proper Dwarf tag.
1526 unsigned Tag = DV->getTag();
1528 // Define variable debug information entry.
1529 DIE *VariableDie = new DIE(Tag);
1530 DbgVariable *AbsVar = DV->getAbstractVariable();
1531 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1533 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1534 dwarf::DW_FORM_ref4, AbsDIE);
1536 addString(VariableDie, dwarf::DW_AT_name, Name);
1537 addSourceLine(VariableDie, DV->getVariable());
1538 addType(VariableDie, DV->getType());
1541 if (DV->isArtificial())
1542 addFlag(VariableDie, dwarf::DW_AT_artificial);
1544 if (isScopeAbstract) {
1545 DV->setDIE(VariableDie);
1549 // Add variable address.
1551 unsigned Offset = DV->getDotDebugLocOffset();
1552 if (Offset != ~0U) {
1553 addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
1554 Asm->GetTempSymbol("debug_loc", Offset));
1555 DV->setDIE(VariableDie);
1559 // Check if variable is described by a DBG_VALUE instruction.
1560 if (const MachineInstr *DVInsn = DV->getMInsn()) {
1561 bool updated = false;
1562 assert(DVInsn->getNumOperands() == 3);
1563 if (DVInsn->getOperand(0).isReg()) {
1564 const MachineOperand RegOp = DVInsn->getOperand(0);
1565 if (int64_t Offset = DVInsn->getOperand(1).getImm()) {
1566 MachineLocation Location(RegOp.getReg(), Offset);
1567 addVariableAddress(*DV, VariableDie, Location);
1568 } else if (RegOp.getReg())
1569 addVariableAddress(*DV, VariableDie, MachineLocation(RegOp.getReg()));
1571 } else if (DVInsn->getOperand(0).isImm())
1573 addConstantValue(VariableDie, DVInsn->getOperand(0), DV->getType());
1574 else if (DVInsn->getOperand(0).isFPImm())
1575 updated = addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1576 else if (DVInsn->getOperand(0).isCImm())
1577 updated = addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1578 DV->getType().isUnsignedDIType());
1580 // If variableDie is not updated then DBG_VALUE instruction does not
1581 // have valid variable info.
1585 DV->setDIE(VariableDie);
1588 // .. else use frame index.
1589 int FI = DV->getFrameIndex();
1591 unsigned FrameReg = 0;
1592 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1594 TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1595 MachineLocation Location(FrameReg, Offset);
1596 addVariableAddress(*DV, VariableDie, Location);
1600 DV->setDIE(VariableDie);
1604 /// createMemberDIE - Create new member DIE.
1605 DIE *CompileUnit::createMemberDIE(DIDerivedType DT) {
1606 DIE *MemberDie = new DIE(DT.getTag());
1607 StringRef Name = DT.getName();
1609 addString(MemberDie, dwarf::DW_AT_name, Name);
1611 addType(MemberDie, DT.getTypeDerivedFrom());
1613 addSourceLine(MemberDie, DT);
1615 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1616 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1618 uint64_t Size = DT.getSizeInBits();
1619 uint64_t FieldSize = DT.getOriginalTypeSize();
1621 if (Size != FieldSize) {
1623 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1624 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1626 uint64_t Offset = DT.getOffsetInBits();
1627 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1628 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1629 uint64_t FieldOffset = (HiMark - FieldSize);
1630 Offset -= FieldOffset;
1632 // Maybe we need to work from the other end.
1633 if (Asm->getDataLayout().isLittleEndian())
1634 Offset = FieldSize - (Offset + Size);
1635 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1637 // Here WD_AT_data_member_location points to the anonymous
1638 // field that includes this bit field.
1639 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1642 // This is not a bitfield.
1643 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1645 if (DT.getTag() == dwarf::DW_TAG_inheritance
1646 && DT.isVirtual()) {
1648 // For C++, virtual base classes are not at fixed offset. Use following
1649 // expression to extract appropriate offset from vtable.
1650 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1652 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1653 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1654 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1655 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1656 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1657 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1658 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1659 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1661 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1664 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1666 if (DT.isProtected())
1667 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1668 dwarf::DW_ACCESS_protected);
1669 else if (DT.isPrivate())
1670 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1671 dwarf::DW_ACCESS_private);
1672 // Otherwise C++ member and base classes are considered public.
1674 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1675 dwarf::DW_ACCESS_public);
1677 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1678 dwarf::DW_VIRTUALITY_virtual);
1680 // Objective-C properties.
1681 if (MDNode *PNode = DT.getObjCProperty())
1682 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1683 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1686 if (DT.isArtificial())
1687 addFlag(MemberDie, dwarf::DW_AT_artificial);
1692 /// createStaticMemberDIE - Create new DIE for C++ static member.
1693 DIE *CompileUnit::createStaticMemberDIE(const DIDerivedType DT) {
1697 DIE *StaticMemberDIE = new DIE(DT.getTag());
1698 DIType Ty = DT.getTypeDerivedFrom();
1700 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1701 addType(StaticMemberDIE, Ty);
1702 addSourceLine(StaticMemberDIE, DT);
1703 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1704 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1706 // FIXME: We could omit private if the parent is a class_type, and
1707 // public if the parent is something else.
1708 if (DT.isProtected())
1709 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1710 dwarf::DW_ACCESS_protected);
1711 else if (DT.isPrivate())
1712 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1713 dwarf::DW_ACCESS_private);
1715 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1716 dwarf::DW_ACCESS_public);
1718 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1719 addConstantValue(StaticMemberDIE, CI, Ty.isUnsignedDIType());
1720 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1721 addConstantFPValue(StaticMemberDIE, CFP);
1723 insertDIE(DT, StaticMemberDIE);
1724 return StaticMemberDIE;