1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains support for constructing a dwarf compile unit. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #define DEBUG_TYPE "dwarfdebug" 15 16 #include "DwarfUnit.h" 17 #include "DwarfAccelTable.h" 18 #include "DwarfDebug.h" 19 #include "llvm/ADT/APFloat.h" 20 #include "llvm/DIBuilder.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/DataLayout.h" 23 #include "llvm/IR/GlobalVariable.h" 24 #include "llvm/IR/Instructions.h" 25 #include "llvm/IR/Mangler.h" 26 #include "llvm/MC/MCAsmInfo.h" 27 #include "llvm/MC/MCContext.h" 28 #include "llvm/MC/MCSection.h" 29 #include "llvm/MC/MCStreamer.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Target/TargetFrameLowering.h" 32 #include "llvm/Target/TargetLoweringObjectFile.h" 33 #include "llvm/Target/TargetMachine.h" 34 #include "llvm/Target/TargetRegisterInfo.h" 35 36 using namespace llvm; 37 38 static cl::opt<bool> 39 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden, 40 cl::desc("Generate DWARF4 type units."), 41 cl::init(false)); 42 43 /// Unit - Unit constructor. 44 DwarfUnit::DwarfUnit(unsigned UID, DIE *D, DICompileUnit Node, AsmPrinter *A, 45 DwarfDebug *DW, DwarfFile *DWU) 46 : UniqueID(UID), CUNode(Node), UnitDie(D), DebugInfoOffset(0), Asm(A), 47 DD(DW), DU(DWU), IndexTyDie(0), Section(0), Skeleton(0) { 48 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1); 49 } 50 51 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node, 52 AsmPrinter *A, DwarfDebug *DW, 53 DwarfFile *DWU) 54 : DwarfUnit(UID, D, Node, A, DW, DWU) { 55 insertDIE(Node, D); 56 } 57 58 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DIE *D, DwarfCompileUnit &CU, 59 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU) 60 : DwarfUnit(UID, D, CU.getCUNode(), A, DW, DWU), CU(CU) {} 61 62 /// ~Unit - Destructor for compile unit. 63 DwarfUnit::~DwarfUnit() { 64 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j) 65 DIEBlocks[j]->~DIEBlock(); 66 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j) 67 DIELocs[j]->~DIELoc(); 68 } 69 70 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug 71 /// information entry. 72 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) { 73 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry); 74 return Value; 75 } 76 77 /// getDefaultLowerBound - Return the default lower bound for an array. If the 78 /// DWARF version doesn't handle the language, return -1. 79 int64_t DwarfUnit::getDefaultLowerBound() const { 80 switch (getLanguage()) { 81 default: 82 break; 83 84 case dwarf::DW_LANG_C89: 85 case dwarf::DW_LANG_C99: 86 case dwarf::DW_LANG_C: 87 case dwarf::DW_LANG_C_plus_plus: 88 case dwarf::DW_LANG_ObjC: 89 case dwarf::DW_LANG_ObjC_plus_plus: 90 return 0; 91 92 case dwarf::DW_LANG_Fortran77: 93 case dwarf::DW_LANG_Fortran90: 94 case dwarf::DW_LANG_Fortran95: 95 return 1; 96 97 // The languages below have valid values only if the DWARF version >= 4. 98 case dwarf::DW_LANG_Java: 99 case dwarf::DW_LANG_Python: 100 case dwarf::DW_LANG_UPC: 101 case dwarf::DW_LANG_D: 102 if (dwarf::DWARF_VERSION >= 4) 103 return 0; 104 break; 105 106 case dwarf::DW_LANG_Ada83: 107 case dwarf::DW_LANG_Ada95: 108 case dwarf::DW_LANG_Cobol74: 109 case dwarf::DW_LANG_Cobol85: 110 case dwarf::DW_LANG_Modula2: 111 case dwarf::DW_LANG_Pascal83: 112 case dwarf::DW_LANG_PLI: 113 if (dwarf::DWARF_VERSION >= 4) 114 return 1; 115 break; 116 } 117 118 return -1; 119 } 120 121 /// Check whether the DIE for this MDNode can be shared across CUs. 122 static bool isShareableAcrossCUs(DIDescriptor D) { 123 // When the MDNode can be part of the type system, the DIE can be shared 124 // across CUs. 125 // Combining type units and cross-CU DIE sharing is lower value (since 126 // cross-CU DIE sharing is used in LTO and removes type redundancy at that 127 // level already) but may be implementable for some value in projects 128 // building multiple independent libraries with LTO and then linking those 129 // together. 130 return (D.isType() || 131 (D.isSubprogram() && !DISubprogram(D).isDefinition())) && 132 !GenerateDwarfTypeUnits; 133 } 134 135 /// getDIE - Returns the debug information entry map slot for the 136 /// specified debug variable. We delegate the request to DwarfDebug 137 /// when the DIE for this MDNode can be shared across CUs. The mappings 138 /// will be kept in DwarfDebug for shareable DIEs. 139 DIE *DwarfUnit::getDIE(DIDescriptor D) const { 140 if (isShareableAcrossCUs(D)) 141 return DD->getDIE(D); 142 return MDNodeToDieMap.lookup(D); 143 } 144 145 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug 146 /// when the DIE for this MDNode can be shared across CUs. The mappings 147 /// will be kept in DwarfDebug for shareable DIEs. 148 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) { 149 if (isShareableAcrossCUs(Desc)) { 150 DD->insertDIE(Desc, D); 151 return; 152 } 153 MDNodeToDieMap.insert(std::make_pair(Desc, D)); 154 } 155 156 /// addFlag - Add a flag that is true. 157 void DwarfUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) { 158 if (DD->getDwarfVersion() >= 4) 159 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne); 160 else 161 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne); 162 } 163 164 /// addUInt - Add an unsigned integer attribute data and value. 165 /// 166 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute, 167 Optional<dwarf::Form> Form, uint64_t Integer) { 168 if (!Form) 169 Form = DIEInteger::BestForm(false, Integer); 170 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator) 171 DIEInteger(Integer); 172 Die->addValue(Attribute, *Form, Value); 173 } 174 175 void DwarfUnit::addUInt(DIE *Block, dwarf::Form Form, uint64_t Integer) { 176 addUInt(Block, (dwarf::Attribute)0, Form, Integer); 177 } 178 179 /// addSInt - Add an signed integer attribute data and value. 180 /// 181 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute, 182 Optional<dwarf::Form> Form, int64_t Integer) { 183 if (!Form) 184 Form = DIEInteger::BestForm(true, Integer); 185 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer); 186 Die->addValue(Attribute, *Form, Value); 187 } 188 189 void DwarfUnit::addSInt(DIELoc *Die, Optional<dwarf::Form> Form, 190 int64_t Integer) { 191 addSInt(Die, (dwarf::Attribute)0, Form, Integer); 192 } 193 194 /// addString - Add a string attribute data and value. We always emit a 195 /// reference to the string pool instead of immediate strings so that DIEs have 196 /// more predictable sizes. In the case of split dwarf we emit an index 197 /// into another table which gets us the static offset into the string 198 /// table. 199 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute, 200 StringRef String) { 201 202 if (!DD->useSplitDwarf()) 203 return addLocalString(Die, Attribute, String); 204 205 unsigned idx = DU->getStringPoolIndex(String); 206 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx); 207 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String); 208 Die->addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str); 209 } 210 211 /// addLocalString - Add a string attribute data and value. This is guaranteed 212 /// to be in the local string pool instead of indirected. 213 void DwarfUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute, 214 StringRef String) { 215 MCSymbol *Symb = DU->getStringPoolEntry(String); 216 DIEValue *Value; 217 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) 218 Value = new (DIEValueAllocator) DIELabel(Symb); 219 else { 220 MCSymbol *StringPool = DU->getStringPoolSym(); 221 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool); 222 } 223 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String); 224 Die->addValue(Attribute, dwarf::DW_FORM_strp, Str); 225 } 226 227 /// addExpr - Add a Dwarf expression attribute data and value. 228 /// 229 void DwarfUnit::addExpr(DIELoc *Die, dwarf::Form Form, const MCExpr *Expr) { 230 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr); 231 Die->addValue((dwarf::Attribute)0, Form, Value); 232 } 233 234 /// addLabel - Add a Dwarf label attribute data and value. 235 /// 236 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form, 237 const MCSymbol *Label) { 238 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label); 239 Die->addValue(Attribute, Form, Value); 240 } 241 242 void DwarfUnit::addLabel(DIELoc *Die, dwarf::Form Form, const MCSymbol *Label) { 243 addLabel(Die, (dwarf::Attribute)0, Form, Label); 244 } 245 246 /// addSectionLabel - Add a Dwarf section label attribute data and value. 247 /// 248 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute, 249 const MCSymbol *Label) { 250 if (DD->getDwarfVersion() >= 4) 251 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label); 252 else 253 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label); 254 } 255 256 /// addSectionOffset - Add an offset into a section attribute data and value. 257 /// 258 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute, 259 uint64_t Integer) { 260 if (DD->getDwarfVersion() >= 4) 261 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer); 262 else 263 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer); 264 } 265 266 /// addLabelAddress - Add a dwarf label attribute data and value using 267 /// DW_FORM_addr or DW_FORM_GNU_addr_index. 268 /// 269 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute, 270 MCSymbol *Label) { 271 if (Label) 272 DD->addArangeLabel(SymbolCU(this, Label)); 273 274 if (!DD->useSplitDwarf()) { 275 if (Label) { 276 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label); 277 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value); 278 } else { 279 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0); 280 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value); 281 } 282 } else { 283 unsigned idx = DU->getAddrPoolIndex(Label); 284 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx); 285 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value); 286 } 287 } 288 289 /// addOpAddress - Add a dwarf op address data and value using the 290 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index. 291 /// 292 void DwarfUnit::addOpAddress(DIELoc *Die, const MCSymbol *Sym) { 293 if (!DD->useSplitDwarf()) { 294 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr); 295 addLabel(Die, dwarf::DW_FORM_udata, Sym); 296 } else { 297 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index); 298 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym)); 299 } 300 } 301 302 /// addSectionDelta - Add a section label delta attribute data and value. 303 /// 304 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute, 305 const MCSymbol *Hi, const MCSymbol *Lo) { 306 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo); 307 if (DD->getDwarfVersion() >= 4) 308 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value); 309 else 310 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value); 311 } 312 313 /// addDIEEntry - Add a DIE attribute data and value. 314 /// 315 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) { 316 addDIEEntry(Die, Attribute, createDIEEntry(Entry)); 317 } 318 319 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) { 320 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8, 321 new (DIEValueAllocator) DIETypeSignature(Type)); 322 } 323 324 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, 325 DIEEntry *Entry) { 326 const DIE *DieCU = Die->getUnitOrNull(); 327 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull(); 328 if (!DieCU) 329 // We assume that Die belongs to this CU, if it is not linked to any CU yet. 330 DieCU = getUnitDie(); 331 if (!EntryCU) 332 EntryCU = getUnitDie(); 333 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4 334 : dwarf::DW_FORM_ref_addr, 335 Entry); 336 } 337 338 /// Create a DIE with the given Tag, add the DIE to its parent, and 339 /// call insertDIE if MD is not null. 340 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) { 341 DIE *Die = new DIE(Tag); 342 Parent.addChild(Die); 343 if (N) 344 insertDIE(N, Die); 345 return Die; 346 } 347 348 /// addBlock - Add block data. 349 /// 350 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute, DIELoc *Loc) { 351 Loc->setSize(Loc->ComputeSize(Asm)); 352 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on. 353 Die->addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc); 354 } 355 356 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute, 357 DIEBlock *Block) { 358 Block->setSize(Block->ComputeSize(Asm)); 359 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on. 360 Die->addValue(Attribute, Block->BestForm(), Block); 361 } 362 363 /// addSourceLine - Add location information to specified debug information 364 /// entry. 365 void DwarfUnit::addSourceLine(DIE *Die, unsigned Line, StringRef File, 366 StringRef Directory) { 367 if (Line == 0) 368 return; 369 370 unsigned FileID = 371 DD->getOrCreateSourceID(File, Directory, getCU().getUniqueID()); 372 assert(FileID && "Invalid file id"); 373 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID); 374 addUInt(Die, dwarf::DW_AT_decl_line, None, Line); 375 } 376 377 /// addSourceLine - Add location information to specified debug information 378 /// entry. 379 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) { 380 assert(V.isVariable()); 381 382 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(), 383 V.getContext().getDirectory()); 384 } 385 386 /// addSourceLine - Add location information to specified debug information 387 /// entry. 388 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) { 389 assert(G.isGlobalVariable()); 390 391 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory()); 392 } 393 394 /// addSourceLine - Add location information to specified debug information 395 /// entry. 396 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) { 397 assert(SP.isSubprogram()); 398 399 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory()); 400 } 401 402 /// addSourceLine - Add location information to specified debug information 403 /// entry. 404 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) { 405 assert(Ty.isType()); 406 407 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory()); 408 } 409 410 /// addSourceLine - Add location information to specified debug information 411 /// entry. 412 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) { 413 assert(Ty.isObjCProperty()); 414 415 DIFile File = Ty.getFile(); 416 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(), 417 File.getDirectory()); 418 } 419 420 /// addSourceLine - Add location information to specified debug information 421 /// entry. 422 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) { 423 assert(NS.Verify()); 424 425 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory()); 426 } 427 428 /// addVariableAddress - Add DW_AT_location attribute for a 429 /// DbgVariable based on provided MachineLocation. 430 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die, 431 MachineLocation Location) { 432 if (DV.variableHasComplexAddress()) 433 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location); 434 else if (DV.isBlockByrefVariable()) 435 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location); 436 else 437 addAddress(Die, dwarf::DW_AT_location, Location, 438 DV.getVariable().isIndirect()); 439 } 440 441 /// addRegisterOp - Add register operand. 442 void DwarfUnit::addRegisterOp(DIELoc *TheDie, unsigned Reg) { 443 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo(); 444 int DWReg = RI->getDwarfRegNum(Reg, false); 445 bool isSubRegister = DWReg < 0; 446 447 unsigned Idx = 0; 448 449 // Go up the super-register chain until we hit a valid dwarf register number. 450 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) { 451 DWReg = RI->getDwarfRegNum(*SR, false); 452 if (DWReg >= 0) 453 Idx = RI->getSubRegIndex(*SR, Reg); 454 } 455 456 if (DWReg < 0) { 457 DEBUG(llvm::dbgs() << "Invalid Dwarf register number.\n"); 458 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop); 459 return; 460 } 461 462 // Emit register 463 if (DWReg < 32) 464 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg); 465 else { 466 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx); 467 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg); 468 } 469 470 // Emit Mask 471 if (isSubRegister) { 472 unsigned Size = RI->getSubRegIdxSize(Idx); 473 unsigned Offset = RI->getSubRegIdxOffset(Idx); 474 if (Offset > 0) { 475 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece); 476 addUInt(TheDie, dwarf::DW_FORM_data1, Size); 477 addUInt(TheDie, dwarf::DW_FORM_data1, Offset); 478 } else { 479 unsigned ByteSize = Size / 8; // Assuming 8 bits per byte. 480 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece); 481 addUInt(TheDie, dwarf::DW_FORM_data1, ByteSize); 482 } 483 } 484 } 485 486 /// addRegisterOffset - Add register offset. 487 void DwarfUnit::addRegisterOffset(DIELoc *TheDie, unsigned Reg, 488 int64_t Offset) { 489 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo(); 490 unsigned DWReg = RI->getDwarfRegNum(Reg, false); 491 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo(); 492 if (Reg == TRI->getFrameRegister(*Asm->MF)) 493 // If variable offset is based in frame register then use fbreg. 494 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg); 495 else if (DWReg < 32) 496 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg); 497 else { 498 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx); 499 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg); 500 } 501 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset); 502 } 503 504 /// addAddress - Add an address attribute to a die based on the location 505 /// provided. 506 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute, 507 const MachineLocation &Location, bool Indirect) { 508 DIELoc *Loc = new (DIEValueAllocator) DIELoc(); 509 510 if (Location.isReg() && !Indirect) 511 addRegisterOp(Loc, Location.getReg()); 512 else { 513 addRegisterOffset(Loc, Location.getReg(), Location.getOffset()); 514 if (Indirect && !Location.isReg()) { 515 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 516 } 517 } 518 519 // Now attach the location information to the DIE. 520 addBlock(Die, Attribute, Loc); 521 } 522 523 /// addComplexAddress - Start with the address based on the location provided, 524 /// and generate the DWARF information necessary to find the actual variable 525 /// given the extra address information encoded in the DbgVariable, starting 526 /// from the starting location. Add the DWARF information to the die. 527 /// 528 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die, 529 dwarf::Attribute Attribute, 530 const MachineLocation &Location) { 531 DIELoc *Loc = new (DIEValueAllocator) DIELoc(); 532 unsigned N = DV.getNumAddrElements(); 533 unsigned i = 0; 534 if (Location.isReg()) { 535 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) { 536 // If first address element is OpPlus then emit 537 // DW_OP_breg + Offset instead of DW_OP_reg + Offset. 538 addRegisterOffset(Loc, Location.getReg(), DV.getAddrElement(1)); 539 i = 2; 540 } else 541 addRegisterOp(Loc, Location.getReg()); 542 } else 543 addRegisterOffset(Loc, Location.getReg(), Location.getOffset()); 544 545 for (; i < N; ++i) { 546 uint64_t Element = DV.getAddrElement(i); 547 if (Element == DIBuilder::OpPlus) { 548 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 549 addUInt(Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i)); 550 } else if (Element == DIBuilder::OpDeref) { 551 if (!Location.isReg()) 552 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 553 } else 554 llvm_unreachable("unknown DIBuilder Opcode"); 555 } 556 557 // Now attach the location information to the DIE. 558 addBlock(Die, Attribute, Loc); 559 } 560 561 /* Byref variables, in Blocks, are declared by the programmer as "SomeType 562 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and 563 gives the variable VarName either the struct, or a pointer to the struct, as 564 its type. This is necessary for various behind-the-scenes things the 565 compiler needs to do with by-reference variables in Blocks. 566 567 However, as far as the original *programmer* is concerned, the variable 568 should still have type 'SomeType', as originally declared. 569 570 The function getBlockByrefType dives into the __Block_byref_x_VarName 571 struct to find the original type of the variable, which is then assigned to 572 the variable's Debug Information Entry as its real type. So far, so good. 573 However now the debugger will expect the variable VarName to have the type 574 SomeType. So we need the location attribute for the variable to be an 575 expression that explains to the debugger how to navigate through the 576 pointers and struct to find the actual variable of type SomeType. 577 578 The following function does just that. We start by getting 579 the "normal" location for the variable. This will be the location 580 of either the struct __Block_byref_x_VarName or the pointer to the 581 struct __Block_byref_x_VarName. 582 583 The struct will look something like: 584 585 struct __Block_byref_x_VarName { 586 ... <various fields> 587 struct __Block_byref_x_VarName *forwarding; 588 ... <various other fields> 589 SomeType VarName; 590 ... <maybe more fields> 591 }; 592 593 If we are given the struct directly (as our starting point) we 594 need to tell the debugger to: 595 596 1). Add the offset of the forwarding field. 597 598 2). Follow that pointer to get the real __Block_byref_x_VarName 599 struct to use (the real one may have been copied onto the heap). 600 601 3). Add the offset for the field VarName, to find the actual variable. 602 603 If we started with a pointer to the struct, then we need to 604 dereference that pointer first, before the other steps. 605 Translating this into DWARF ops, we will need to append the following 606 to the current location description for the variable: 607 608 DW_OP_deref -- optional, if we start with a pointer 609 DW_OP_plus_uconst <forward_fld_offset> 610 DW_OP_deref 611 DW_OP_plus_uconst <varName_fld_offset> 612 613 That is what this function does. */ 614 615 /// addBlockByrefAddress - Start with the address based on the location 616 /// provided, and generate the DWARF information necessary to find the 617 /// actual Block variable (navigating the Block struct) based on the 618 /// starting location. Add the DWARF information to the die. For 619 /// more information, read large comment just above here. 620 /// 621 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die, 622 dwarf::Attribute Attribute, 623 const MachineLocation &Location) { 624 DIType Ty = DV.getType(); 625 DIType TmpTy = Ty; 626 uint16_t Tag = Ty.getTag(); 627 bool isPointer = false; 628 629 StringRef varName = DV.getName(); 630 631 if (Tag == dwarf::DW_TAG_pointer_type) { 632 DIDerivedType DTy(Ty); 633 TmpTy = resolve(DTy.getTypeDerivedFrom()); 634 isPointer = true; 635 } 636 637 DICompositeType blockStruct(TmpTy); 638 639 // Find the __forwarding field and the variable field in the __Block_byref 640 // struct. 641 DIArray Fields = blockStruct.getTypeArray(); 642 DIDerivedType varField; 643 DIDerivedType forwardingField; 644 645 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) { 646 DIDerivedType DT(Fields.getElement(i)); 647 StringRef fieldName = DT.getName(); 648 if (fieldName == "__forwarding") 649 forwardingField = DT; 650 else if (fieldName == varName) 651 varField = DT; 652 } 653 654 // Get the offsets for the forwarding field and the variable field. 655 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3; 656 unsigned varFieldOffset = varField.getOffsetInBits() >> 2; 657 658 // Decode the original location, and use that as the start of the byref 659 // variable's location. 660 DIELoc *Loc = new (DIEValueAllocator) DIELoc(); 661 662 if (Location.isReg()) 663 addRegisterOp(Loc, Location.getReg()); 664 else 665 addRegisterOffset(Loc, Location.getReg(), Location.getOffset()); 666 667 // If we started with a pointer to the __Block_byref... struct, then 668 // the first thing we need to do is dereference the pointer (DW_OP_deref). 669 if (isPointer) 670 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 671 672 // Next add the offset for the '__forwarding' field: 673 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in 674 // adding the offset if it's 0. 675 if (forwardingFieldOffset > 0) { 676 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 677 addUInt(Loc, dwarf::DW_FORM_udata, forwardingFieldOffset); 678 } 679 680 // Now dereference the __forwarding field to get to the real __Block_byref 681 // struct: DW_OP_deref. 682 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 683 684 // Now that we've got the real __Block_byref... struct, add the offset 685 // for the variable's field to get to the location of the actual variable: 686 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0. 687 if (varFieldOffset > 0) { 688 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 689 addUInt(Loc, dwarf::DW_FORM_udata, varFieldOffset); 690 } 691 692 // Now attach the location information to the DIE. 693 addBlock(Die, Attribute, Loc); 694 } 695 696 /// isTypeSigned - Return true if the type is signed. 697 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) { 698 if (Ty.isDerivedType()) 699 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()), 700 SizeInBits); 701 if (Ty.isBasicType()) 702 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed || 703 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) { 704 *SizeInBits = Ty.getSizeInBits(); 705 return true; 706 } 707 return false; 708 } 709 710 /// Return true if type encoding is unsigned. 711 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) { 712 DIDerivedType DTy(Ty); 713 if (DTy.isDerivedType()) 714 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom())); 715 716 DIBasicType BTy(Ty); 717 if (BTy.isBasicType()) { 718 unsigned Encoding = BTy.getEncoding(); 719 if (Encoding == dwarf::DW_ATE_unsigned || 720 Encoding == dwarf::DW_ATE_unsigned_char || 721 Encoding == dwarf::DW_ATE_boolean) 722 return true; 723 } 724 return false; 725 } 726 727 /// If this type is derived from a base type then return base type size. 728 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) { 729 unsigned Tag = Ty.getTag(); 730 731 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef && 732 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type && 733 Tag != dwarf::DW_TAG_restrict_type) 734 return Ty.getSizeInBits(); 735 736 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom()); 737 738 // If this type is not derived from any type then take conservative approach. 739 if (!BaseType.isValid()) 740 return Ty.getSizeInBits(); 741 742 // If this is a derived type, go ahead and get the base type, unless it's a 743 // reference then it's just the size of the field. Pointer types have no need 744 // of this since they're a different type of qualification on the type. 745 if (BaseType.getTag() == dwarf::DW_TAG_reference_type || 746 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type) 747 return Ty.getSizeInBits(); 748 749 if (BaseType.isDerivedType()) 750 return getBaseTypeSize(DD, DIDerivedType(BaseType)); 751 752 return BaseType.getSizeInBits(); 753 } 754 755 /// addConstantValue - Add constant value entry in variable DIE. 756 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO, 757 DIType Ty) { 758 // FIXME: This is a bit conservative/simple - it emits negative values at 759 // their maximum bit width which is a bit unfortunate (& doesn't prefer 760 // udata/sdata over dataN as suggested by the DWARF spec) 761 assert(MO.isImm() && "Invalid machine operand!"); 762 int SizeInBits = -1; 763 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits); 764 dwarf::Form Form; 765 766 // If we're a signed constant definitely use sdata. 767 if (SignedConstant) { 768 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm()); 769 return; 770 } 771 772 // Else use data for now unless it's larger than we can deal with. 773 switch (SizeInBits) { 774 case 8: 775 Form = dwarf::DW_FORM_data1; 776 break; 777 case 16: 778 Form = dwarf::DW_FORM_data2; 779 break; 780 case 32: 781 Form = dwarf::DW_FORM_data4; 782 break; 783 case 64: 784 Form = dwarf::DW_FORM_data8; 785 break; 786 default: 787 Form = dwarf::DW_FORM_udata; 788 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm()); 789 return; 790 } 791 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm()); 792 } 793 794 /// addConstantFPValue - Add constant value entry in variable DIE. 795 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) { 796 assert(MO.isFPImm() && "Invalid machine operand!"); 797 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 798 APFloat FPImm = MO.getFPImm()->getValueAPF(); 799 800 // Get the raw data form of the floating point. 801 const APInt FltVal = FPImm.bitcastToAPInt(); 802 const char *FltPtr = (const char *)FltVal.getRawData(); 803 804 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte. 805 bool LittleEndian = Asm->getDataLayout().isLittleEndian(); 806 int Incr = (LittleEndian ? 1 : -1); 807 int Start = (LittleEndian ? 0 : NumBytes - 1); 808 int Stop = (LittleEndian ? NumBytes : -1); 809 810 // Output the constant to DWARF one byte at a time. 811 for (; Start != Stop; Start += Incr) 812 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]); 813 814 addBlock(Die, dwarf::DW_AT_const_value, Block); 815 } 816 817 /// addConstantFPValue - Add constant value entry in variable DIE. 818 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) { 819 // Pass this down to addConstantValue as an unsigned bag of bits. 820 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true); 821 } 822 823 /// addConstantValue - Add constant value entry in variable DIE. 824 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI, 825 bool Unsigned) { 826 addConstantValue(Die, CI->getValue(), Unsigned); 827 } 828 829 // addConstantValue - Add constant value entry in variable DIE. 830 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) { 831 unsigned CIBitWidth = Val.getBitWidth(); 832 if (CIBitWidth <= 64) { 833 // If we're a signed constant definitely use sdata. 834 if (!Unsigned) { 835 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, 836 Val.getSExtValue()); 837 return; 838 } 839 840 // Else use data for now unless it's larger than we can deal with. 841 dwarf::Form Form; 842 switch (CIBitWidth) { 843 case 8: 844 Form = dwarf::DW_FORM_data1; 845 break; 846 case 16: 847 Form = dwarf::DW_FORM_data2; 848 break; 849 case 32: 850 Form = dwarf::DW_FORM_data4; 851 break; 852 case 64: 853 Form = dwarf::DW_FORM_data8; 854 break; 855 default: 856 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata, 857 Val.getZExtValue()); 858 return; 859 } 860 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue()); 861 return; 862 } 863 864 DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); 865 866 // Get the raw data form of the large APInt. 867 const uint64_t *Ptr64 = Val.getRawData(); 868 869 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte. 870 bool LittleEndian = Asm->getDataLayout().isLittleEndian(); 871 872 // Output the constant to DWARF one byte at a time. 873 for (int i = 0; i < NumBytes; i++) { 874 uint8_t c; 875 if (LittleEndian) 876 c = Ptr64[i / 8] >> (8 * (i & 7)); 877 else 878 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7)); 879 addUInt(Block, dwarf::DW_FORM_data1, c); 880 } 881 882 addBlock(Die, dwarf::DW_AT_const_value, Block); 883 } 884 885 /// addTemplateParams - Add template parameters into buffer. 886 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) { 887 // Add template parameters. 888 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) { 889 DIDescriptor Element = TParams.getElement(i); 890 if (Element.isTemplateTypeParameter()) 891 constructTemplateTypeParameterDIE(Buffer, 892 DITemplateTypeParameter(Element)); 893 else if (Element.isTemplateValueParameter()) 894 constructTemplateValueParameterDIE(Buffer, 895 DITemplateValueParameter(Element)); 896 } 897 } 898 899 /// getOrCreateContextDIE - Get context owner's DIE. 900 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) { 901 if (!Context || Context.isFile()) 902 return getUnitDie(); 903 if (Context.isType()) 904 return getOrCreateTypeDIE(DIType(Context)); 905 if (Context.isNameSpace()) 906 return getOrCreateNameSpace(DINameSpace(Context)); 907 if (Context.isSubprogram()) 908 return getOrCreateSubprogramDIE(DISubprogram(Context)); 909 return getDIE(Context); 910 } 911 912 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) { 913 DIScope Context = resolve(Ty.getContext()); 914 DIE *ContextDIE = getOrCreateContextDIE(Context); 915 916 DIE *TyDIE = getDIE(Ty); 917 if (TyDIE) 918 return TyDIE; 919 920 // Create new type. 921 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty); 922 923 constructTypeDIE(*TyDIE, Ty); 924 925 updateAcceleratorTables(Context, Ty, TyDIE); 926 return TyDIE; 927 } 928 929 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the 930 /// given DIType. 931 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) { 932 if (!TyNode) 933 return NULL; 934 935 DIType Ty(TyNode); 936 assert(Ty.isType()); 937 938 // Construct the context before querying for the existence of the DIE in case 939 // such construction creates the DIE. 940 DIScope Context = resolve(Ty.getContext()); 941 DIE *ContextDIE = getOrCreateContextDIE(Context); 942 assert(ContextDIE); 943 944 DIE *TyDIE = getDIE(Ty); 945 if (TyDIE) 946 return TyDIE; 947 948 // Create new type. 949 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty); 950 951 if (Ty.isBasicType()) 952 constructTypeDIE(*TyDIE, DIBasicType(Ty)); 953 else if (Ty.isCompositeType()) { 954 DICompositeType CTy(Ty); 955 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl()) 956 if (MDString *TypeId = CTy.getIdentifier()) { 957 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy); 958 // Skip updating the accellerator tables since this is not the full type 959 return TyDIE; 960 } 961 constructTypeDIE(*TyDIE, CTy); 962 } else { 963 assert(Ty.isDerivedType() && "Unknown kind of DIType"); 964 constructTypeDIE(*TyDIE, DIDerivedType(Ty)); 965 } 966 967 updateAcceleratorTables(Context, Ty, TyDIE); 968 969 return TyDIE; 970 } 971 972 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty, 973 const DIE *TyDIE) { 974 if (!Ty.getName().empty() && !Ty.isForwardDecl()) { 975 bool IsImplementation = 0; 976 if (Ty.isCompositeType()) { 977 DICompositeType CT(Ty); 978 // A runtime language of 0 actually means C/C++ and that any 979 // non-negative value is some version of Objective-C/C++. 980 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete(); 981 } 982 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0; 983 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags)); 984 985 if (!Context || Context.isCompileUnit() || Context.isFile() || 986 Context.isNameSpace()) 987 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE; 988 } 989 } 990 991 /// addType - Add a new type attribute to the specified entity. 992 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) { 993 assert(Ty && "Trying to add a type that doesn't exist?"); 994 995 // Check for pre-existence. 996 DIEEntry *Entry = getDIEEntry(Ty); 997 // If it exists then use the existing value. 998 if (Entry) { 999 addDIEEntry(Entity, Attribute, Entry); 1000 return; 1001 } 1002 1003 // Construct type. 1004 DIE *Buffer = getOrCreateTypeDIE(Ty); 1005 1006 // Set up proxy. 1007 Entry = createDIEEntry(Buffer); 1008 insertDIEEntry(Ty, Entry); 1009 addDIEEntry(Entity, Attribute, Entry); 1010 } 1011 1012 // Accelerator table mutators - add each name along with its companion 1013 // DIE to the proper table while ensuring that the name that we're going 1014 // to reference is in the string table. We do this since the names we 1015 // add may not only be identical to the names in the DIE. 1016 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) { 1017 if (!DD->useDwarfAccelTables()) 1018 return; 1019 DU->getStringPoolEntry(Name); 1020 std::vector<const DIE *> &DIEs = AccelNames[Name]; 1021 DIEs.push_back(Die); 1022 } 1023 1024 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) { 1025 if (!DD->useDwarfAccelTables()) 1026 return; 1027 DU->getStringPoolEntry(Name); 1028 std::vector<const DIE *> &DIEs = AccelObjC[Name]; 1029 DIEs.push_back(Die); 1030 } 1031 1032 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) { 1033 if (!DD->useDwarfAccelTables()) 1034 return; 1035 DU->getStringPoolEntry(Name); 1036 std::vector<const DIE *> &DIEs = AccelNamespace[Name]; 1037 DIEs.push_back(Die); 1038 } 1039 1040 void DwarfUnit::addAccelType(StringRef Name, 1041 std::pair<const DIE *, unsigned> Die) { 1042 if (!DD->useDwarfAccelTables()) 1043 return; 1044 DU->getStringPoolEntry(Name); 1045 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name]; 1046 DIEs.push_back(Die); 1047 } 1048 1049 /// addGlobalName - Add a new global name to the compile unit. 1050 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) { 1051 std::string FullName = getParentContextString(Context) + Name.str(); 1052 GlobalNames[FullName] = Die; 1053 } 1054 1055 /// getParentContextString - Walks the metadata parent chain in a language 1056 /// specific manner (using the compile unit language) and returns 1057 /// it as a string. This is done at the metadata level because DIEs may 1058 /// not currently have been added to the parent context and walking the 1059 /// DIEs looking for names is more expensive than walking the metadata. 1060 std::string DwarfUnit::getParentContextString(DIScope Context) const { 1061 if (!Context) 1062 return ""; 1063 1064 // FIXME: Decide whether to implement this for non-C++ languages. 1065 if (getLanguage() != dwarf::DW_LANG_C_plus_plus) 1066 return ""; 1067 1068 std::string CS; 1069 SmallVector<DIScope, 1> Parents; 1070 while (!Context.isCompileUnit()) { 1071 Parents.push_back(Context); 1072 if (Context.getContext()) 1073 Context = resolve(Context.getContext()); 1074 else 1075 // Structure, etc types will have a NULL context if they're at the top 1076 // level. 1077 break; 1078 } 1079 1080 // Reverse iterate over our list to go from the outermost construct to the 1081 // innermost. 1082 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(), 1083 E = Parents.rend(); 1084 I != E; ++I) { 1085 DIScope Ctx = *I; 1086 StringRef Name = Ctx.getName(); 1087 if (!Name.empty()) { 1088 CS += Name; 1089 CS += "::"; 1090 } 1091 } 1092 return CS; 1093 } 1094 1095 /// constructTypeDIE - Construct basic type die from DIBasicType. 1096 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) { 1097 // Get core information. 1098 StringRef Name = BTy.getName(); 1099 // Add name if not anonymous or intermediate type. 1100 if (!Name.empty()) 1101 addString(&Buffer, dwarf::DW_AT_name, Name); 1102 1103 // An unspecified type only has a name attribute. 1104 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type) 1105 return; 1106 1107 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, 1108 BTy.getEncoding()); 1109 1110 uint64_t Size = BTy.getSizeInBits() >> 3; 1111 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size); 1112 } 1113 1114 /// constructTypeDIE - Construct derived type die from DIDerivedType. 1115 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) { 1116 // Get core information. 1117 StringRef Name = DTy.getName(); 1118 uint64_t Size = DTy.getSizeInBits() >> 3; 1119 uint16_t Tag = Buffer.getTag(); 1120 1121 // Map to main type, void will not have a type. 1122 DIType FromTy = resolve(DTy.getTypeDerivedFrom()); 1123 if (FromTy) 1124 addType(&Buffer, FromTy); 1125 1126 // Add name if not anonymous or intermediate type. 1127 if (!Name.empty()) 1128 addString(&Buffer, dwarf::DW_AT_name, Name); 1129 1130 // Add size if non-zero (derived types might be zero-sized.) 1131 if (Size && Tag != dwarf::DW_TAG_pointer_type) 1132 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size); 1133 1134 if (Tag == dwarf::DW_TAG_ptr_to_member_type) 1135 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, 1136 getOrCreateTypeDIE(resolve(DTy.getClassType()))); 1137 // Add source line info if available and TyDesc is not a forward declaration. 1138 if (!DTy.isForwardDecl()) 1139 addSourceLine(&Buffer, DTy); 1140 } 1141 1142 /// constructTypeDIE - Construct type DIE from DICompositeType. 1143 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) { 1144 // Add name if not anonymous or intermediate type. 1145 StringRef Name = CTy.getName(); 1146 1147 uint64_t Size = CTy.getSizeInBits() >> 3; 1148 uint16_t Tag = Buffer.getTag(); 1149 1150 switch (Tag) { 1151 case dwarf::DW_TAG_array_type: 1152 constructArrayTypeDIE(Buffer, CTy); 1153 break; 1154 case dwarf::DW_TAG_enumeration_type: 1155 constructEnumTypeDIE(Buffer, CTy); 1156 break; 1157 case dwarf::DW_TAG_subroutine_type: { 1158 // Add return type. A void return won't have a type. 1159 DIArray Elements = CTy.getTypeArray(); 1160 DIType RTy(Elements.getElement(0)); 1161 if (RTy) 1162 addType(&Buffer, RTy); 1163 1164 bool isPrototyped = true; 1165 // Add arguments. 1166 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) { 1167 DIDescriptor Ty = Elements.getElement(i); 1168 if (Ty.isUnspecifiedParameter()) { 1169 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer); 1170 isPrototyped = false; 1171 } else { 1172 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer); 1173 addType(Arg, DIType(Ty)); 1174 if (DIType(Ty).isArtificial()) 1175 addFlag(Arg, dwarf::DW_AT_artificial); 1176 } 1177 } 1178 // Add prototype flag if we're dealing with a C language and the 1179 // function has been prototyped. 1180 uint16_t Language = getLanguage(); 1181 if (isPrototyped && 1182 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 || 1183 Language == dwarf::DW_LANG_ObjC)) 1184 addFlag(&Buffer, dwarf::DW_AT_prototyped); 1185 1186 if (CTy.isLValueReference()) 1187 addFlag(&Buffer, dwarf::DW_AT_reference); 1188 1189 if (CTy.isRValueReference()) 1190 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference); 1191 } break; 1192 case dwarf::DW_TAG_structure_type: 1193 case dwarf::DW_TAG_union_type: 1194 case dwarf::DW_TAG_class_type: { 1195 // Add elements to structure type. 1196 DIArray Elements = CTy.getTypeArray(); 1197 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 1198 DIDescriptor Element = Elements.getElement(i); 1199 DIE *ElemDie = NULL; 1200 if (Element.isSubprogram()) 1201 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element)); 1202 else if (Element.isDerivedType()) { 1203 DIDerivedType DDTy(Element); 1204 if (DDTy.getTag() == dwarf::DW_TAG_friend) { 1205 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer); 1206 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()), 1207 dwarf::DW_AT_friend); 1208 } else if (DDTy.isStaticMember()) { 1209 getOrCreateStaticMemberDIE(DDTy); 1210 } else { 1211 constructMemberDIE(Buffer, DDTy); 1212 } 1213 } else if (Element.isObjCProperty()) { 1214 DIObjCProperty Property(Element); 1215 ElemDie = createAndAddDIE(Property.getTag(), Buffer); 1216 StringRef PropertyName = Property.getObjCPropertyName(); 1217 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName); 1218 if (Property.getType()) 1219 addType(ElemDie, Property.getType()); 1220 addSourceLine(ElemDie, Property); 1221 StringRef GetterName = Property.getObjCPropertyGetterName(); 1222 if (!GetterName.empty()) 1223 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName); 1224 StringRef SetterName = Property.getObjCPropertySetterName(); 1225 if (!SetterName.empty()) 1226 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName); 1227 unsigned PropertyAttributes = 0; 1228 if (Property.isReadOnlyObjCProperty()) 1229 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly; 1230 if (Property.isReadWriteObjCProperty()) 1231 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite; 1232 if (Property.isAssignObjCProperty()) 1233 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign; 1234 if (Property.isRetainObjCProperty()) 1235 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain; 1236 if (Property.isCopyObjCProperty()) 1237 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy; 1238 if (Property.isNonAtomicObjCProperty()) 1239 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic; 1240 if (PropertyAttributes) 1241 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None, 1242 PropertyAttributes); 1243 1244 DIEEntry *Entry = getDIEEntry(Element); 1245 if (!Entry) { 1246 Entry = createDIEEntry(ElemDie); 1247 insertDIEEntry(Element, Entry); 1248 } 1249 } else 1250 continue; 1251 } 1252 1253 if (CTy.isAppleBlockExtension()) 1254 addFlag(&Buffer, dwarf::DW_AT_APPLE_block); 1255 1256 DICompositeType ContainingType(resolve(CTy.getContainingType())); 1257 if (ContainingType) 1258 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, 1259 getOrCreateTypeDIE(ContainingType)); 1260 1261 if (CTy.isObjcClassComplete()) 1262 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type); 1263 1264 // Add template parameters to a class, structure or union types. 1265 // FIXME: The support isn't in the metadata for this yet. 1266 if (Tag == dwarf::DW_TAG_class_type || 1267 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) 1268 addTemplateParams(Buffer, CTy.getTemplateParams()); 1269 1270 break; 1271 } 1272 default: 1273 break; 1274 } 1275 1276 // Add name if not anonymous or intermediate type. 1277 if (!Name.empty()) 1278 addString(&Buffer, dwarf::DW_AT_name, Name); 1279 1280 if (Tag == dwarf::DW_TAG_enumeration_type || 1281 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type || 1282 Tag == dwarf::DW_TAG_union_type) { 1283 // Add size if non-zero (derived types might be zero-sized.) 1284 // TODO: Do we care about size for enum forward declarations? 1285 if (Size) 1286 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size); 1287 else if (!CTy.isForwardDecl()) 1288 // Add zero size if it is not a forward declaration. 1289 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0); 1290 1291 // If we're a forward decl, say so. 1292 if (CTy.isForwardDecl()) 1293 addFlag(&Buffer, dwarf::DW_AT_declaration); 1294 1295 // Add source line info if available. 1296 if (!CTy.isForwardDecl()) 1297 addSourceLine(&Buffer, CTy); 1298 1299 // No harm in adding the runtime language to the declaration. 1300 unsigned RLang = CTy.getRunTimeLang(); 1301 if (RLang) 1302 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1, 1303 RLang); 1304 } 1305 } 1306 1307 /// constructTemplateTypeParameterDIE - Construct new DIE for the given 1308 /// DITemplateTypeParameter. 1309 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer, 1310 DITemplateTypeParameter TP) { 1311 DIE *ParamDIE = 1312 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer); 1313 // Add the type if it exists, it could be void and therefore no type. 1314 if (TP.getType()) 1315 addType(ParamDIE, resolve(TP.getType())); 1316 if (!TP.getName().empty()) 1317 addString(ParamDIE, dwarf::DW_AT_name, TP.getName()); 1318 } 1319 1320 /// constructTemplateValueParameterDIE - Construct new DIE for the given 1321 /// DITemplateValueParameter. 1322 void 1323 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer, 1324 DITemplateValueParameter VP) { 1325 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer); 1326 1327 // Add the type if there is one, template template and template parameter 1328 // packs will not have a type. 1329 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter) 1330 addType(ParamDIE, resolve(VP.getType())); 1331 if (!VP.getName().empty()) 1332 addString(ParamDIE, dwarf::DW_AT_name, VP.getName()); 1333 if (Value *Val = VP.getValue()) { 1334 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) 1335 addConstantValue(ParamDIE, CI, 1336 isUnsignedDIType(DD, resolve(VP.getType()))); 1337 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) { 1338 // For declaration non-type template parameters (such as global values and 1339 // functions) 1340 DIELoc *Loc = new (DIEValueAllocator) DIELoc(); 1341 addOpAddress(Loc, Asm->getSymbol(GV)); 1342 // Emit DW_OP_stack_value to use the address as the immediate value of the 1343 // parameter, rather than a pointer to it. 1344 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value); 1345 addBlock(ParamDIE, dwarf::DW_AT_location, Loc); 1346 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) { 1347 assert(isa<MDString>(Val)); 1348 addString(ParamDIE, dwarf::DW_AT_GNU_template_name, 1349 cast<MDString>(Val)->getString()); 1350 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) { 1351 assert(isa<MDNode>(Val)); 1352 DIArray A(cast<MDNode>(Val)); 1353 addTemplateParams(*ParamDIE, A); 1354 } 1355 } 1356 } 1357 1358 /// getOrCreateNameSpace - Create a DIE for DINameSpace. 1359 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) { 1360 // Construct the context before querying for the existence of the DIE in case 1361 // such construction creates the DIE. 1362 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext()); 1363 1364 DIE *NDie = getDIE(NS); 1365 if (NDie) 1366 return NDie; 1367 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS); 1368 1369 if (!NS.getName().empty()) { 1370 addString(NDie, dwarf::DW_AT_name, NS.getName()); 1371 addAccelNamespace(NS.getName(), NDie); 1372 addGlobalName(NS.getName(), NDie, NS.getContext()); 1373 } else 1374 addAccelNamespace("(anonymous namespace)", NDie); 1375 addSourceLine(NDie, NS); 1376 return NDie; 1377 } 1378 1379 /// getOrCreateSubprogramDIE - Create new DIE using SP. 1380 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) { 1381 // Construct the context before querying for the existence of the DIE in case 1382 // such construction creates the DIE (as is the case for member function 1383 // declarations). 1384 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext())); 1385 1386 DIE *SPDie = getDIE(SP); 1387 if (SPDie) 1388 return SPDie; 1389 1390 DISubprogram SPDecl = SP.getFunctionDeclaration(); 1391 if (SPDecl.isSubprogram()) 1392 // Add subprogram definitions to the CU die directly. 1393 ContextDIE = UnitDie.get(); 1394 1395 // DW_TAG_inlined_subroutine may refer to this DIE. 1396 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP); 1397 1398 DIE *DeclDie = NULL; 1399 if (SPDecl.isSubprogram()) 1400 DeclDie = getOrCreateSubprogramDIE(SPDecl); 1401 1402 // Add function template parameters. 1403 addTemplateParams(*SPDie, SP.getTemplateParams()); 1404 1405 // If this DIE is going to refer declaration info using AT_specification 1406 // then there is no need to add other attributes. 1407 if (DeclDie) { 1408 // Refer function declaration directly. 1409 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie); 1410 1411 return SPDie; 1412 } 1413 1414 // Add the linkage name if we have one. 1415 StringRef LinkageName = SP.getLinkageName(); 1416 if (!LinkageName.empty()) 1417 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, 1418 GlobalValue::getRealLinkageName(LinkageName)); 1419 1420 // Constructors and operators for anonymous aggregates do not have names. 1421 if (!SP.getName().empty()) 1422 addString(SPDie, dwarf::DW_AT_name, SP.getName()); 1423 1424 addSourceLine(SPDie, SP); 1425 1426 // Add the prototype if we have a prototype and we have a C like 1427 // language. 1428 uint16_t Language = getLanguage(); 1429 if (SP.isPrototyped() && 1430 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 || 1431 Language == dwarf::DW_LANG_ObjC)) 1432 addFlag(SPDie, dwarf::DW_AT_prototyped); 1433 1434 DICompositeType SPTy = SP.getType(); 1435 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type && 1436 "the type of a subprogram should be a subroutine"); 1437 1438 DIArray Args = SPTy.getTypeArray(); 1439 // Add a return type. If this is a type like a C/C++ void type we don't add a 1440 // return type. 1441 if (Args.getElement(0)) 1442 addType(SPDie, DIType(Args.getElement(0))); 1443 1444 unsigned VK = SP.getVirtuality(); 1445 if (VK) { 1446 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK); 1447 DIELoc *Block = getDIELoc(); 1448 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 1449 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex()); 1450 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block); 1451 ContainingTypeMap.insert( 1452 std::make_pair(SPDie, resolve(SP.getContainingType()))); 1453 } 1454 1455 if (!SP.isDefinition()) { 1456 addFlag(SPDie, dwarf::DW_AT_declaration); 1457 1458 // Add arguments. Do not add arguments for subprogram definition. They will 1459 // be handled while processing variables. 1460 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) { 1461 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie); 1462 DIType ATy(Args.getElement(i)); 1463 addType(Arg, ATy); 1464 if (ATy.isArtificial()) 1465 addFlag(Arg, dwarf::DW_AT_artificial); 1466 } 1467 } 1468 1469 if (SP.isArtificial()) 1470 addFlag(SPDie, dwarf::DW_AT_artificial); 1471 1472 if (!SP.isLocalToUnit()) 1473 addFlag(SPDie, dwarf::DW_AT_external); 1474 1475 if (SP.isOptimized()) 1476 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized); 1477 1478 if (unsigned isa = Asm->getISAEncoding()) { 1479 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa); 1480 } 1481 1482 if (SP.isLValueReference()) 1483 addFlag(SPDie, dwarf::DW_AT_reference); 1484 1485 if (SP.isRValueReference()) 1486 addFlag(SPDie, dwarf::DW_AT_rvalue_reference); 1487 1488 if (SP.isProtected()) 1489 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1490 dwarf::DW_ACCESS_protected); 1491 else if (SP.isPrivate()) 1492 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1493 dwarf::DW_ACCESS_private); 1494 else 1495 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1496 dwarf::DW_ACCESS_public); 1497 1498 if (SP.isExplicit()) 1499 addFlag(SPDie, dwarf::DW_AT_explicit); 1500 1501 return SPDie; 1502 } 1503 1504 // Return const expression if value is a GEP to access merged global 1505 // constant. e.g. 1506 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0) 1507 static const ConstantExpr *getMergedGlobalExpr(const Value *V) { 1508 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V); 1509 if (!CE || CE->getNumOperands() != 3 || 1510 CE->getOpcode() != Instruction::GetElementPtr) 1511 return NULL; 1512 1513 // First operand points to a global struct. 1514 Value *Ptr = CE->getOperand(0); 1515 if (!isa<GlobalValue>(Ptr) || 1516 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType())) 1517 return NULL; 1518 1519 // Second operand is zero. 1520 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1)); 1521 if (!CI || !CI->isZero()) 1522 return NULL; 1523 1524 // Third operand is offset. 1525 if (!isa<ConstantInt>(CE->getOperand(2))) 1526 return NULL; 1527 1528 return CE; 1529 } 1530 1531 /// createGlobalVariableDIE - create global variable DIE. 1532 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) { 1533 // Check for pre-existence. 1534 if (getDIE(GV)) 1535 return; 1536 1537 assert(GV.isGlobalVariable()); 1538 1539 DIScope GVContext = GV.getContext(); 1540 DIType GTy = GV.getType(); 1541 1542 // If this is a static data member definition, some attributes belong 1543 // to the declaration DIE. 1544 DIE *VariableDIE = NULL; 1545 bool IsStaticMember = false; 1546 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration(); 1547 if (SDMDecl.Verify()) { 1548 assert(SDMDecl.isStaticMember() && "Expected static member decl"); 1549 // We need the declaration DIE that is in the static member's class. 1550 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl); 1551 IsStaticMember = true; 1552 } 1553 1554 // If this is not a static data member definition, create the variable 1555 // DIE and add the initial set of attributes to it. 1556 if (!VariableDIE) { 1557 // Construct the context before querying for the existence of the DIE in 1558 // case such construction creates the DIE. 1559 DIE *ContextDIE = getOrCreateContextDIE(GVContext); 1560 1561 // Add to map. 1562 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV); 1563 1564 // Add name and type. 1565 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName()); 1566 addType(VariableDIE, GTy); 1567 1568 // Add scoping info. 1569 if (!GV.isLocalToUnit()) 1570 addFlag(VariableDIE, dwarf::DW_AT_external); 1571 1572 // Add line number info. 1573 addSourceLine(VariableDIE, GV); 1574 } 1575 1576 // Add location. 1577 bool addToAccelTable = false; 1578 DIE *VariableSpecDIE = NULL; 1579 bool isGlobalVariable = GV.getGlobal() != NULL; 1580 if (isGlobalVariable) { 1581 addToAccelTable = true; 1582 DIELoc *Loc = new (DIEValueAllocator) DIELoc(); 1583 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal()); 1584 if (GV.getGlobal()->isThreadLocal()) { 1585 // FIXME: Make this work with -gsplit-dwarf. 1586 unsigned PointerSize = Asm->getDataLayout().getPointerSize(); 1587 assert((PointerSize == 4 || PointerSize == 8) && 1588 "Add support for other sizes if necessary"); 1589 // Based on GCC's support for TLS: 1590 if (!DD->useSplitDwarf()) { 1591 // 1) Start with a constNu of the appropriate pointer size 1592 addUInt(Loc, dwarf::DW_FORM_data1, 1593 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u); 1594 // 2) containing the (relocated) offset of the TLS variable 1595 // within the module's TLS block. 1596 addExpr(Loc, dwarf::DW_FORM_udata, 1597 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym)); 1598 } else { 1599 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index); 1600 addUInt(Loc, dwarf::DW_FORM_udata, 1601 DU->getAddrPoolIndex(Sym, /* TLS */ true)); 1602 } 1603 // 3) followed by a custom OP to make the debugger do a TLS lookup. 1604 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address); 1605 } else { 1606 DD->addArangeLabel(SymbolCU(this, Sym)); 1607 addOpAddress(Loc, Sym); 1608 } 1609 // Do not create specification DIE if context is either compile unit 1610 // or a subprogram. 1611 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() && 1612 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) { 1613 // Create specification DIE. 1614 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie); 1615 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE); 1616 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Loc); 1617 // A static member's declaration is already flagged as such. 1618 if (!SDMDecl.Verify()) 1619 addFlag(VariableDIE, dwarf::DW_AT_declaration); 1620 } else { 1621 addBlock(VariableDIE, dwarf::DW_AT_location, Loc); 1622 } 1623 // Add the linkage name. 1624 StringRef LinkageName = GV.getLinkageName(); 1625 if (!LinkageName.empty()) 1626 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include: 1627 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and 1628 // TAG_variable. 1629 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE 1630 : VariableDIE, 1631 dwarf::DW_AT_MIPS_linkage_name, 1632 GlobalValue::getRealLinkageName(LinkageName)); 1633 } else if (const ConstantInt *CI = 1634 dyn_cast_or_null<ConstantInt>(GV.getConstant())) { 1635 // AT_const_value was added when the static member was created. To avoid 1636 // emitting AT_const_value multiple times, we only add AT_const_value when 1637 // it is not a static member. 1638 if (!IsStaticMember) 1639 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy)); 1640 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) { 1641 addToAccelTable = true; 1642 // GV is a merged global. 1643 DIELoc *Loc = new (DIEValueAllocator) DIELoc(); 1644 Value *Ptr = CE->getOperand(0); 1645 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr)); 1646 DD->addArangeLabel(SymbolCU(this, Sym)); 1647 addOpAddress(Loc, Sym); 1648 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 1649 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end()); 1650 addUInt(Loc, dwarf::DW_FORM_udata, 1651 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx)); 1652 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus); 1653 addBlock(VariableDIE, dwarf::DW_AT_location, Loc); 1654 } 1655 1656 if (addToAccelTable) { 1657 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE; 1658 addAccelName(GV.getName(), AddrDIE); 1659 1660 // If the linkage name is different than the name, go ahead and output 1661 // that as well into the name table. 1662 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName()) 1663 addAccelName(GV.getLinkageName(), AddrDIE); 1664 } 1665 1666 if (!GV.isLocalToUnit()) 1667 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE, 1668 GV.getContext()); 1669 } 1670 1671 /// constructSubrangeDIE - Construct subrange DIE from DISubrange. 1672 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) { 1673 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer); 1674 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy); 1675 1676 // The LowerBound value defines the lower bounds which is typically zero for 1677 // C/C++. The Count value is the number of elements. Values are 64 bit. If 1678 // Count == -1 then the array is unbounded and we do not emit 1679 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and 1680 // Count == 0, then the array has zero elements in which case we do not emit 1681 // an upper bound. 1682 int64_t LowerBound = SR.getLo(); 1683 int64_t DefaultLowerBound = getDefaultLowerBound(); 1684 int64_t Count = SR.getCount(); 1685 1686 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound) 1687 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound); 1688 1689 if (Count != -1 && Count != 0) 1690 // FIXME: An unbounded array should reference the expression that defines 1691 // the array. 1692 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None, 1693 LowerBound + Count - 1); 1694 } 1695 1696 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType. 1697 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) { 1698 if (CTy.isVector()) 1699 addFlag(&Buffer, dwarf::DW_AT_GNU_vector); 1700 1701 // Emit the element type. 1702 addType(&Buffer, resolve(CTy.getTypeDerivedFrom())); 1703 1704 // Get an anonymous type for index type. 1705 // FIXME: This type should be passed down from the front end 1706 // as different languages may have different sizes for indexes. 1707 DIE *IdxTy = getIndexTyDie(); 1708 if (!IdxTy) { 1709 // Construct an anonymous type for index type. 1710 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie); 1711 addString(IdxTy, dwarf::DW_AT_name, "int"); 1712 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t)); 1713 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, 1714 dwarf::DW_ATE_signed); 1715 setIndexTyDie(IdxTy); 1716 } 1717 1718 // Add subranges to array type. 1719 DIArray Elements = CTy.getTypeArray(); 1720 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 1721 DIDescriptor Element = Elements.getElement(i); 1722 if (Element.getTag() == dwarf::DW_TAG_subrange_type) 1723 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy); 1724 } 1725 } 1726 1727 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType. 1728 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) { 1729 DIArray Elements = CTy.getTypeArray(); 1730 1731 // Add enumerators to enumeration type. 1732 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 1733 DIEnumerator Enum(Elements.getElement(i)); 1734 if (Enum.isEnumerator()) { 1735 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer); 1736 StringRef Name = Enum.getName(); 1737 addString(Enumerator, dwarf::DW_AT_name, Name); 1738 int64_t Value = Enum.getEnumValue(); 1739 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, 1740 Value); 1741 } 1742 } 1743 DIType DTy = resolve(CTy.getTypeDerivedFrom()); 1744 if (DTy) { 1745 addType(&Buffer, DTy); 1746 addFlag(&Buffer, dwarf::DW_AT_enum_class); 1747 } 1748 } 1749 1750 /// constructContainingTypeDIEs - Construct DIEs for types that contain 1751 /// vtables. 1752 void DwarfUnit::constructContainingTypeDIEs() { 1753 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(), 1754 CE = ContainingTypeMap.end(); 1755 CI != CE; ++CI) { 1756 DIE *SPDie = CI->first; 1757 DIDescriptor D(CI->second); 1758 if (!D) 1759 continue; 1760 DIE *NDie = getDIE(D); 1761 if (!NDie) 1762 continue; 1763 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie); 1764 } 1765 } 1766 1767 /// constructVariableDIE - Construct a DIE for the given DbgVariable. 1768 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) { 1769 StringRef Name = DV.getName(); 1770 1771 // Define variable debug information entry. 1772 DIE *VariableDie = new DIE(DV.getTag()); 1773 DbgVariable *AbsVar = DV.getAbstractVariable(); 1774 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL; 1775 if (AbsDIE) 1776 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE); 1777 else { 1778 if (!Name.empty()) 1779 addString(VariableDie, dwarf::DW_AT_name, Name); 1780 addSourceLine(VariableDie, DV.getVariable()); 1781 addType(VariableDie, DV.getType()); 1782 } 1783 1784 if (DV.isArtificial()) 1785 addFlag(VariableDie, dwarf::DW_AT_artificial); 1786 1787 if (isScopeAbstract) { 1788 DV.setDIE(VariableDie); 1789 return VariableDie; 1790 } 1791 1792 // Add variable address. 1793 1794 unsigned Offset = DV.getDotDebugLocOffset(); 1795 if (Offset != ~0U) { 1796 addSectionLabel(VariableDie, dwarf::DW_AT_location, 1797 Asm->GetTempSymbol("debug_loc", Offset)); 1798 DV.setDIE(VariableDie); 1799 return VariableDie; 1800 } 1801 1802 // Check if variable is described by a DBG_VALUE instruction. 1803 if (const MachineInstr *DVInsn = DV.getMInsn()) { 1804 assert(DVInsn->getNumOperands() == 3); 1805 if (DVInsn->getOperand(0).isReg()) { 1806 const MachineOperand RegOp = DVInsn->getOperand(0); 1807 // If the second operand is an immediate, this is an indirect value. 1808 if (DVInsn->getOperand(1).isImm()) { 1809 MachineLocation Location(RegOp.getReg(), 1810 DVInsn->getOperand(1).getImm()); 1811 addVariableAddress(DV, VariableDie, Location); 1812 } else if (RegOp.getReg()) 1813 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg())); 1814 } else if (DVInsn->getOperand(0).isImm()) 1815 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType()); 1816 else if (DVInsn->getOperand(0).isFPImm()) 1817 addConstantFPValue(VariableDie, DVInsn->getOperand(0)); 1818 else if (DVInsn->getOperand(0).isCImm()) 1819 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(), 1820 isUnsignedDIType(DD, DV.getType())); 1821 1822 DV.setDIE(VariableDie); 1823 return VariableDie; 1824 } else { 1825 // .. else use frame index. 1826 int FI = DV.getFrameIndex(); 1827 if (FI != ~0) { 1828 unsigned FrameReg = 0; 1829 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering(); 1830 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg); 1831 MachineLocation Location(FrameReg, Offset); 1832 addVariableAddress(DV, VariableDie, Location); 1833 } 1834 } 1835 1836 DV.setDIE(VariableDie); 1837 return VariableDie; 1838 } 1839 1840 /// constructMemberDIE - Construct member DIE from DIDerivedType. 1841 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) { 1842 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer); 1843 StringRef Name = DT.getName(); 1844 if (!Name.empty()) 1845 addString(MemberDie, dwarf::DW_AT_name, Name); 1846 1847 addType(MemberDie, resolve(DT.getTypeDerivedFrom())); 1848 1849 addSourceLine(MemberDie, DT); 1850 1851 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) { 1852 1853 // For C++, virtual base classes are not at fixed offset. Use following 1854 // expression to extract appropriate offset from vtable. 1855 // BaseAddr = ObAddr + *((*ObAddr) - Offset) 1856 1857 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc(); 1858 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup); 1859 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 1860 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); 1861 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits()); 1862 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus); 1863 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); 1864 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus); 1865 1866 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie); 1867 } else { 1868 uint64_t Size = DT.getSizeInBits(); 1869 uint64_t FieldSize = getBaseTypeSize(DD, DT); 1870 uint64_t OffsetInBytes; 1871 1872 if (Size != FieldSize) { 1873 // Handle bitfield. 1874 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, 1875 getBaseTypeSize(DD, DT) >> 3); 1876 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits()); 1877 1878 uint64_t Offset = DT.getOffsetInBits(); 1879 uint64_t AlignMask = ~(DT.getAlignInBits() - 1); 1880 uint64_t HiMark = (Offset + FieldSize) & AlignMask; 1881 uint64_t FieldOffset = (HiMark - FieldSize); 1882 Offset -= FieldOffset; 1883 1884 // Maybe we need to work from the other end. 1885 if (Asm->getDataLayout().isLittleEndian()) 1886 Offset = FieldSize - (Offset + Size); 1887 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset); 1888 1889 // Here DW_AT_data_member_location points to the anonymous 1890 // field that includes this bit field. 1891 OffsetInBytes = FieldOffset >> 3; 1892 } else 1893 // This is not a bitfield. 1894 OffsetInBytes = DT.getOffsetInBits() >> 3; 1895 1896 if (DD->getDwarfVersion() <= 2) { 1897 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc(); 1898 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); 1899 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes); 1900 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie); 1901 } else 1902 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None, 1903 OffsetInBytes); 1904 } 1905 1906 if (DT.isProtected()) 1907 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1908 dwarf::DW_ACCESS_protected); 1909 else if (DT.isPrivate()) 1910 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1911 dwarf::DW_ACCESS_private); 1912 // Otherwise C++ member and base classes are considered public. 1913 else 1914 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1915 dwarf::DW_ACCESS_public); 1916 if (DT.isVirtual()) 1917 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, 1918 dwarf::DW_VIRTUALITY_virtual); 1919 1920 // Objective-C properties. 1921 if (MDNode *PNode = DT.getObjCProperty()) 1922 if (DIEEntry *PropertyDie = getDIEEntry(PNode)) 1923 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4, 1924 PropertyDie); 1925 1926 if (DT.isArtificial()) 1927 addFlag(MemberDie, dwarf::DW_AT_artificial); 1928 } 1929 1930 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member. 1931 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) { 1932 if (!DT.Verify()) 1933 return NULL; 1934 1935 // Construct the context before querying for the existence of the DIE in case 1936 // such construction creates the DIE. 1937 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext())); 1938 assert(dwarf::isType(ContextDIE->getTag()) && 1939 "Static member should belong to a type."); 1940 1941 DIE *StaticMemberDIE = getDIE(DT); 1942 if (StaticMemberDIE) 1943 return StaticMemberDIE; 1944 1945 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT); 1946 1947 DIType Ty = resolve(DT.getTypeDerivedFrom()); 1948 1949 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName()); 1950 addType(StaticMemberDIE, Ty); 1951 addSourceLine(StaticMemberDIE, DT); 1952 addFlag(StaticMemberDIE, dwarf::DW_AT_external); 1953 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration); 1954 1955 // FIXME: We could omit private if the parent is a class_type, and 1956 // public if the parent is something else. 1957 if (DT.isProtected()) 1958 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1959 dwarf::DW_ACCESS_protected); 1960 else if (DT.isPrivate()) 1961 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1962 dwarf::DW_ACCESS_private); 1963 else 1964 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, 1965 dwarf::DW_ACCESS_public); 1966 1967 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant())) 1968 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty)); 1969 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant())) 1970 addConstantFPValue(StaticMemberDIE, CFP); 1971 1972 return StaticMemberDIE; 1973 } 1974 1975 void DwarfUnit::emitHeader(const MCSection *ASection, 1976 const MCSymbol *ASectionSym) const { 1977 Asm->OutStreamer.AddComment("DWARF version number"); 1978 Asm->EmitInt16(DD->getDwarfVersion()); 1979 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section"); 1980 // We share one abbreviations table across all units so it's always at the 1981 // start of the section. Use a relocatable offset where needed to ensure 1982 // linking doesn't invalidate that offset. 1983 Asm->EmitSectionOffset(ASectionSym, ASectionSym); 1984 Asm->OutStreamer.AddComment("Address Size (in bytes)"); 1985 Asm->EmitInt8(Asm->getDataLayout().getPointerSize()); 1986 } 1987 1988 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) { 1989 // Define start line table label for each Compile Unit. 1990 MCSymbol *LineTableStartSym = 1991 Asm->GetTempSymbol("line_table_start", getUniqueID()); 1992 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym, 1993 getUniqueID()); 1994 1995 // Use a single line table if we are generating assembly. 1996 bool UseTheFirstCU = 1997 Asm->OutStreamer.hasRawTextSupport() || (getUniqueID() == 0); 1998 1999 stmtListIndex = UnitDie->getValues().size(); 2000 2001 // DW_AT_stmt_list is a offset of line number information for this 2002 // compile unit in debug_line section. For split dwarf this is 2003 // left in the skeleton CU and so not included. 2004 // The line table entries are not always emitted in assembly, so it 2005 // is not okay to use line_table_start here. 2006 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) 2007 addSectionLabel(UnitDie.get(), dwarf::DW_AT_stmt_list, 2008 UseTheFirstCU ? DwarfLineSectionSym : LineTableStartSym); 2009 else if (UseTheFirstCU) 2010 addSectionOffset(UnitDie.get(), dwarf::DW_AT_stmt_list, 0); 2011 else 2012 addSectionDelta(UnitDie.get(), dwarf::DW_AT_stmt_list, LineTableStartSym, 2013 DwarfLineSectionSym); 2014 } 2015 2016 void DwarfCompileUnit::applyStmtList(DIE &D) { 2017 D.addValue(dwarf::DW_AT_stmt_list, 2018 UnitDie->getAbbrev().getData()[stmtListIndex].getForm(), 2019 UnitDie->getValues()[stmtListIndex]); 2020 } 2021 2022 void DwarfTypeUnit::emitHeader(const MCSection *ASection, 2023 const MCSymbol *ASectionSym) const { 2024 DwarfUnit::emitHeader(ASection, ASectionSym); 2025 Asm->OutStreamer.AddComment("Type Signature"); 2026 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature)); 2027 Asm->OutStreamer.AddComment("Type DIE Offset"); 2028 // In a skeleton type unit there is no type DIE so emit a zero offset. 2029 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0, 2030 sizeof(Ty->getOffset())); 2031 } 2032 2033 void DwarfTypeUnit::initSection(const MCSection *Section) { 2034 assert(!this->Section); 2035 this->Section = Section; 2036 // Since each type unit is contained in its own COMDAT section, the begin 2037 // label and the section label are the same. Using the begin label emission in 2038 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but 2039 // the only other alternative of lazily constructing start-of-section labels 2040 // and storing a mapping in DwarfDebug (or AsmPrinter). 2041 this->SectionSym = this->LabelBegin = 2042 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID()); 2043 this->LabelEnd = 2044 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID()); 2045 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID()); 2046 } 2047