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/TargetRegisterInfo.h"
34 /// CompileUnit - Compile unit constructor.
35 CompileUnit::CompileUnit(unsigned UID, unsigned L, DIE *D, AsmPrinter *A,
36 DwarfDebug *DW, DwarfUnits *DWU)
37 : UniqueID(UID), Language(L), CUDie(D), Asm(A), DD(DW), DU(DWU),
39 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
42 /// ~CompileUnit - Destructor for compile unit.
43 CompileUnit::~CompileUnit() {
44 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
45 DIEBlocks[j]->~DIEBlock();
48 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
49 /// information entry.
50 DIEEntry *CompileUnit::createDIEEntry(DIE *Entry) {
51 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
55 /// getDefaultLowerBound - Return the default lower bound for an array. If the
56 /// DWARF version doesn't handle the language, return -1.
57 int64_t CompileUnit::getDefaultLowerBound() const {
62 case dwarf::DW_LANG_C89:
63 case dwarf::DW_LANG_C99:
64 case dwarf::DW_LANG_C:
65 case dwarf::DW_LANG_C_plus_plus:
66 case dwarf::DW_LANG_ObjC:
67 case dwarf::DW_LANG_ObjC_plus_plus:
70 case dwarf::DW_LANG_Fortran77:
71 case dwarf::DW_LANG_Fortran90:
72 case dwarf::DW_LANG_Fortran95:
75 // The languages below have valid values only if the DWARF version >= 4.
76 case dwarf::DW_LANG_Java:
77 case dwarf::DW_LANG_Python:
78 case dwarf::DW_LANG_UPC:
79 case dwarf::DW_LANG_D:
80 if (dwarf::DWARF_VERSION >= 4)
84 case dwarf::DW_LANG_Ada83:
85 case dwarf::DW_LANG_Ada95:
86 case dwarf::DW_LANG_Cobol74:
87 case dwarf::DW_LANG_Cobol85:
88 case dwarf::DW_LANG_Modula2:
89 case dwarf::DW_LANG_Pascal83:
90 case dwarf::DW_LANG_PLI:
91 if (dwarf::DWARF_VERSION >= 4)
99 /// addFlag - Add a flag that is true.
100 void CompileUnit::addFlag(DIE *Die, unsigned Attribute) {
101 if (!DD->useDarwinGDBCompat())
102 Die->addValue(Attribute, dwarf::DW_FORM_flag_present,
105 addUInt(Die, Attribute, dwarf::DW_FORM_flag, 1);
108 /// addUInt - Add an unsigned integer attribute data and value.
110 void CompileUnit::addUInt(DIE *Die, unsigned Attribute,
111 unsigned Form, uint64_t Integer) {
112 if (!Form) Form = DIEInteger::BestForm(false, Integer);
113 DIEValue *Value = Integer == 1 ?
114 DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer);
115 Die->addValue(Attribute, Form, Value);
118 /// addSInt - Add an signed integer attribute data and value.
120 void CompileUnit::addSInt(DIE *Die, unsigned Attribute,
121 unsigned Form, int64_t Integer) {
122 if (!Form) Form = DIEInteger::BestForm(true, Integer);
123 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
124 Die->addValue(Attribute, Form, Value);
127 /// addString - Add a string attribute data and value. We always emit a
128 /// reference to the string pool instead of immediate strings so that DIEs have
129 /// more predictable sizes. In the case of split dwarf we emit an index
130 /// into another table which gets us the static offset into the string
132 void CompileUnit::addString(DIE *Die, unsigned Attribute, StringRef String) {
133 if (!DD->useSplitDwarf()) {
134 MCSymbol *Symb = DU->getStringPoolEntry(String);
136 if (Asm->needsRelocationsForDwarfStringPool())
137 Value = new (DIEValueAllocator) DIELabel(Symb);
139 MCSymbol *StringPool = DU->getStringPoolSym();
140 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
142 Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
144 unsigned idx = DU->getStringPoolIndex(String);
145 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
146 Die->addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Value);
150 /// addLocalString - Add a string attribute data and value. This is guaranteed
151 /// to be in the local string pool instead of indirected.
152 void CompileUnit::addLocalString(DIE *Die, unsigned Attribute,
154 MCSymbol *Symb = DU->getStringPoolEntry(String);
156 if (Asm->needsRelocationsForDwarfStringPool())
157 Value = new (DIEValueAllocator) DIELabel(Symb);
159 MCSymbol *StringPool = DU->getStringPoolSym();
160 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
162 Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
165 /// addLabel - Add a Dwarf label attribute data and value.
167 void CompileUnit::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
168 const MCSymbol *Label) {
169 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
170 Die->addValue(Attribute, Form, Value);
173 /// addLabelAddress - Add a dwarf label attribute data and value using
174 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
176 void CompileUnit::addLabelAddress(DIE *Die, unsigned Attribute,
178 if (!DD->useSplitDwarf()) {
180 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
181 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
183 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
184 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
187 unsigned idx = DU->getAddrPoolIndex(Label);
188 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
189 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
193 /// addOpAddress - Add a dwarf op address data and value using the
194 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
196 void CompileUnit::addOpAddress(DIE *Die, MCSymbol *Sym) {
198 if (!DD->useSplitDwarf()) {
199 addUInt(Die, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
200 addLabel(Die, 0, dwarf::DW_FORM_udata, Sym);
202 unsigned idx = DU->getAddrPoolIndex(Sym);
203 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
204 addUInt(Die, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
205 Die->addValue(0, dwarf::DW_FORM_GNU_addr_index, Value);
209 /// addDelta - Add a label delta attribute data and value.
211 void CompileUnit::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
212 const MCSymbol *Hi, const MCSymbol *Lo) {
213 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
214 Die->addValue(Attribute, Form, Value);
217 /// addDIEEntry - Add a DIE attribute data and value.
219 void CompileUnit::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
221 Die->addValue(Attribute, Form, createDIEEntry(Entry));
224 /// addBlock - Add block data.
226 void CompileUnit::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
228 Block->ComputeSize(Asm);
229 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
230 Die->addValue(Attribute, Block->BestForm(), Block);
233 /// addSourceLine - Add location information to specified debug information
235 void CompileUnit::addSourceLine(DIE *Die, DIVariable V) {
240 unsigned Line = V.getLineNumber();
243 unsigned FileID = DD->getOrCreateSourceID(V.getContext().getFilename(),
244 V.getContext().getDirectory());
245 assert(FileID && "Invalid file id");
246 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
247 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
250 /// addSourceLine - Add location information to specified debug information
252 void CompileUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
253 // Verify global variable.
257 unsigned Line = G.getLineNumber();
260 unsigned FileID = DD->getOrCreateSourceID(G.getFilename(), G.getDirectory());
261 assert(FileID && "Invalid file id");
262 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
263 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
266 /// addSourceLine - Add location information to specified debug information
268 void CompileUnit::addSourceLine(DIE *Die, DISubprogram SP) {
269 // Verify subprogram.
273 // If the line number is 0, don't add it.
274 unsigned Line = SP.getLineNumber();
278 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(),
280 assert(FileID && "Invalid file id");
281 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
282 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
285 /// addSourceLine - Add location information to specified debug information
287 void CompileUnit::addSourceLine(DIE *Die, DIType Ty) {
292 unsigned Line = Ty.getLineNumber();
295 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(),
297 assert(FileID && "Invalid file id");
298 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
299 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
302 /// addSourceLine - Add location information to specified debug information
304 void CompileUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
309 unsigned Line = Ty.getLineNumber();
312 DIFile File = Ty.getFile();
313 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
314 File.getDirectory());
315 assert(FileID && "Invalid file id");
316 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
317 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
320 /// addSourceLine - Add location information to specified debug information
322 void CompileUnit::addSourceLine(DIE *Die, DINameSpace NS) {
327 unsigned Line = NS.getLineNumber();
330 StringRef FN = NS.getFilename();
332 unsigned FileID = DD->getOrCreateSourceID(FN, NS.getDirectory());
333 assert(FileID && "Invalid file id");
334 addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
335 addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
338 /// addVariableAddress - Add DW_AT_location attribute for a
339 /// DbgVariable based on provided MachineLocation.
340 void CompileUnit::addVariableAddress(DbgVariable *&DV, DIE *Die,
341 MachineLocation Location) {
342 if (DV->variableHasComplexAddress())
343 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
344 else if (DV->isBlockByrefVariable())
345 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
347 addAddress(Die, dwarf::DW_AT_location, Location);
350 /// addRegisterOp - Add register operand.
351 void CompileUnit::addRegisterOp(DIE *TheDie, unsigned Reg) {
352 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
353 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
355 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
357 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
358 addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
362 /// addRegisterOffset - Add register offset.
363 void CompileUnit::addRegisterOffset(DIE *TheDie, unsigned Reg,
365 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
366 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
367 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
368 if (Reg == TRI->getFrameRegister(*Asm->MF))
369 // If variable offset is based in frame register then use fbreg.
370 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
372 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
374 addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
375 addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
377 addSInt(TheDie, 0, dwarf::DW_FORM_sdata, Offset);
380 /// addAddress - Add an address attribute to a die based on the location
382 void CompileUnit::addAddress(DIE *Die, unsigned Attribute,
383 const MachineLocation &Location) {
384 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
386 if (Location.isReg())
387 addRegisterOp(Block, Location.getReg());
389 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
391 // Now attach the location information to the DIE.
392 addBlock(Die, Attribute, 0, Block);
395 /// addComplexAddress - Start with the address based on the location provided,
396 /// and generate the DWARF information necessary to find the actual variable
397 /// given the extra address information encoded in the DIVariable, starting from
398 /// the starting location. Add the DWARF information to the die.
400 void CompileUnit::addComplexAddress(DbgVariable *&DV, DIE *Die,
402 const MachineLocation &Location) {
403 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
404 unsigned N = DV->getNumAddrElements();
406 if (Location.isReg()) {
407 if (N >= 2 && DV->getAddrElement(0) == DIBuilder::OpPlus) {
408 // If first address element is OpPlus then emit
409 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
410 addRegisterOffset(Block, Location.getReg(), DV->getAddrElement(1));
413 addRegisterOp(Block, Location.getReg());
416 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
419 uint64_t Element = DV->getAddrElement(i);
420 if (Element == DIBuilder::OpPlus) {
421 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
422 addUInt(Block, 0, dwarf::DW_FORM_udata, DV->getAddrElement(++i));
423 } else if (Element == DIBuilder::OpDeref) {
424 if (!Location.isReg())
425 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
426 } else llvm_unreachable("unknown DIBuilder Opcode");
429 // Now attach the location information to the DIE.
430 addBlock(Die, Attribute, 0, Block);
433 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
434 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
435 gives the variable VarName either the struct, or a pointer to the struct, as
436 its type. This is necessary for various behind-the-scenes things the
437 compiler needs to do with by-reference variables in Blocks.
439 However, as far as the original *programmer* is concerned, the variable
440 should still have type 'SomeType', as originally declared.
442 The function getBlockByrefType dives into the __Block_byref_x_VarName
443 struct to find the original type of the variable, which is then assigned to
444 the variable's Debug Information Entry as its real type. So far, so good.
445 However now the debugger will expect the variable VarName to have the type
446 SomeType. So we need the location attribute for the variable to be an
447 expression that explains to the debugger how to navigate through the
448 pointers and struct to find the actual variable of type SomeType.
450 The following function does just that. We start by getting
451 the "normal" location for the variable. This will be the location
452 of either the struct __Block_byref_x_VarName or the pointer to the
453 struct __Block_byref_x_VarName.
455 The struct will look something like:
457 struct __Block_byref_x_VarName {
459 struct __Block_byref_x_VarName *forwarding;
460 ... <various other fields>
462 ... <maybe more fields>
465 If we are given the struct directly (as our starting point) we
466 need to tell the debugger to:
468 1). Add the offset of the forwarding field.
470 2). Follow that pointer to get the real __Block_byref_x_VarName
471 struct to use (the real one may have been copied onto the heap).
473 3). Add the offset for the field VarName, to find the actual variable.
475 If we started with a pointer to the struct, then we need to
476 dereference that pointer first, before the other steps.
477 Translating this into DWARF ops, we will need to append the following
478 to the current location description for the variable:
480 DW_OP_deref -- optional, if we start with a pointer
481 DW_OP_plus_uconst <forward_fld_offset>
483 DW_OP_plus_uconst <varName_fld_offset>
485 That is what this function does. */
487 /// addBlockByrefAddress - Start with the address based on the location
488 /// provided, and generate the DWARF information necessary to find the
489 /// actual Block variable (navigating the Block struct) based on the
490 /// starting location. Add the DWARF information to the die. For
491 /// more information, read large comment just above here.
493 void CompileUnit::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
495 const MachineLocation &Location) {
496 DIType Ty = DV->getType();
498 unsigned Tag = Ty.getTag();
499 bool isPointer = false;
501 StringRef varName = DV->getName();
503 if (Tag == dwarf::DW_TAG_pointer_type) {
504 DIDerivedType DTy = DIDerivedType(Ty);
505 TmpTy = DTy.getTypeDerivedFrom();
509 DICompositeType blockStruct = DICompositeType(TmpTy);
511 // Find the __forwarding field and the variable field in the __Block_byref
513 DIArray Fields = blockStruct.getTypeArray();
514 DIDescriptor varField = DIDescriptor();
515 DIDescriptor forwardingField = DIDescriptor();
517 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
518 DIDescriptor Element = Fields.getElement(i);
519 DIDerivedType DT = DIDerivedType(Element);
520 StringRef fieldName = DT.getName();
521 if (fieldName == "__forwarding")
522 forwardingField = Element;
523 else if (fieldName == varName)
527 // Get the offsets for the forwarding field and the variable field.
528 unsigned forwardingFieldOffset =
529 DIDerivedType(forwardingField).getOffsetInBits() >> 3;
530 unsigned varFieldOffset =
531 DIDerivedType(varField).getOffsetInBits() >> 3;
533 // Decode the original location, and use that as the start of the byref
534 // variable's location.
535 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
537 if (Location.isReg())
538 addRegisterOp(Block, Location.getReg());
540 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
542 // If we started with a pointer to the __Block_byref... struct, then
543 // the first thing we need to do is dereference the pointer (DW_OP_deref).
545 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
547 // Next add the offset for the '__forwarding' field:
548 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
549 // adding the offset if it's 0.
550 if (forwardingFieldOffset > 0) {
551 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
552 addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
555 // Now dereference the __forwarding field to get to the real __Block_byref
556 // struct: DW_OP_deref.
557 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
559 // Now that we've got the real __Block_byref... struct, add the offset
560 // for the variable's field to get to the location of the actual variable:
561 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
562 if (varFieldOffset > 0) {
563 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
564 addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
567 // Now attach the location information to the DIE.
568 addBlock(Die, Attribute, 0, Block);
571 /// isTypeSigned - Return true if the type is signed.
572 static bool isTypeSigned(DIType Ty, int *SizeInBits) {
573 if (Ty.isDerivedType())
574 return isTypeSigned(DIDerivedType(Ty).getTypeDerivedFrom(), SizeInBits);
575 if (Ty.isBasicType())
576 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed
577 || DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
578 *SizeInBits = Ty.getSizeInBits();
584 /// addConstantValue - Add constant value entry in variable DIE.
585 bool CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
587 assert(MO.isImm() && "Invalid machine operand!");
588 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
590 bool SignedConstant = isTypeSigned(Ty, &SizeInBits);
591 unsigned Form = SignedConstant ? dwarf::DW_FORM_sdata : dwarf::DW_FORM_udata;
592 switch (SizeInBits) {
593 case 8: Form = dwarf::DW_FORM_data1; break;
594 case 16: Form = dwarf::DW_FORM_data2; break;
595 case 32: Form = dwarf::DW_FORM_data4; break;
596 case 64: Form = dwarf::DW_FORM_data8; break;
599 SignedConstant ? addSInt(Block, 0, Form, MO.getImm())
600 : addUInt(Block, 0, Form, MO.getImm());
602 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
606 /// addConstantFPValue - Add constant value entry in variable DIE.
607 bool CompileUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
608 assert (MO.isFPImm() && "Invalid machine operand!");
609 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
610 APFloat FPImm = MO.getFPImm()->getValueAPF();
612 // Get the raw data form of the floating point.
613 const APInt FltVal = FPImm.bitcastToAPInt();
614 const char *FltPtr = (const char*)FltVal.getRawData();
616 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
617 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
618 int Incr = (LittleEndian ? 1 : -1);
619 int Start = (LittleEndian ? 0 : NumBytes - 1);
620 int Stop = (LittleEndian ? NumBytes : -1);
622 // Output the constant to DWARF one byte at a time.
623 for (; Start != Stop; Start += Incr)
624 addUInt(Block, 0, dwarf::DW_FORM_data1,
625 (unsigned char)0xFF & FltPtr[Start]);
627 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
631 /// addConstantFPValue - Add constant value entry in variable DIE.
632 bool CompileUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
633 return addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), false);
636 /// addConstantValue - Add constant value entry in variable DIE.
637 bool CompileUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
639 return addConstantValue(Die, CI->getValue(), Unsigned);
642 // addConstantValue - Add constant value entry in variable DIE.
643 bool CompileUnit::addConstantValue(DIE *Die, const APInt &Val,
645 unsigned CIBitWidth = Val.getBitWidth();
646 if (CIBitWidth <= 64) {
648 switch (CIBitWidth) {
649 case 8: form = dwarf::DW_FORM_data1; break;
650 case 16: form = dwarf::DW_FORM_data2; break;
651 case 32: form = dwarf::DW_FORM_data4; break;
652 case 64: form = dwarf::DW_FORM_data8; break;
654 form = Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata;
657 addUInt(Die, dwarf::DW_AT_const_value, form, Val.getZExtValue());
659 addSInt(Die, dwarf::DW_AT_const_value, form, Val.getSExtValue());
663 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
665 // Get the raw data form of the large APInt.
666 const uint64_t *Ptr64 = Val.getRawData();
668 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
669 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
671 // Output the constant to DWARF one byte at a time.
672 for (int i = 0; i < NumBytes; i++) {
675 c = Ptr64[i / 8] >> (8 * (i & 7));
677 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
678 addUInt(Block, 0, dwarf::DW_FORM_data1, c);
681 addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
685 /// addTemplateParams - Add template parameters in buffer.
686 void CompileUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
687 // Add template parameters.
688 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
689 DIDescriptor Element = TParams.getElement(i);
690 if (Element.isTemplateTypeParameter())
691 Buffer.addChild(getOrCreateTemplateTypeParameterDIE(
692 DITemplateTypeParameter(Element)));
693 else if (Element.isTemplateValueParameter())
694 Buffer.addChild(getOrCreateTemplateValueParameterDIE(
695 DITemplateValueParameter(Element)));
699 /// getOrCreateContextDIE - Get context owner's DIE.
700 DIE *CompileUnit::getOrCreateContextDIE(DIDescriptor Context) {
701 if (Context.isType())
702 return getOrCreateTypeDIE(DIType(Context));
703 else if (Context.isNameSpace())
704 return getOrCreateNameSpace(DINameSpace(Context));
705 else if (Context.isSubprogram())
706 return getOrCreateSubprogramDIE(DISubprogram(Context));
708 return getDIE(Context);
711 /// addToContextOwner - Add Die into the list of its context owner's children.
712 void CompileUnit::addToContextOwner(DIE *Die, DIDescriptor Context) {
713 if (DIE *ContextDIE = getOrCreateContextDIE(Context))
714 ContextDIE->addChild(Die);
719 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
721 DIE *CompileUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
725 DIE *TyDIE = getDIE(Ty);
730 TyDIE = new DIE(dwarf::DW_TAG_base_type);
731 insertDIE(Ty, TyDIE);
732 if (Ty.isBasicType())
733 constructTypeDIE(*TyDIE, DIBasicType(Ty));
734 else if (Ty.isCompositeType())
735 constructTypeDIE(*TyDIE, DICompositeType(Ty));
737 assert(Ty.isDerivedType() && "Unknown kind of DIType");
738 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
740 // If this is a named finished type then include it in the list of types
741 // for the accelerator tables.
742 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
743 bool IsImplementation = 0;
744 if (Ty.isCompositeType()) {
745 DICompositeType CT(Ty);
746 // A runtime language of 0 actually means C/C++ and that any
747 // non-negative value is some version of Objective-C/C++.
748 IsImplementation = (CT.getRunTimeLang() == 0) ||
749 CT.isObjcClassComplete();
751 unsigned Flags = IsImplementation ?
752 DwarfAccelTable::eTypeFlagClassIsImplementation : 0;
753 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
756 addToContextOwner(TyDIE, Ty.getContext());
760 /// addType - Add a new type attribute to the specified entity.
761 void CompileUnit::addType(DIE *Entity, DIType Ty, unsigned Attribute) {
765 // Check for pre-existence.
766 DIEEntry *Entry = getDIEEntry(Ty);
767 // If it exists then use the existing value.
769 Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
774 DIE *Buffer = getOrCreateTypeDIE(Ty);
777 Entry = createDIEEntry(Buffer);
778 insertDIEEntry(Ty, Entry);
779 Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
781 // If this is a complete composite type then include it in the
782 // list of global types.
786 /// addGlobalType - Add a new global type to the compile unit.
788 void CompileUnit::addGlobalType(DIType Ty) {
789 DIDescriptor Context = Ty.getContext();
790 if (Ty.isCompositeType() && !Ty.getName().empty() && !Ty.isForwardDecl()
791 && (!Context || Context.isCompileUnit() || Context.isFile()
792 || Context.isNameSpace()))
793 if (DIEEntry *Entry = getDIEEntry(Ty))
794 GlobalTypes[Ty.getName()] = Entry->getEntry();
797 /// addPubTypes - Add type for pubtypes section.
798 void CompileUnit::addPubTypes(DISubprogram SP) {
799 DICompositeType SPTy = SP.getType();
800 unsigned SPTag = SPTy.getTag();
801 if (SPTag != dwarf::DW_TAG_subroutine_type)
804 DIArray Args = SPTy.getTypeArray();
805 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
806 DIType ATy(Args.getElement(i));
813 /// constructTypeDIE - Construct basic type die from DIBasicType.
814 void CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
815 // Get core information.
816 StringRef Name = BTy.getName();
817 // Add name if not anonymous or intermediate type.
819 addString(&Buffer, dwarf::DW_AT_name, Name);
821 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type) {
822 Buffer.setTag(dwarf::DW_TAG_unspecified_type);
823 // Unspecified types has only name, nothing else.
827 Buffer.setTag(dwarf::DW_TAG_base_type);
828 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
831 uint64_t Size = BTy.getSizeInBits() >> 3;
832 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
835 /// constructTypeDIE - Construct derived type die from DIDerivedType.
836 void CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
837 // Get core information.
838 StringRef Name = DTy.getName();
839 uint64_t Size = DTy.getSizeInBits() >> 3;
840 unsigned Tag = DTy.getTag();
842 // FIXME - Workaround for templates.
843 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
847 // Map to main type, void will not have a type.
848 DIType FromTy = DTy.getTypeDerivedFrom();
849 addType(&Buffer, FromTy);
851 // Add name if not anonymous or intermediate type.
853 addString(&Buffer, dwarf::DW_AT_name, Name);
855 // Add size if non-zero (derived types might be zero-sized.)
856 if (Size && Tag != dwarf::DW_TAG_pointer_type)
857 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
859 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
860 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
861 getOrCreateTypeDIE(DTy.getClassType()));
862 // Add source line info if available and TyDesc is not a forward declaration.
863 if (!DTy.isForwardDecl())
864 addSourceLine(&Buffer, DTy);
867 /// constructTypeDIE - Construct type DIE from DICompositeType.
868 void CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
869 // Get core information.
870 StringRef Name = CTy.getName();
872 uint64_t Size = CTy.getSizeInBits() >> 3;
873 unsigned Tag = CTy.getTag();
877 case dwarf::DW_TAG_array_type:
878 constructArrayTypeDIE(Buffer, &CTy);
880 case dwarf::DW_TAG_enumeration_type: {
881 DIArray Elements = CTy.getTypeArray();
883 // Add enumerators to enumeration type.
884 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
886 DIDescriptor Enum(Elements.getElement(i));
887 if (Enum.isEnumerator()) {
888 ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
889 Buffer.addChild(ElemDie);
892 DIType DTy = CTy.getTypeDerivedFrom();
894 addType(&Buffer, DTy);
895 addUInt(&Buffer, dwarf::DW_AT_enum_class, dwarf::DW_FORM_flag, 1);
899 case dwarf::DW_TAG_subroutine_type: {
901 DIArray Elements = CTy.getTypeArray();
902 DIDescriptor RTy = Elements.getElement(0);
903 addType(&Buffer, DIType(RTy));
905 bool isPrototyped = true;
907 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
908 DIDescriptor Ty = Elements.getElement(i);
909 if (Ty.isUnspecifiedParameter()) {
910 DIE *Arg = new DIE(dwarf::DW_TAG_unspecified_parameters);
911 Buffer.addChild(Arg);
912 isPrototyped = false;
914 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
915 addType(Arg, DIType(Ty));
916 if (DIType(Ty).isArtificial())
917 addFlag(Arg, dwarf::DW_AT_artificial);
918 Buffer.addChild(Arg);
921 // Add prototype flag if we're dealing with a C language and the
922 // function has been prototyped.
924 (Language == dwarf::DW_LANG_C89 ||
925 Language == dwarf::DW_LANG_C99 ||
926 Language == dwarf::DW_LANG_ObjC))
927 addFlag(&Buffer, dwarf::DW_AT_prototyped);
930 case dwarf::DW_TAG_structure_type:
931 case dwarf::DW_TAG_union_type:
932 case dwarf::DW_TAG_class_type: {
933 // Add elements to structure type.
934 DIArray Elements = CTy.getTypeArray();
936 // A forward struct declared type may not have elements available.
937 unsigned N = Elements.getNumElements();
941 // Add elements to structure type.
942 for (unsigned i = 0; i < N; ++i) {
943 DIDescriptor Element = Elements.getElement(i);
945 if (Element.isSubprogram()) {
946 DISubprogram SP(Element);
947 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
948 if (SP.isProtected())
949 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
950 dwarf::DW_ACCESS_protected);
951 else if (SP.isPrivate())
952 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
953 dwarf::DW_ACCESS_private);
955 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
956 dwarf::DW_ACCESS_public);
958 addFlag(ElemDie, dwarf::DW_AT_explicit);
959 } else if (Element.isDerivedType()) {
960 DIDerivedType DDTy(Element);
961 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
962 ElemDie = new DIE(dwarf::DW_TAG_friend);
963 addType(ElemDie, DDTy.getTypeDerivedFrom(), dwarf::DW_AT_friend);
964 } else if (DDTy.isStaticMember())
965 ElemDie = createStaticMemberDIE(DDTy);
967 ElemDie = createMemberDIE(DDTy);
968 } else if (Element.isObjCProperty()) {
969 DIObjCProperty Property(Element);
970 ElemDie = new DIE(Property.getTag());
971 StringRef PropertyName = Property.getObjCPropertyName();
972 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
973 addType(ElemDie, Property.getType());
974 addSourceLine(ElemDie, Property);
975 StringRef GetterName = Property.getObjCPropertyGetterName();
976 if (!GetterName.empty())
977 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
978 StringRef SetterName = Property.getObjCPropertySetterName();
979 if (!SetterName.empty())
980 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
981 unsigned PropertyAttributes = 0;
982 if (Property.isReadOnlyObjCProperty())
983 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
984 if (Property.isReadWriteObjCProperty())
985 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
986 if (Property.isAssignObjCProperty())
987 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
988 if (Property.isRetainObjCProperty())
989 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
990 if (Property.isCopyObjCProperty())
991 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
992 if (Property.isNonAtomicObjCProperty())
993 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
994 if (PropertyAttributes)
995 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, 0,
998 DIEEntry *Entry = getDIEEntry(Element);
1000 Entry = createDIEEntry(ElemDie);
1001 insertDIEEntry(Element, Entry);
1005 Buffer.addChild(ElemDie);
1008 if (CTy.isAppleBlockExtension())
1009 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1011 DICompositeType ContainingType = CTy.getContainingType();
1012 if (DIDescriptor(ContainingType).isCompositeType())
1013 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1014 getOrCreateTypeDIE(DIType(ContainingType)));
1016 DIDescriptor Context = CTy.getContext();
1017 addToContextOwner(&Buffer, Context);
1020 if (CTy.isObjcClassComplete())
1021 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1023 // Add template parameters to a class, structure or union types.
1024 // FIXME: The support isn't in the metadata for this yet.
1025 if (Tag == dwarf::DW_TAG_class_type ||
1026 Tag == dwarf::DW_TAG_structure_type ||
1027 Tag == dwarf::DW_TAG_union_type)
1028 addTemplateParams(Buffer, CTy.getTemplateParams());
1036 // Add name if not anonymous or intermediate type.
1038 addString(&Buffer, dwarf::DW_AT_name, Name);
1040 if (Tag == dwarf::DW_TAG_enumeration_type ||
1041 Tag == dwarf::DW_TAG_class_type ||
1042 Tag == dwarf::DW_TAG_structure_type ||
1043 Tag == dwarf::DW_TAG_union_type) {
1044 // Add size if non-zero (derived types might be zero-sized.)
1045 // TODO: Do we care about size for enum forward declarations?
1047 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1048 else if (!CTy.isForwardDecl())
1049 // Add zero size if it is not a forward declaration.
1050 addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1052 // If we're a forward decl, say so.
1053 if (CTy.isForwardDecl())
1054 addFlag(&Buffer, dwarf::DW_AT_declaration);
1056 // Add source line info if available.
1057 if (!CTy.isForwardDecl())
1058 addSourceLine(&Buffer, CTy);
1060 // No harm in adding the runtime language to the declaration.
1061 unsigned RLang = CTy.getRunTimeLang();
1063 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1064 dwarf::DW_FORM_data1, RLang);
1068 /// getOrCreateTemplateTypeParameterDIE - Find existing DIE or create new DIE
1069 /// for the given DITemplateTypeParameter.
1071 CompileUnit::getOrCreateTemplateTypeParameterDIE(DITemplateTypeParameter TP) {
1072 DIE *ParamDIE = getDIE(TP);
1076 ParamDIE = new DIE(dwarf::DW_TAG_template_type_parameter);
1077 addType(ParamDIE, TP.getType());
1078 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1082 /// getOrCreateTemplateValueParameterDIE - Find existing DIE or create new DIE
1083 /// for the given DITemplateValueParameter.
1085 CompileUnit::getOrCreateTemplateValueParameterDIE(DITemplateValueParameter TPV){
1086 DIE *ParamDIE = getDIE(TPV);
1090 ParamDIE = new DIE(dwarf::DW_TAG_template_value_parameter);
1091 addType(ParamDIE, TPV.getType());
1092 if (!TPV.getName().empty())
1093 addString(ParamDIE, dwarf::DW_AT_name, TPV.getName());
1094 addUInt(ParamDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
1099 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1100 DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
1101 DIE *NDie = getDIE(NS);
1104 NDie = new DIE(dwarf::DW_TAG_namespace);
1105 insertDIE(NS, NDie);
1106 if (!NS.getName().empty()) {
1107 addString(NDie, dwarf::DW_AT_name, NS.getName());
1108 addAccelNamespace(NS.getName(), NDie);
1110 addAccelNamespace("(anonymous namespace)", NDie);
1111 addSourceLine(NDie, NS);
1112 addToContextOwner(NDie, NS.getContext());
1116 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1117 /// printer to not emit usual symbol prefix before the symbol name is used then
1118 /// return linkage name after skipping this special LLVM prefix.
1119 static StringRef getRealLinkageName(StringRef LinkageName) {
1121 if (LinkageName.startswith(StringRef(&One, 1)))
1122 return LinkageName.substr(1);
1126 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1127 DIE *CompileUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1128 DIE *SPDie = getDIE(SP);
1132 SPDie = new DIE(dwarf::DW_TAG_subprogram);
1134 // DW_TAG_inlined_subroutine may refer to this DIE.
1135 insertDIE(SP, SPDie);
1137 DISubprogram SPDecl = SP.getFunctionDeclaration();
1138 DIE *DeclDie = NULL;
1139 if (SPDecl.isSubprogram()) {
1140 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1143 // Add to context owner.
1144 addToContextOwner(SPDie, SP.getContext());
1146 // Add function template parameters.
1147 addTemplateParams(*SPDie, SP.getTemplateParams());
1149 // Unfortunately this code needs to stay here instead of below the
1150 // AT_specification code in order to work around a bug in older
1151 // gdbs that requires the linkage name to resolve multiple template
1153 // TODO: Remove this set of code when we get rid of the old gdb
1155 StringRef LinkageName = SP.getLinkageName();
1156 if (!LinkageName.empty() && DD->useDarwinGDBCompat())
1157 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1158 getRealLinkageName(LinkageName));
1160 // If this DIE is going to refer declaration info using AT_specification
1161 // then there is no need to add other attributes.
1163 // Refer function declaration directly.
1164 addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1170 // Add the linkage name if we have one.
1171 if (!LinkageName.empty() && !DD->useDarwinGDBCompat())
1172 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1173 getRealLinkageName(LinkageName));
1175 // Constructors and operators for anonymous aggregates do not have names.
1176 if (!SP.getName().empty())
1177 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1179 addSourceLine(SPDie, SP);
1181 // Add the prototype if we have a prototype and we have a C like
1183 if (SP.isPrototyped() &&
1184 (Language == dwarf::DW_LANG_C89 ||
1185 Language == dwarf::DW_LANG_C99 ||
1186 Language == dwarf::DW_LANG_ObjC))
1187 addFlag(SPDie, dwarf::DW_AT_prototyped);
1190 DICompositeType SPTy = SP.getType();
1191 DIArray Args = SPTy.getTypeArray();
1192 unsigned SPTag = SPTy.getTag();
1194 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1195 addType(SPDie, SPTy);
1197 addType(SPDie, DIType(Args.getElement(0)));
1199 unsigned VK = SP.getVirtuality();
1201 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1202 DIEBlock *Block = getDIEBlock();
1203 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1204 addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1205 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1206 ContainingTypeMap.insert(std::make_pair(SPDie,
1207 SP.getContainingType()));
1210 if (!SP.isDefinition()) {
1211 addFlag(SPDie, dwarf::DW_AT_declaration);
1213 // Add arguments. Do not add arguments for subprogram definition. They will
1214 // be handled while processing variables.
1215 DICompositeType SPTy = SP.getType();
1216 DIArray Args = SPTy.getTypeArray();
1217 unsigned SPTag = SPTy.getTag();
1219 if (SPTag == dwarf::DW_TAG_subroutine_type)
1220 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1221 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1222 DIType ATy = DIType(Args.getElement(i));
1224 if (ATy.isArtificial())
1225 addFlag(Arg, dwarf::DW_AT_artificial);
1226 SPDie->addChild(Arg);
1230 if (SP.isArtificial())
1231 addFlag(SPDie, dwarf::DW_AT_artificial);
1233 if (!SP.isLocalToUnit())
1234 addFlag(SPDie, dwarf::DW_AT_external);
1236 if (SP.isOptimized())
1237 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1239 if (unsigned isa = Asm->getISAEncoding()) {
1240 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1246 // Return const expression if value is a GEP to access merged global
1248 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1249 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1250 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1251 if (!CE || CE->getNumOperands() != 3 ||
1252 CE->getOpcode() != Instruction::GetElementPtr)
1255 // First operand points to a global struct.
1256 Value *Ptr = CE->getOperand(0);
1257 if (!isa<GlobalValue>(Ptr) ||
1258 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1261 // Second operand is zero.
1262 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1263 if (!CI || !CI->isZero())
1266 // Third operand is offset.
1267 if (!isa<ConstantInt>(CE->getOperand(2)))
1273 /// createGlobalVariableDIE - create global variable DIE.
1274 void CompileUnit::createGlobalVariableDIE(const MDNode *N) {
1275 // Check for pre-existence.
1279 DIGlobalVariable GV(N);
1283 DIDescriptor GVContext = GV.getContext();
1284 DIType GTy = GV.getType();
1286 // If this is a static data member definition, some attributes belong
1287 // to the declaration DIE.
1288 DIE *VariableDIE = NULL;
1289 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1290 if (SDMDecl.Verify()) {
1291 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1292 // We need the declaration DIE that is in the static member's class.
1293 // But that class might not exist in the DWARF yet.
1294 // Creating the class will create the static member decl DIE.
1295 getOrCreateContextDIE(SDMDecl.getContext());
1296 VariableDIE = getDIE(SDMDecl);
1297 assert(VariableDIE && "Static member decl has no context?");
1300 // If this is not a static data member definition, create the variable
1301 // DIE and add the initial set of attributes to it.
1303 VariableDIE = new DIE(GV.getTag());
1305 insertDIE(N, VariableDIE);
1307 // Add name and type.
1308 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1309 addType(VariableDIE, GTy);
1311 // Add scoping info.
1312 if (!GV.isLocalToUnit())
1313 addFlag(VariableDIE, dwarf::DW_AT_external);
1315 // Add line number info.
1316 addSourceLine(VariableDIE, GV);
1317 // Add to context owner.
1318 addToContextOwner(VariableDIE, GVContext);
1322 bool addToAccelTable = false;
1323 DIE *VariableSpecDIE = NULL;
1324 bool isGlobalVariable = GV.getGlobal() != NULL;
1325 if (isGlobalVariable) {
1326 addToAccelTable = true;
1327 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1328 addOpAddress(Block, Asm->Mang->getSymbol(GV.getGlobal()));
1329 // Do not create specification DIE if context is either compile unit
1331 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1332 !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1333 // Create specification DIE.
1334 VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1335 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1336 dwarf::DW_FORM_ref4, VariableDIE);
1337 addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1338 // A static member's declaration is already flagged as such.
1339 if (!SDMDecl.Verify())
1340 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1341 addDie(VariableSpecDIE);
1343 addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1345 // Add linkage name.
1346 StringRef LinkageName = GV.getLinkageName();
1347 if (!LinkageName.empty() && isGlobalVariable)
1348 addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
1349 getRealLinkageName(LinkageName));
1350 } else if (const ConstantInt *CI =
1351 dyn_cast_or_null<ConstantInt>(GV.getConstant()))
1352 addConstantValue(VariableDIE, CI, GTy.isUnsignedDIType());
1353 else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
1354 addToAccelTable = true;
1355 // GV is a merged global.
1356 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1357 Value *Ptr = CE->getOperand(0);
1358 addOpAddress(Block, Asm->Mang->getSymbol(cast<GlobalValue>(Ptr)));
1359 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1360 SmallVector<Value*, 3> Idx(CE->op_begin()+1, CE->op_end());
1361 addUInt(Block, 0, dwarf::DW_FORM_udata,
1362 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1363 addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1364 addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1367 if (addToAccelTable) {
1368 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1369 addAccelName(GV.getName(), AddrDIE);
1371 // If the linkage name is different than the name, go ahead and output
1372 // that as well into the name table.
1373 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1374 addAccelName(GV.getLinkageName(), AddrDIE);
1380 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1381 void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR,
1383 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1384 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1386 // The LowerBound value defines the lower bounds which is typically zero for
1387 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1388 // Count == -1 then the array is unbounded and we do not emit
1389 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1390 // Count == 0, then the array has zero elements in which case we do not emit
1392 int64_t LowerBound = SR.getLo();
1393 int64_t DefaultLowerBound = getDefaultLowerBound();
1394 int64_t Count = SR.getCount();
1396 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1397 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, LowerBound);
1399 if (Count != -1 && Count != 0)
1400 // FIXME: An unbounded array should reference the expression that defines
1402 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, LowerBound + Count - 1);
1404 Buffer.addChild(DW_Subrange);
1407 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1408 void CompileUnit::constructArrayTypeDIE(DIE &Buffer,
1409 DICompositeType *CTy) {
1410 Buffer.setTag(dwarf::DW_TAG_array_type);
1411 if (CTy->isVector())
1412 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1414 // Emit derived type.
1415 addType(&Buffer, CTy->getTypeDerivedFrom());
1416 DIArray Elements = CTy->getTypeArray();
1418 // Get an anonymous type for index type.
1419 // FIXME: This type should be passed down from the front end
1420 // as different languages may have different sizes for indexes.
1421 DIE *IdxTy = getIndexTyDie();
1423 // Construct an anonymous type for index type.
1424 IdxTy = new DIE(dwarf::DW_TAG_base_type);
1425 addString(IdxTy, dwarf::DW_AT_name, "int");
1426 addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1427 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1428 dwarf::DW_ATE_signed);
1430 setIndexTyDie(IdxTy);
1433 // Add subranges to array type.
1434 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1435 DIDescriptor Element = Elements.getElement(i);
1436 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1437 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1441 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1442 DIE *CompileUnit::constructEnumTypeDIE(DIEnumerator ETy) {
1443 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1444 StringRef Name = ETy.getName();
1445 addString(Enumerator, dwarf::DW_AT_name, Name);
1446 int64_t Value = ETy.getEnumValue();
1447 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1451 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1453 void CompileUnit::constructContainingTypeDIEs() {
1454 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1455 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1456 DIE *SPDie = CI->first;
1457 const MDNode *N = CI->second;
1459 DIE *NDie = getDIE(N);
1460 if (!NDie) continue;
1461 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1465 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1466 DIE *CompileUnit::constructVariableDIE(DbgVariable *DV, bool isScopeAbstract) {
1467 StringRef Name = DV->getName();
1469 // Translate tag to proper Dwarf tag.
1470 unsigned Tag = DV->getTag();
1472 // Define variable debug information entry.
1473 DIE *VariableDie = new DIE(Tag);
1474 DbgVariable *AbsVar = DV->getAbstractVariable();
1475 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1477 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1478 dwarf::DW_FORM_ref4, AbsDIE);
1480 addString(VariableDie, dwarf::DW_AT_name, Name);
1481 addSourceLine(VariableDie, DV->getVariable());
1482 addType(VariableDie, DV->getType());
1485 if (DV->isArtificial())
1486 addFlag(VariableDie, dwarf::DW_AT_artificial);
1488 if (isScopeAbstract) {
1489 DV->setDIE(VariableDie);
1493 // Add variable address.
1495 unsigned Offset = DV->getDotDebugLocOffset();
1496 if (Offset != ~0U) {
1497 addLabel(VariableDie, dwarf::DW_AT_location,
1498 dwarf::DW_FORM_data4,
1499 Asm->GetTempSymbol("debug_loc", Offset));
1500 DV->setDIE(VariableDie);
1504 // Check if variable is described by a DBG_VALUE instruction.
1505 if (const MachineInstr *DVInsn = DV->getMInsn()) {
1506 bool updated = false;
1507 if (DVInsn->getNumOperands() == 3) {
1508 if (DVInsn->getOperand(0).isReg()) {
1509 const MachineOperand RegOp = DVInsn->getOperand(0);
1510 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1511 if (DVInsn->getOperand(1).isImm() &&
1512 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
1513 unsigned FrameReg = 0;
1514 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1516 TFI->getFrameIndexReference(*Asm->MF,
1517 DVInsn->getOperand(1).getImm(),
1519 MachineLocation Location(FrameReg, Offset);
1520 addVariableAddress(DV, VariableDie, Location);
1522 } else if (RegOp.getReg())
1523 addVariableAddress(DV, VariableDie,
1524 MachineLocation(RegOp.getReg()));
1527 else if (DVInsn->getOperand(0).isImm())
1529 addConstantValue(VariableDie, DVInsn->getOperand(0),
1531 else if (DVInsn->getOperand(0).isFPImm())
1533 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1534 else if (DVInsn->getOperand(0).isCImm())
1536 addConstantValue(VariableDie,
1537 DVInsn->getOperand(0).getCImm(),
1538 DV->getType().isUnsignedDIType());
1540 addVariableAddress(DV, VariableDie,
1541 Asm->getDebugValueLocation(DVInsn));
1545 // If variableDie is not updated then DBG_VALUE instruction does not
1546 // have valid variable info.
1550 DV->setDIE(VariableDie);
1553 // .. else use frame index.
1554 int FI = DV->getFrameIndex();
1556 unsigned FrameReg = 0;
1557 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1559 TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1560 MachineLocation Location(FrameReg, Offset);
1561 addVariableAddress(DV, VariableDie, Location);
1565 DV->setDIE(VariableDie);
1569 /// createMemberDIE - Create new member DIE.
1570 DIE *CompileUnit::createMemberDIE(DIDerivedType DT) {
1571 DIE *MemberDie = new DIE(DT.getTag());
1572 StringRef Name = DT.getName();
1574 addString(MemberDie, dwarf::DW_AT_name, Name);
1576 addType(MemberDie, DT.getTypeDerivedFrom());
1578 addSourceLine(MemberDie, DT);
1580 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1581 addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1583 uint64_t Size = DT.getSizeInBits();
1584 uint64_t FieldSize = DT.getOriginalTypeSize();
1586 if (Size != FieldSize) {
1588 addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1589 addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1591 uint64_t Offset = DT.getOffsetInBits();
1592 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1593 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1594 uint64_t FieldOffset = (HiMark - FieldSize);
1595 Offset -= FieldOffset;
1597 // Maybe we need to work from the other end.
1598 if (Asm->getDataLayout().isLittleEndian())
1599 Offset = FieldSize - (Offset + Size);
1600 addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1602 // Here WD_AT_data_member_location points to the anonymous
1603 // field that includes this bit field.
1604 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1607 // This is not a bitfield.
1608 addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1610 if (DT.getTag() == dwarf::DW_TAG_inheritance
1611 && DT.isVirtual()) {
1613 // For C++, virtual base classes are not at fixed offset. Use following
1614 // expression to extract appropriate offset from vtable.
1615 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1617 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1618 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1619 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1620 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1621 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1622 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1623 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1624 addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1626 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1629 addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1631 if (DT.isProtected())
1632 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1633 dwarf::DW_ACCESS_protected);
1634 else if (DT.isPrivate())
1635 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1636 dwarf::DW_ACCESS_private);
1637 // Otherwise C++ member and base classes are considered public.
1639 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1640 dwarf::DW_ACCESS_public);
1642 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1643 dwarf::DW_VIRTUALITY_virtual);
1645 // Objective-C properties.
1646 if (MDNode *PNode = DT.getObjCProperty())
1647 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1648 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1651 if (DT.isArtificial())
1652 addFlag(MemberDie, dwarf::DW_AT_artificial);
1654 // This is only for backward compatibility.
1655 StringRef PropertyName = DT.getObjCPropertyName();
1656 if (!PropertyName.empty()) {
1657 addString(MemberDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1658 StringRef GetterName = DT.getObjCPropertyGetterName();
1659 if (!GetterName.empty())
1660 addString(MemberDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1661 StringRef SetterName = DT.getObjCPropertySetterName();
1662 if (!SetterName.empty())
1663 addString(MemberDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1664 unsigned PropertyAttributes = 0;
1665 if (DT.isReadOnlyObjCProperty())
1666 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1667 if (DT.isReadWriteObjCProperty())
1668 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1669 if (DT.isAssignObjCProperty())
1670 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1671 if (DT.isRetainObjCProperty())
1672 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1673 if (DT.isCopyObjCProperty())
1674 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1675 if (DT.isNonAtomicObjCProperty())
1676 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1677 if (PropertyAttributes)
1678 addUInt(MemberDie, dwarf::DW_AT_APPLE_property_attribute, 0,
1679 PropertyAttributes);
1684 /// createStaticMemberDIE - Create new DIE for C++ static member.
1685 DIE *CompileUnit::createStaticMemberDIE(const DIDerivedType DT) {
1689 DIE *StaticMemberDIE = new DIE(DT.getTag());
1690 DIType Ty = DT.getTypeDerivedFrom();
1692 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1693 addType(StaticMemberDIE, Ty);
1694 addSourceLine(StaticMemberDIE, DT);
1695 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1696 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1698 // FIXME: We could omit private if the parent is a class_type, and
1699 // public if the parent is something else.
1700 if (DT.isProtected())
1701 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1702 dwarf::DW_ACCESS_protected);
1703 else if (DT.isPrivate())
1704 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1705 dwarf::DW_ACCESS_private);
1707 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1708 dwarf::DW_ACCESS_public);
1710 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1711 addConstantValue(StaticMemberDIE, CI, Ty.isUnsignedDIType());
1712 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1713 addConstantFPValue(StaticMemberDIE, CFP);
1715 insertDIE(DT, StaticMemberDIE);
1716 return StaticMemberDIE;