DwarfUnit.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721
  1. //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains support for constructing a dwarf compile unit.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "DwarfUnit.h"
  13. #include "AddressPool.h"
  14. #include "DwarfCompileUnit.h"
  15. #include "DwarfDebug.h"
  16. #include "DwarfExpression.h"
  17. #include "llvm/ADT/APFloat.h"
  18. #include "llvm/ADT/APInt.h"
  19. #include "llvm/ADT/None.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/iterator_range.h"
  22. #include "llvm/CodeGen/MachineFunction.h"
  23. #include "llvm/CodeGen/MachineOperand.h"
  24. #include "llvm/CodeGen/TargetRegisterInfo.h"
  25. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/GlobalValue.h"
  29. #include "llvm/IR/Metadata.h"
  30. #include "llvm/MC/MCAsmInfo.h"
  31. #include "llvm/MC/MCContext.h"
  32. #include "llvm/MC/MCDwarf.h"
  33. #include "llvm/MC/MCSection.h"
  34. #include "llvm/MC/MCStreamer.h"
  35. #include "llvm/MC/MachineLocation.h"
  36. #include "llvm/Support/Casting.h"
  37. #include "llvm/Support/CommandLine.h"
  38. #include "llvm/Target/TargetLoweringObjectFile.h"
  39. #include <cassert>
  40. #include <cstdint>
  41. #include <string>
  42. #include <utility>
  43. using namespace llvm;
  44. #define DEBUG_TYPE "dwarfdebug"
  45. DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP,
  46. DwarfCompileUnit &CU,
  47. DIELoc &DIE)
  48. : DwarfExpression(AP.getDwarfVersion(), CU), AP(AP),
  49. DIE(DIE) {}
  50. void DIEDwarfExpression::emitOp(uint8_t Op, const char* Comment) {
  51. CU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
  52. }
  53. void DIEDwarfExpression::emitSigned(int64_t Value) {
  54. CU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
  55. }
  56. void DIEDwarfExpression::emitUnsigned(uint64_t Value) {
  57. CU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
  58. }
  59. void DIEDwarfExpression::emitData1(uint8_t Value) {
  60. CU.addUInt(DIE, dwarf::DW_FORM_data1, Value);
  61. }
  62. void DIEDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
  63. CU.addBaseTypeRef(DIE, Idx);
  64. }
  65. bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
  66. unsigned MachineReg) {
  67. return MachineReg == TRI.getFrameRegister(*AP.MF);
  68. }
  69. DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node,
  70. AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
  71. : DIEUnit(A->getDwarfVersion(), A->MAI->getCodePointerSize(), UnitTag),
  72. CUNode(Node), Asm(A), DD(DW), DU(DWU), IndexTyDie(nullptr) {
  73. }
  74. DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A,
  75. DwarfDebug *DW, DwarfFile *DWU,
  76. MCDwarfDwoLineTable *SplitLineTable)
  77. : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU),
  78. SplitLineTable(SplitLineTable) {
  79. }
  80. DwarfUnit::~DwarfUnit() {
  81. for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
  82. DIEBlocks[j]->~DIEBlock();
  83. for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
  84. DIELocs[j]->~DIELoc();
  85. }
  86. int64_t DwarfUnit::getDefaultLowerBound() const {
  87. switch (getLanguage()) {
  88. default:
  89. break;
  90. // The languages below have valid values in all DWARF versions.
  91. case dwarf::DW_LANG_C:
  92. case dwarf::DW_LANG_C89:
  93. case dwarf::DW_LANG_C_plus_plus:
  94. return 0;
  95. case dwarf::DW_LANG_Fortran77:
  96. case dwarf::DW_LANG_Fortran90:
  97. return 1;
  98. // The languages below have valid values only if the DWARF version >= 3.
  99. case dwarf::DW_LANG_C99:
  100. case dwarf::DW_LANG_ObjC:
  101. case dwarf::DW_LANG_ObjC_plus_plus:
  102. if (DD->getDwarfVersion() >= 3)
  103. return 0;
  104. break;
  105. case dwarf::DW_LANG_Fortran95:
  106. if (DD->getDwarfVersion() >= 3)
  107. return 1;
  108. break;
  109. // Starting with DWARF v4, all defined languages have valid values.
  110. case dwarf::DW_LANG_D:
  111. case dwarf::DW_LANG_Java:
  112. case dwarf::DW_LANG_Python:
  113. case dwarf::DW_LANG_UPC:
  114. if (DD->getDwarfVersion() >= 4)
  115. return 0;
  116. break;
  117. case dwarf::DW_LANG_Ada83:
  118. case dwarf::DW_LANG_Ada95:
  119. case dwarf::DW_LANG_Cobol74:
  120. case dwarf::DW_LANG_Cobol85:
  121. case dwarf::DW_LANG_Modula2:
  122. case dwarf::DW_LANG_Pascal83:
  123. case dwarf::DW_LANG_PLI:
  124. if (DD->getDwarfVersion() >= 4)
  125. return 1;
  126. break;
  127. // The languages below are new in DWARF v5.
  128. case dwarf::DW_LANG_BLISS:
  129. case dwarf::DW_LANG_C11:
  130. case dwarf::DW_LANG_C_plus_plus_03:
  131. case dwarf::DW_LANG_C_plus_plus_11:
  132. case dwarf::DW_LANG_C_plus_plus_14:
  133. case dwarf::DW_LANG_Dylan:
  134. case dwarf::DW_LANG_Go:
  135. case dwarf::DW_LANG_Haskell:
  136. case dwarf::DW_LANG_OCaml:
  137. case dwarf::DW_LANG_OpenCL:
  138. case dwarf::DW_LANG_RenderScript:
  139. case dwarf::DW_LANG_Rust:
  140. case dwarf::DW_LANG_Swift:
  141. if (DD->getDwarfVersion() >= 5)
  142. return 0;
  143. break;
  144. case dwarf::DW_LANG_Fortran03:
  145. case dwarf::DW_LANG_Fortran08:
  146. case dwarf::DW_LANG_Julia:
  147. case dwarf::DW_LANG_Modula3:
  148. if (DD->getDwarfVersion() >= 5)
  149. return 1;
  150. break;
  151. }
  152. return -1;
  153. }
  154. /// Check whether the DIE for this MDNode can be shared across CUs.
  155. bool DwarfUnit::isShareableAcrossCUs(const DINode *D) const {
  156. // When the MDNode can be part of the type system, the DIE can be shared
  157. // across CUs.
  158. // Combining type units and cross-CU DIE sharing is lower value (since
  159. // cross-CU DIE sharing is used in LTO and removes type redundancy at that
  160. // level already) but may be implementable for some value in projects
  161. // building multiple independent libraries with LTO and then linking those
  162. // together.
  163. if (isDwoUnit() && !DD->shareAcrossDWOCUs())
  164. return false;
  165. return (isa<DIType>(D) ||
  166. (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
  167. !DD->generateTypeUnits();
  168. }
  169. DIE *DwarfUnit::getDIE(const DINode *D) const {
  170. if (isShareableAcrossCUs(D))
  171. return DU->getDIE(D);
  172. return MDNodeToDieMap.lookup(D);
  173. }
  174. void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
  175. if (isShareableAcrossCUs(Desc)) {
  176. DU->insertDIE(Desc, D);
  177. return;
  178. }
  179. MDNodeToDieMap.insert(std::make_pair(Desc, D));
  180. }
  181. void DwarfUnit::insertDIE(DIE *D) {
  182. MDNodeToDieMap.insert(std::make_pair(nullptr, D));
  183. }
  184. void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
  185. if (DD->getDwarfVersion() >= 4)
  186. Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present,
  187. DIEInteger(1));
  188. else
  189. Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag,
  190. DIEInteger(1));
  191. }
  192. void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
  193. Optional<dwarf::Form> Form, uint64_t Integer) {
  194. if (!Form)
  195. Form = DIEInteger::BestForm(false, Integer);
  196. assert(Form != dwarf::DW_FORM_implicit_const &&
  197. "DW_FORM_implicit_const is used only for signed integers");
  198. Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
  199. }
  200. void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
  201. uint64_t Integer) {
  202. addUInt(Block, (dwarf::Attribute)0, Form, Integer);
  203. }
  204. void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
  205. Optional<dwarf::Form> Form, int64_t Integer) {
  206. if (!Form)
  207. Form = DIEInteger::BestForm(true, Integer);
  208. Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
  209. }
  210. void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
  211. int64_t Integer) {
  212. addSInt(Die, (dwarf::Attribute)0, Form, Integer);
  213. }
  214. void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
  215. StringRef String) {
  216. if (CUNode->isDebugDirectivesOnly())
  217. return;
  218. if (DD->useInlineStrings()) {
  219. Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_string,
  220. new (DIEValueAllocator)
  221. DIEInlineString(String, DIEValueAllocator));
  222. return;
  223. }
  224. dwarf::Form IxForm =
  225. isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp;
  226. auto StringPoolEntry =
  227. useSegmentedStringOffsetsTable() || IxForm == dwarf::DW_FORM_GNU_str_index
  228. ? DU->getStringPool().getIndexedEntry(*Asm, String)
  229. : DU->getStringPool().getEntry(*Asm, String);
  230. // For DWARF v5 and beyond, use the smallest strx? form possible.
  231. if (useSegmentedStringOffsetsTable()) {
  232. IxForm = dwarf::DW_FORM_strx1;
  233. unsigned Index = StringPoolEntry.getIndex();
  234. if (Index > 0xffffff)
  235. IxForm = dwarf::DW_FORM_strx4;
  236. else if (Index > 0xffff)
  237. IxForm = dwarf::DW_FORM_strx3;
  238. else if (Index > 0xff)
  239. IxForm = dwarf::DW_FORM_strx2;
  240. }
  241. Die.addValue(DIEValueAllocator, Attribute, IxForm,
  242. DIEString(StringPoolEntry));
  243. }
  244. DIEValueList::value_iterator DwarfUnit::addLabel(DIEValueList &Die,
  245. dwarf::Attribute Attribute,
  246. dwarf::Form Form,
  247. const MCSymbol *Label) {
  248. return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label));
  249. }
  250. void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
  251. addLabel(Die, (dwarf::Attribute)0, Form, Label);
  252. }
  253. void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
  254. uint64_t Integer) {
  255. if (DD->getDwarfVersion() >= 4)
  256. addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
  257. else
  258. addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
  259. }
  260. Optional<MD5::MD5Result> DwarfUnit::getMD5AsBytes(const DIFile *File) const {
  261. assert(File);
  262. if (DD->getDwarfVersion() < 5)
  263. return None;
  264. Optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
  265. if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
  266. return None;
  267. // Convert the string checksum to an MD5Result for the streamer.
  268. // The verifier validates the checksum so we assume it's okay.
  269. // An MD5 checksum is 16 bytes.
  270. std::string ChecksumString = fromHex(Checksum->Value);
  271. MD5::MD5Result CKMem;
  272. std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.Bytes.data());
  273. return CKMem;
  274. }
  275. unsigned DwarfTypeUnit::getOrCreateSourceID(const DIFile *File) {
  276. if (!SplitLineTable)
  277. return getCU().getOrCreateSourceID(File);
  278. if (!UsedLineTable) {
  279. UsedLineTable = true;
  280. // This is a split type unit that needs a line table.
  281. addSectionOffset(getUnitDie(), dwarf::DW_AT_stmt_list, 0);
  282. }
  283. return SplitLineTable->getFile(File->getDirectory(), File->getFilename(),
  284. getMD5AsBytes(File),
  285. Asm->OutContext.getDwarfVersion(),
  286. File->getSource());
  287. }
  288. void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
  289. if (DD->getDwarfVersion() >= 5) {
  290. addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addrx);
  291. addUInt(Die, dwarf::DW_FORM_addrx, DD->getAddressPool().getIndex(Sym));
  292. return;
  293. }
  294. if (DD->useSplitDwarf()) {
  295. addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
  296. addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
  297. DD->getAddressPool().getIndex(Sym));
  298. return;
  299. }
  300. addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
  301. addLabel(Die, dwarf::DW_FORM_udata, Sym);
  302. }
  303. void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
  304. const MCSymbol *Hi, const MCSymbol *Lo) {
  305. Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4,
  306. new (DIEValueAllocator) DIEDelta(Hi, Lo));
  307. }
  308. void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
  309. addDIEEntry(Die, Attribute, DIEEntry(Entry));
  310. }
  311. void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
  312. // Flag the type unit reference as a declaration so that if it contains
  313. // members (implicit special members, static data member definitions, member
  314. // declarations for definitions in this CU, etc) consumers don't get confused
  315. // and think this is a full definition.
  316. addFlag(Die, dwarf::DW_AT_declaration);
  317. Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature,
  318. dwarf::DW_FORM_ref_sig8, DIEInteger(Signature));
  319. }
  320. void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
  321. DIEEntry Entry) {
  322. const DIEUnit *CU = Die.getUnit();
  323. const DIEUnit *EntryCU = Entry.getEntry().getUnit();
  324. if (!CU)
  325. // We assume that Die belongs to this CU, if it is not linked to any CU yet.
  326. CU = getUnitDie().getUnit();
  327. if (!EntryCU)
  328. EntryCU = getUnitDie().getUnit();
  329. Die.addValue(DIEValueAllocator, Attribute,
  330. EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
  331. Entry);
  332. }
  333. DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
  334. DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag));
  335. if (N)
  336. insertDIE(N, &Die);
  337. return Die;
  338. }
  339. void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
  340. Loc->ComputeSize(Asm);
  341. DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
  342. Die.addValue(DIEValueAllocator, Attribute,
  343. Loc->BestForm(DD->getDwarfVersion()), Loc);
  344. }
  345. void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
  346. DIEBlock *Block) {
  347. Block->ComputeSize(Asm);
  348. DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
  349. Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block);
  350. }
  351. void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, const DIFile *File) {
  352. if (Line == 0)
  353. return;
  354. unsigned FileID = getOrCreateSourceID(File);
  355. addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
  356. addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
  357. }
  358. void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
  359. assert(V);
  360. addSourceLine(Die, V->getLine(), V->getFile());
  361. }
  362. void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
  363. assert(G);
  364. addSourceLine(Die, G->getLine(), G->getFile());
  365. }
  366. void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
  367. assert(SP);
  368. addSourceLine(Die, SP->getLine(), SP->getFile());
  369. }
  370. void DwarfUnit::addSourceLine(DIE &Die, const DILabel *L) {
  371. assert(L);
  372. addSourceLine(Die, L->getLine(), L->getFile());
  373. }
  374. void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
  375. assert(Ty);
  376. addSourceLine(Die, Ty->getLine(), Ty->getFile());
  377. }
  378. void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
  379. assert(Ty);
  380. addSourceLine(Die, Ty->getLine(), Ty->getFile());
  381. }
  382. /// Return true if type encoding is unsigned.
  383. static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
  384. if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
  385. // FIXME: Enums without a fixed underlying type have unknown signedness
  386. // here, leading to incorrectly emitted constants.
  387. if (CTy->getTag() == dwarf::DW_TAG_enumeration_type)
  388. return false;
  389. // (Pieces of) aggregate types that get hacked apart by SROA may be
  390. // represented by a constant. Encode them as unsigned bytes.
  391. return true;
  392. }
  393. if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
  394. dwarf::Tag T = (dwarf::Tag)Ty->getTag();
  395. // Encode pointer constants as unsigned bytes. This is used at least for
  396. // null pointer constant emission.
  397. // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
  398. // here, but accept them for now due to a bug in SROA producing bogus
  399. // dbg.values.
  400. if (T == dwarf::DW_TAG_pointer_type ||
  401. T == dwarf::DW_TAG_ptr_to_member_type ||
  402. T == dwarf::DW_TAG_reference_type ||
  403. T == dwarf::DW_TAG_rvalue_reference_type)
  404. return true;
  405. assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
  406. T == dwarf::DW_TAG_volatile_type ||
  407. T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type);
  408. assert(DTy->getBaseType() && "Expected valid base type");
  409. return isUnsignedDIType(DD, DTy->getBaseType());
  410. }
  411. auto *BTy = cast<DIBasicType>(Ty);
  412. unsigned Encoding = BTy->getEncoding();
  413. assert((Encoding == dwarf::DW_ATE_unsigned ||
  414. Encoding == dwarf::DW_ATE_unsigned_char ||
  415. Encoding == dwarf::DW_ATE_signed ||
  416. Encoding == dwarf::DW_ATE_signed_char ||
  417. Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
  418. Encoding == dwarf::DW_ATE_boolean ||
  419. (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
  420. Ty->getName() == "decltype(nullptr)")) &&
  421. "Unsupported encoding");
  422. return Encoding == dwarf::DW_ATE_unsigned ||
  423. Encoding == dwarf::DW_ATE_unsigned_char ||
  424. Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
  425. Ty->getTag() == dwarf::DW_TAG_unspecified_type;
  426. }
  427. void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
  428. assert(MO.isFPImm() && "Invalid machine operand!");
  429. DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
  430. APFloat FPImm = MO.getFPImm()->getValueAPF();
  431. // Get the raw data form of the floating point.
  432. const APInt FltVal = FPImm.bitcastToAPInt();
  433. const char *FltPtr = (const char *)FltVal.getRawData();
  434. int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
  435. bool LittleEndian = Asm->getDataLayout().isLittleEndian();
  436. int Incr = (LittleEndian ? 1 : -1);
  437. int Start = (LittleEndian ? 0 : NumBytes - 1);
  438. int Stop = (LittleEndian ? NumBytes : -1);
  439. // Output the constant to DWARF one byte at a time.
  440. for (; Start != Stop; Start += Incr)
  441. addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
  442. addBlock(Die, dwarf::DW_AT_const_value, Block);
  443. }
  444. void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
  445. // Pass this down to addConstantValue as an unsigned bag of bits.
  446. addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
  447. }
  448. void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
  449. const DIType *Ty) {
  450. addConstantValue(Die, CI->getValue(), Ty);
  451. }
  452. void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
  453. const DIType *Ty) {
  454. assert(MO.isImm() && "Invalid machine operand!");
  455. addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
  456. }
  457. void DwarfUnit::addConstantValue(DIE &Die, uint64_t Val, const DIType *Ty) {
  458. addConstantValue(Die, isUnsignedDIType(DD, Ty), Val);
  459. }
  460. void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
  461. // FIXME: This is a bit conservative/simple - it emits negative values always
  462. // sign extended to 64 bits rather than minimizing the number of bytes.
  463. addUInt(Die, dwarf::DW_AT_const_value,
  464. Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
  465. }
  466. void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
  467. addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
  468. }
  469. void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
  470. unsigned CIBitWidth = Val.getBitWidth();
  471. if (CIBitWidth <= 64) {
  472. addConstantValue(Die, Unsigned,
  473. Unsigned ? Val.getZExtValue() : Val.getSExtValue());
  474. return;
  475. }
  476. DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
  477. // Get the raw data form of the large APInt.
  478. const uint64_t *Ptr64 = Val.getRawData();
  479. int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
  480. bool LittleEndian = Asm->getDataLayout().isLittleEndian();
  481. // Output the constant to DWARF one byte at a time.
  482. for (int i = 0; i < NumBytes; i++) {
  483. uint8_t c;
  484. if (LittleEndian)
  485. c = Ptr64[i / 8] >> (8 * (i & 7));
  486. else
  487. c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
  488. addUInt(*Block, dwarf::DW_FORM_data1, c);
  489. }
  490. addBlock(Die, dwarf::DW_AT_const_value, Block);
  491. }
  492. void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
  493. if (!LinkageName.empty())
  494. addString(Die,
  495. DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
  496. : dwarf::DW_AT_MIPS_linkage_name,
  497. GlobalValue::dropLLVMManglingEscape(LinkageName));
  498. }
  499. void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
  500. // Add template parameters.
  501. for (const auto *Element : TParams) {
  502. if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
  503. constructTemplateTypeParameterDIE(Buffer, TTP);
  504. else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
  505. constructTemplateValueParameterDIE(Buffer, TVP);
  506. }
  507. }
  508. /// Add thrown types.
  509. void DwarfUnit::addThrownTypes(DIE &Die, DINodeArray ThrownTypes) {
  510. for (const auto *Ty : ThrownTypes) {
  511. DIE &TT = createAndAddDIE(dwarf::DW_TAG_thrown_type, Die);
  512. addType(TT, cast<DIType>(Ty));
  513. }
  514. }
  515. DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
  516. if (!Context || isa<DIFile>(Context))
  517. return &getUnitDie();
  518. if (auto *T = dyn_cast<DIType>(Context))
  519. return getOrCreateTypeDIE(T);
  520. if (auto *NS = dyn_cast<DINamespace>(Context))
  521. return getOrCreateNameSpace(NS);
  522. if (auto *SP = dyn_cast<DISubprogram>(Context))
  523. return getOrCreateSubprogramDIE(SP);
  524. if (auto *M = dyn_cast<DIModule>(Context))
  525. return getOrCreateModule(M);
  526. return getDIE(Context);
  527. }
  528. DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
  529. auto *Context = Ty->getScope();
  530. DIE *ContextDIE = getOrCreateContextDIE(Context);
  531. if (DIE *TyDIE = getDIE(Ty))
  532. return TyDIE;
  533. // Create new type.
  534. DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
  535. constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
  536. updateAcceleratorTables(Context, Ty, TyDIE);
  537. return &TyDIE;
  538. }
  539. DIE *DwarfUnit::createTypeDIE(const DIScope *Context, DIE &ContextDIE,
  540. const DIType *Ty) {
  541. // Create new type.
  542. DIE &TyDIE = createAndAddDIE(Ty->getTag(), ContextDIE, Ty);
  543. updateAcceleratorTables(Context, Ty, TyDIE);
  544. if (auto *BT = dyn_cast<DIBasicType>(Ty))
  545. constructTypeDIE(TyDIE, BT);
  546. else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
  547. constructTypeDIE(TyDIE, STy);
  548. else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
  549. if (DD->generateTypeUnits() && !Ty->isForwardDecl() &&
  550. (Ty->getRawName() || CTy->getRawIdentifier())) {
  551. // Skip updating the accelerator tables since this is not the full type.
  552. if (MDString *TypeId = CTy->getRawIdentifier())
  553. DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
  554. else {
  555. auto X = DD->enterNonTypeUnitContext();
  556. finishNonUnitTypeDIE(TyDIE, CTy);
  557. }
  558. return &TyDIE;
  559. }
  560. constructTypeDIE(TyDIE, CTy);
  561. } else {
  562. constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
  563. }
  564. return &TyDIE;
  565. }
  566. DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
  567. if (!TyNode)
  568. return nullptr;
  569. auto *Ty = cast<DIType>(TyNode);
  570. // DW_TAG_restrict_type is not supported in DWARF2
  571. if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
  572. return getOrCreateTypeDIE(cast<DIDerivedType>(Ty)->getBaseType());
  573. // DW_TAG_atomic_type is not supported in DWARF < 5
  574. if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
  575. return getOrCreateTypeDIE(cast<DIDerivedType>(Ty)->getBaseType());
  576. // Construct the context before querying for the existence of the DIE in case
  577. // such construction creates the DIE.
  578. auto *Context = Ty->getScope();
  579. DIE *ContextDIE = getOrCreateContextDIE(Context);
  580. assert(ContextDIE);
  581. if (DIE *TyDIE = getDIE(Ty))
  582. return TyDIE;
  583. return static_cast<DwarfUnit *>(ContextDIE->getUnit())
  584. ->createTypeDIE(Context, *ContextDIE, Ty);
  585. }
  586. void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
  587. const DIType *Ty, const DIE &TyDIE) {
  588. if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
  589. bool IsImplementation = false;
  590. if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
  591. // A runtime language of 0 actually means C/C++ and that any
  592. // non-negative value is some version of Objective-C/C++.
  593. IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
  594. }
  595. unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
  596. DD->addAccelType(*CUNode, Ty->getName(), TyDIE, Flags);
  597. if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
  598. isa<DINamespace>(Context) || isa<DICommonBlock>(Context))
  599. addGlobalType(Ty, TyDIE, Context);
  600. }
  601. }
  602. void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
  603. dwarf::Attribute Attribute) {
  604. assert(Ty && "Trying to add a type that doesn't exist?");
  605. addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
  606. }
  607. std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
  608. if (!Context)
  609. return "";
  610. // FIXME: Decide whether to implement this for non-C++ languages.
  611. if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
  612. return "";
  613. std::string CS;
  614. SmallVector<const DIScope *, 1> Parents;
  615. while (!isa<DICompileUnit>(Context)) {
  616. Parents.push_back(Context);
  617. if (const DIScope *S = Context->getScope())
  618. Context = S;
  619. else
  620. // Structure, etc types will have a NULL context if they're at the top
  621. // level.
  622. break;
  623. }
  624. // Reverse iterate over our list to go from the outermost construct to the
  625. // innermost.
  626. for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
  627. StringRef Name = Ctx->getName();
  628. if (Name.empty() && isa<DINamespace>(Ctx))
  629. Name = "(anonymous namespace)";
  630. if (!Name.empty()) {
  631. CS += Name;
  632. CS += "::";
  633. }
  634. }
  635. return CS;
  636. }
  637. void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
  638. // Get core information.
  639. StringRef Name = BTy->getName();
  640. // Add name if not anonymous or intermediate type.
  641. if (!Name.empty())
  642. addString(Buffer, dwarf::DW_AT_name, Name);
  643. // An unspecified type only has a name attribute.
  644. if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
  645. return;
  646. addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
  647. BTy->getEncoding());
  648. uint64_t Size = BTy->getSizeInBits() >> 3;
  649. addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
  650. if (BTy->isBigEndian())
  651. addUInt(Buffer, dwarf::DW_AT_endianity, None, dwarf::DW_END_big);
  652. else if (BTy->isLittleEndian())
  653. addUInt(Buffer, dwarf::DW_AT_endianity, None, dwarf::DW_END_little);
  654. }
  655. void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
  656. // Get core information.
  657. StringRef Name = DTy->getName();
  658. uint64_t Size = DTy->getSizeInBits() >> 3;
  659. uint16_t Tag = Buffer.getTag();
  660. // Map to main type, void will not have a type.
  661. const DIType *FromTy = DTy->getBaseType();
  662. if (FromTy)
  663. addType(Buffer, FromTy);
  664. // Add name if not anonymous or intermediate type.
  665. if (!Name.empty())
  666. addString(Buffer, dwarf::DW_AT_name, Name);
  667. // Add size if non-zero (derived types might be zero-sized.)
  668. if (Size && Tag != dwarf::DW_TAG_pointer_type
  669. && Tag != dwarf::DW_TAG_ptr_to_member_type
  670. && Tag != dwarf::DW_TAG_reference_type
  671. && Tag != dwarf::DW_TAG_rvalue_reference_type)
  672. addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
  673. if (Tag == dwarf::DW_TAG_ptr_to_member_type)
  674. addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
  675. *getOrCreateTypeDIE(cast<DIDerivedType>(DTy)->getClassType()));
  676. // Add source line info if available and TyDesc is not a forward declaration.
  677. if (!DTy->isForwardDecl())
  678. addSourceLine(Buffer, DTy);
  679. // If DWARF address space value is other than None, add it. The IR
  680. // verifier checks that DWARF address space only exists for pointer
  681. // or reference types.
  682. if (DTy->getDWARFAddressSpace())
  683. addUInt(Buffer, dwarf::DW_AT_address_class, dwarf::DW_FORM_data4,
  684. DTy->getDWARFAddressSpace().getValue());
  685. }
  686. void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
  687. for (unsigned i = 1, N = Args.size(); i < N; ++i) {
  688. const DIType *Ty = Args[i];
  689. if (!Ty) {
  690. assert(i == N-1 && "Unspecified parameter must be the last argument");
  691. createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
  692. } else {
  693. DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
  694. addType(Arg, Ty);
  695. if (Ty->isArtificial())
  696. addFlag(Arg, dwarf::DW_AT_artificial);
  697. }
  698. }
  699. }
  700. void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
  701. // Add return type. A void return won't have a type.
  702. auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
  703. if (Elements.size())
  704. if (auto RTy = Elements[0])
  705. addType(Buffer, RTy);
  706. bool isPrototyped = true;
  707. if (Elements.size() == 2 && !Elements[1])
  708. isPrototyped = false;
  709. constructSubprogramArguments(Buffer, Elements);
  710. // Add prototype flag if we're dealing with a C language and the function has
  711. // been prototyped.
  712. uint16_t Language = getLanguage();
  713. if (isPrototyped &&
  714. (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
  715. Language == dwarf::DW_LANG_ObjC))
  716. addFlag(Buffer, dwarf::DW_AT_prototyped);
  717. // Add a DW_AT_calling_convention if this has an explicit convention.
  718. if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
  719. addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
  720. CTy->getCC());
  721. if (CTy->isLValueReference())
  722. addFlag(Buffer, dwarf::DW_AT_reference);
  723. if (CTy->isRValueReference())
  724. addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
  725. }
  726. void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
  727. // Add name if not anonymous or intermediate type.
  728. StringRef Name = CTy->getName();
  729. uint64_t Size = CTy->getSizeInBits() >> 3;
  730. uint16_t Tag = Buffer.getTag();
  731. switch (Tag) {
  732. case dwarf::DW_TAG_array_type:
  733. constructArrayTypeDIE(Buffer, CTy);
  734. break;
  735. case dwarf::DW_TAG_enumeration_type:
  736. constructEnumTypeDIE(Buffer, CTy);
  737. break;
  738. case dwarf::DW_TAG_variant_part:
  739. case dwarf::DW_TAG_structure_type:
  740. case dwarf::DW_TAG_union_type:
  741. case dwarf::DW_TAG_class_type: {
  742. // Emit the discriminator for a variant part.
  743. DIDerivedType *Discriminator = nullptr;
  744. if (Tag == dwarf::DW_TAG_variant_part) {
  745. Discriminator = CTy->getDiscriminator();
  746. if (Discriminator) {
  747. // DWARF says:
  748. // If the variant part has a discriminant, the discriminant is
  749. // represented by a separate debugging information entry which is
  750. // a child of the variant part entry.
  751. DIE &DiscMember = constructMemberDIE(Buffer, Discriminator);
  752. addDIEEntry(Buffer, dwarf::DW_AT_discr, DiscMember);
  753. }
  754. }
  755. // Add elements to structure type.
  756. DINodeArray Elements = CTy->getElements();
  757. for (const auto *Element : Elements) {
  758. if (!Element)
  759. continue;
  760. if (auto *SP = dyn_cast<DISubprogram>(Element))
  761. getOrCreateSubprogramDIE(SP);
  762. else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
  763. if (DDTy->getTag() == dwarf::DW_TAG_friend) {
  764. DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
  765. addType(ElemDie, DDTy->getBaseType(), dwarf::DW_AT_friend);
  766. } else if (DDTy->isStaticMember()) {
  767. getOrCreateStaticMemberDIE(DDTy);
  768. } else if (Tag == dwarf::DW_TAG_variant_part) {
  769. // When emitting a variant part, wrap each member in
  770. // DW_TAG_variant.
  771. DIE &Variant = createAndAddDIE(dwarf::DW_TAG_variant, Buffer);
  772. if (const ConstantInt *CI =
  773. dyn_cast_or_null<ConstantInt>(DDTy->getDiscriminantValue())) {
  774. if (isUnsignedDIType(DD, Discriminator->getBaseType()))
  775. addUInt(Variant, dwarf::DW_AT_discr_value, None, CI->getZExtValue());
  776. else
  777. addSInt(Variant, dwarf::DW_AT_discr_value, None, CI->getSExtValue());
  778. }
  779. constructMemberDIE(Variant, DDTy);
  780. } else {
  781. constructMemberDIE(Buffer, DDTy);
  782. }
  783. } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
  784. DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
  785. StringRef PropertyName = Property->getName();
  786. addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
  787. if (Property->getType())
  788. addType(ElemDie, Property->getType());
  789. addSourceLine(ElemDie, Property);
  790. StringRef GetterName = Property->getGetterName();
  791. if (!GetterName.empty())
  792. addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
  793. StringRef SetterName = Property->getSetterName();
  794. if (!SetterName.empty())
  795. addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
  796. if (unsigned PropertyAttributes = Property->getAttributes())
  797. addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
  798. PropertyAttributes);
  799. } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
  800. if (Composite->getTag() == dwarf::DW_TAG_variant_part) {
  801. DIE &VariantPart = createAndAddDIE(Composite->getTag(), Buffer);
  802. constructTypeDIE(VariantPart, Composite);
  803. }
  804. }
  805. }
  806. if (CTy->isAppleBlockExtension())
  807. addFlag(Buffer, dwarf::DW_AT_APPLE_block);
  808. if (CTy->getExportSymbols())
  809. addFlag(Buffer, dwarf::DW_AT_export_symbols);
  810. // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
  811. // inside C++ composite types to point to the base class with the vtable.
  812. // Rust uses DW_AT_containing_type to link a vtable to the type
  813. // for which it was created.
  814. if (auto *ContainingType = CTy->getVTableHolder())
  815. addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
  816. *getOrCreateTypeDIE(ContainingType));
  817. if (CTy->isObjcClassComplete())
  818. addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
  819. // Add template parameters to a class, structure or union types.
  820. // FIXME: The support isn't in the metadata for this yet.
  821. if (Tag == dwarf::DW_TAG_class_type ||
  822. Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
  823. addTemplateParams(Buffer, CTy->getTemplateParams());
  824. // Add the type's non-standard calling convention.
  825. uint8_t CC = 0;
  826. if (CTy->isTypePassByValue())
  827. CC = dwarf::DW_CC_pass_by_value;
  828. else if (CTy->isTypePassByReference())
  829. CC = dwarf::DW_CC_pass_by_reference;
  830. if (CC)
  831. addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
  832. CC);
  833. break;
  834. }
  835. default:
  836. break;
  837. }
  838. // Add name if not anonymous or intermediate type.
  839. if (!Name.empty())
  840. addString(Buffer, dwarf::DW_AT_name, Name);
  841. if (Tag == dwarf::DW_TAG_enumeration_type ||
  842. Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
  843. Tag == dwarf::DW_TAG_union_type) {
  844. // Add size if non-zero (derived types might be zero-sized.)
  845. // TODO: Do we care about size for enum forward declarations?
  846. if (Size)
  847. addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
  848. else if (!CTy->isForwardDecl())
  849. // Add zero size if it is not a forward declaration.
  850. addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
  851. // If we're a forward decl, say so.
  852. if (CTy->isForwardDecl())
  853. addFlag(Buffer, dwarf::DW_AT_declaration);
  854. // Add source line info if available.
  855. if (!CTy->isForwardDecl())
  856. addSourceLine(Buffer, CTy);
  857. // No harm in adding the runtime language to the declaration.
  858. unsigned RLang = CTy->getRuntimeLang();
  859. if (RLang)
  860. addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
  861. RLang);
  862. // Add align info if available.
  863. if (uint32_t AlignInBytes = CTy->getAlignInBytes())
  864. addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
  865. AlignInBytes);
  866. }
  867. }
  868. void DwarfUnit::constructTemplateTypeParameterDIE(
  869. DIE &Buffer, const DITemplateTypeParameter *TP) {
  870. DIE &ParamDIE =
  871. createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
  872. // Add the type if it exists, it could be void and therefore no type.
  873. if (TP->getType())
  874. addType(ParamDIE, TP->getType());
  875. if (!TP->getName().empty())
  876. addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
  877. }
  878. void DwarfUnit::constructTemplateValueParameterDIE(
  879. DIE &Buffer, const DITemplateValueParameter *VP) {
  880. DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
  881. // Add the type if there is one, template template and template parameter
  882. // packs will not have a type.
  883. if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
  884. addType(ParamDIE, VP->getType());
  885. if (!VP->getName().empty())
  886. addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
  887. if (Metadata *Val = VP->getValue()) {
  888. if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
  889. addConstantValue(ParamDIE, CI, VP->getType());
  890. else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
  891. // We cannot describe the location of dllimport'd entities: the
  892. // computation of their address requires loads from the IAT.
  893. if (!GV->hasDLLImportStorageClass()) {
  894. // For declaration non-type template parameters (such as global values
  895. // and functions)
  896. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  897. addOpAddress(*Loc, Asm->getSymbol(GV));
  898. // Emit DW_OP_stack_value to use the address as the immediate value of
  899. // the parameter, rather than a pointer to it.
  900. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
  901. addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
  902. }
  903. } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
  904. assert(isa<MDString>(Val));
  905. addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
  906. cast<MDString>(Val)->getString());
  907. } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
  908. addTemplateParams(ParamDIE, cast<MDTuple>(Val));
  909. }
  910. }
  911. }
  912. DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
  913. // Construct the context before querying for the existence of the DIE in case
  914. // such construction creates the DIE.
  915. DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
  916. if (DIE *NDie = getDIE(NS))
  917. return NDie;
  918. DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
  919. StringRef Name = NS->getName();
  920. if (!Name.empty())
  921. addString(NDie, dwarf::DW_AT_name, NS->getName());
  922. else
  923. Name = "(anonymous namespace)";
  924. DD->addAccelNamespace(*CUNode, Name, NDie);
  925. addGlobalName(Name, NDie, NS->getScope());
  926. if (NS->getExportSymbols())
  927. addFlag(NDie, dwarf::DW_AT_export_symbols);
  928. return &NDie;
  929. }
  930. DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
  931. // Construct the context before querying for the existence of the DIE in case
  932. // such construction creates the DIE.
  933. DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
  934. if (DIE *MDie = getDIE(M))
  935. return MDie;
  936. DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
  937. if (!M->getName().empty()) {
  938. addString(MDie, dwarf::DW_AT_name, M->getName());
  939. addGlobalName(M->getName(), MDie, M->getScope());
  940. }
  941. if (!M->getConfigurationMacros().empty())
  942. addString(MDie, dwarf::DW_AT_LLVM_config_macros,
  943. M->getConfigurationMacros());
  944. if (!M->getIncludePath().empty())
  945. addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
  946. if (!M->getISysRoot().empty())
  947. addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
  948. return &MDie;
  949. }
  950. DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
  951. // Construct the context before querying for the existence of the DIE in case
  952. // such construction creates the DIE (as is the case for member function
  953. // declarations).
  954. DIE *ContextDIE =
  955. Minimal ? &getUnitDie() : getOrCreateContextDIE(SP->getScope());
  956. if (DIE *SPDie = getDIE(SP))
  957. return SPDie;
  958. if (auto *SPDecl = SP->getDeclaration()) {
  959. if (!Minimal) {
  960. // Add subprogram definitions to the CU die directly.
  961. ContextDIE = &getUnitDie();
  962. // Build the decl now to ensure it precedes the definition.
  963. getOrCreateSubprogramDIE(SPDecl);
  964. }
  965. }
  966. // DW_TAG_inlined_subroutine may refer to this DIE.
  967. DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
  968. // Stop here and fill this in later, depending on whether or not this
  969. // subprogram turns out to have inlined instances or not.
  970. if (SP->isDefinition())
  971. return &SPDie;
  972. static_cast<DwarfUnit *>(SPDie.getUnit())
  973. ->applySubprogramAttributes(SP, SPDie);
  974. return &SPDie;
  975. }
  976. bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
  977. DIE &SPDie) {
  978. DIE *DeclDie = nullptr;
  979. StringRef DeclLinkageName;
  980. if (auto *SPDecl = SP->getDeclaration()) {
  981. DeclDie = getDIE(SPDecl);
  982. assert(DeclDie && "This DIE should've already been constructed when the "
  983. "definition DIE was created in "
  984. "getOrCreateSubprogramDIE");
  985. // Look at the Decl's linkage name only if we emitted it.
  986. if (DD->useAllLinkageNames())
  987. DeclLinkageName = SPDecl->getLinkageName();
  988. unsigned DeclID = getOrCreateSourceID(SPDecl->getFile());
  989. unsigned DefID = getOrCreateSourceID(SP->getFile());
  990. if (DeclID != DefID)
  991. addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
  992. if (SP->getLine() != SPDecl->getLine())
  993. addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
  994. }
  995. // Add function template parameters.
  996. addTemplateParams(SPDie, SP->getTemplateParams());
  997. // Add the linkage name if we have one and it isn't in the Decl.
  998. StringRef LinkageName = SP->getLinkageName();
  999. assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
  1000. LinkageName == DeclLinkageName) &&
  1001. "decl has a linkage name and it is different");
  1002. if (DeclLinkageName.empty() &&
  1003. // Always emit it for abstract subprograms.
  1004. (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
  1005. addLinkageName(SPDie, LinkageName);
  1006. if (!DeclDie)
  1007. return false;
  1008. // Refer to the function declaration where all the other attributes will be
  1009. // found.
  1010. addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
  1011. return true;
  1012. }
  1013. void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
  1014. bool SkipSPAttributes) {
  1015. // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
  1016. // and its source location.
  1017. bool SkipSPSourceLocation = SkipSPAttributes &&
  1018. !CUNode->getDebugInfoForProfiling();
  1019. if (!SkipSPSourceLocation)
  1020. if (applySubprogramDefinitionAttributes(SP, SPDie))
  1021. return;
  1022. // Constructors and operators for anonymous aggregates do not have names.
  1023. if (!SP->getName().empty())
  1024. addString(SPDie, dwarf::DW_AT_name, SP->getName());
  1025. if (!SkipSPSourceLocation)
  1026. addSourceLine(SPDie, SP);
  1027. // Skip the rest of the attributes under -gmlt to save space.
  1028. if (SkipSPAttributes)
  1029. return;
  1030. // Add the prototype if we have a prototype and we have a C like
  1031. // language.
  1032. uint16_t Language = getLanguage();
  1033. if (SP->isPrototyped() &&
  1034. (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
  1035. Language == dwarf::DW_LANG_ObjC))
  1036. addFlag(SPDie, dwarf::DW_AT_prototyped);
  1037. unsigned CC = 0;
  1038. DITypeRefArray Args;
  1039. if (const DISubroutineType *SPTy = SP->getType()) {
  1040. Args = SPTy->getTypeArray();
  1041. CC = SPTy->getCC();
  1042. }
  1043. // Add a DW_AT_calling_convention if this has an explicit convention.
  1044. if (CC && CC != dwarf::DW_CC_normal)
  1045. addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
  1046. // Add a return type. If this is a type like a C/C++ void type we don't add a
  1047. // return type.
  1048. if (Args.size())
  1049. if (auto Ty = Args[0])
  1050. addType(SPDie, Ty);
  1051. unsigned VK = SP->getVirtuality();
  1052. if (VK) {
  1053. addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
  1054. if (SP->getVirtualIndex() != -1u) {
  1055. DIELoc *Block = getDIELoc();
  1056. addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
  1057. addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
  1058. addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
  1059. }
  1060. ContainingTypeMap.insert(std::make_pair(&SPDie, SP->getContainingType()));
  1061. }
  1062. if (!SP->isDefinition()) {
  1063. addFlag(SPDie, dwarf::DW_AT_declaration);
  1064. // Add arguments. Do not add arguments for subprogram definition. They will
  1065. // be handled while processing variables.
  1066. constructSubprogramArguments(SPDie, Args);
  1067. }
  1068. addThrownTypes(SPDie, SP->getThrownTypes());
  1069. if (SP->isArtificial())
  1070. addFlag(SPDie, dwarf::DW_AT_artificial);
  1071. if (!SP->isLocalToUnit())
  1072. addFlag(SPDie, dwarf::DW_AT_external);
  1073. if (DD->useAppleExtensionAttributes()) {
  1074. if (SP->isOptimized())
  1075. addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
  1076. if (unsigned isa = Asm->getISAEncoding())
  1077. addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
  1078. }
  1079. if (SP->isLValueReference())
  1080. addFlag(SPDie, dwarf::DW_AT_reference);
  1081. if (SP->isRValueReference())
  1082. addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
  1083. if (SP->isNoReturn())
  1084. addFlag(SPDie, dwarf::DW_AT_noreturn);
  1085. if (SP->isProtected())
  1086. addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
  1087. dwarf::DW_ACCESS_protected);
  1088. else if (SP->isPrivate())
  1089. addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
  1090. dwarf::DW_ACCESS_private);
  1091. else if (SP->isPublic())
  1092. addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
  1093. dwarf::DW_ACCESS_public);
  1094. if (SP->isExplicit())
  1095. addFlag(SPDie, dwarf::DW_AT_explicit);
  1096. if (SP->isMainSubprogram())
  1097. addFlag(SPDie, dwarf::DW_AT_main_subprogram);
  1098. if (SP->isPure())
  1099. addFlag(SPDie, dwarf::DW_AT_pure);
  1100. if (SP->isElemental())
  1101. addFlag(SPDie, dwarf::DW_AT_elemental);
  1102. if (SP->isRecursive())
  1103. addFlag(SPDie, dwarf::DW_AT_recursive);
  1104. }
  1105. void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
  1106. DIE *IndexTy) {
  1107. DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
  1108. addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
  1109. // The LowerBound value defines the lower bounds which is typically zero for
  1110. // C/C++. The Count value is the number of elements. Values are 64 bit. If
  1111. // Count == -1 then the array is unbounded and we do not emit
  1112. // DW_AT_lower_bound and DW_AT_count attributes.
  1113. int64_t LowerBound = SR->getLowerBound();
  1114. int64_t DefaultLowerBound = getDefaultLowerBound();
  1115. int64_t Count = -1;
  1116. if (auto *CI = SR->getCount().dyn_cast<ConstantInt*>())
  1117. Count = CI->getSExtValue();
  1118. if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
  1119. addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
  1120. if (auto *CV = SR->getCount().dyn_cast<DIVariable*>()) {
  1121. if (auto *CountVarDIE = getDIE(CV))
  1122. addDIEEntry(DW_Subrange, dwarf::DW_AT_count, *CountVarDIE);
  1123. } else if (Count != -1)
  1124. addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
  1125. }
  1126. DIE *DwarfUnit::getIndexTyDie() {
  1127. if (IndexTyDie)
  1128. return IndexTyDie;
  1129. // Construct an integer type to use for indexes.
  1130. IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
  1131. StringRef Name = "__ARRAY_SIZE_TYPE__";
  1132. addString(*IndexTyDie, dwarf::DW_AT_name, Name);
  1133. addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
  1134. addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
  1135. dwarf::DW_ATE_unsigned);
  1136. DD->addAccelType(*CUNode, Name, *IndexTyDie, /*Flags*/ 0);
  1137. return IndexTyDie;
  1138. }
  1139. /// Returns true if the vector's size differs from the sum of sizes of elements
  1140. /// the user specified. This can occur if the vector has been rounded up to
  1141. /// fit memory alignment constraints.
  1142. static bool hasVectorBeenPadded(const DICompositeType *CTy) {
  1143. assert(CTy && CTy->isVector() && "Composite type is not a vector");
  1144. const uint64_t ActualSize = CTy->getSizeInBits();
  1145. // Obtain the size of each element in the vector.
  1146. DIType *BaseTy = CTy->getBaseType();
  1147. assert(BaseTy && "Unknown vector element type.");
  1148. const uint64_t ElementSize = BaseTy->getSizeInBits();
  1149. // Locate the number of elements in the vector.
  1150. const DINodeArray Elements = CTy->getElements();
  1151. assert(Elements.size() == 1 &&
  1152. Elements[0]->getTag() == dwarf::DW_TAG_subrange_type &&
  1153. "Invalid vector element array, expected one element of type subrange");
  1154. const auto Subrange = cast<DISubrange>(Elements[0]);
  1155. const auto CI = Subrange->getCount().get<ConstantInt *>();
  1156. const int32_t NumVecElements = CI->getSExtValue();
  1157. // Ensure we found the element count and that the actual size is wide
  1158. // enough to contain the requested size.
  1159. assert(ActualSize >= (NumVecElements * ElementSize) && "Invalid vector size");
  1160. return ActualSize != (NumVecElements * ElementSize);
  1161. }
  1162. void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
  1163. if (CTy->isVector()) {
  1164. addFlag(Buffer, dwarf::DW_AT_GNU_vector);
  1165. if (hasVectorBeenPadded(CTy))
  1166. addUInt(Buffer, dwarf::DW_AT_byte_size, None,
  1167. CTy->getSizeInBits() / CHAR_BIT);
  1168. }
  1169. // Emit the element type.
  1170. addType(Buffer, CTy->getBaseType());
  1171. // Get an anonymous type for index type.
  1172. // FIXME: This type should be passed down from the front end
  1173. // as different languages may have different sizes for indexes.
  1174. DIE *IdxTy = getIndexTyDie();
  1175. // Add subranges to array type.
  1176. DINodeArray Elements = CTy->getElements();
  1177. for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
  1178. // FIXME: Should this really be such a loose cast?
  1179. if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
  1180. if (Element->getTag() == dwarf::DW_TAG_subrange_type)
  1181. constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
  1182. }
  1183. }
  1184. void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
  1185. const DIType *DTy = CTy->getBaseType();
  1186. bool IsUnsigned = DTy && isUnsignedDIType(DD, DTy);
  1187. if (DTy) {
  1188. if (DD->getDwarfVersion() >= 3)
  1189. addType(Buffer, DTy);
  1190. if (DD->getDwarfVersion() >= 4 && (CTy->getFlags() & DINode::FlagEnumClass))
  1191. addFlag(Buffer, dwarf::DW_AT_enum_class);
  1192. }
  1193. auto *Context = CTy->getScope();
  1194. bool IndexEnumerators = !Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
  1195. isa<DINamespace>(Context) || isa<DICommonBlock>(Context);
  1196. DINodeArray Elements = CTy->getElements();
  1197. // Add enumerators to enumeration type.
  1198. for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
  1199. auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
  1200. if (Enum) {
  1201. DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
  1202. StringRef Name = Enum->getName();
  1203. addString(Enumerator, dwarf::DW_AT_name, Name);
  1204. auto Value = static_cast<uint64_t>(Enum->getValue());
  1205. addConstantValue(Enumerator, IsUnsigned, Value);
  1206. if (IndexEnumerators)
  1207. addGlobalName(Name, Enumerator, Context);
  1208. }
  1209. }
  1210. }
  1211. void DwarfUnit::constructContainingTypeDIEs() {
  1212. for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
  1213. CI != CE; ++CI) {
  1214. DIE &SPDie = *CI->first;
  1215. const DINode *D = CI->second;
  1216. if (!D)
  1217. continue;
  1218. DIE *NDie = getDIE(D);
  1219. if (!NDie)
  1220. continue;
  1221. addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
  1222. }
  1223. }
  1224. DIE &DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
  1225. DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
  1226. StringRef Name = DT->getName();
  1227. if (!Name.empty())
  1228. addString(MemberDie, dwarf::DW_AT_name, Name);
  1229. if (DIType *Resolved = DT->getBaseType())
  1230. addType(MemberDie, Resolved);
  1231. addSourceLine(MemberDie, DT);
  1232. if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
  1233. // For C++, virtual base classes are not at fixed offset. Use following
  1234. // expression to extract appropriate offset from vtable.
  1235. // BaseAddr = ObAddr + *((*ObAddr) - Offset)
  1236. DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
  1237. addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
  1238. addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
  1239. addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
  1240. addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
  1241. addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
  1242. addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
  1243. addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
  1244. addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
  1245. } else {
  1246. uint64_t Size = DT->getSizeInBits();
  1247. uint64_t FieldSize = DD->getBaseTypeSize(DT);
  1248. uint32_t AlignInBytes = DT->getAlignInBytes();
  1249. uint64_t OffsetInBytes;
  1250. bool IsBitfield = FieldSize && Size != FieldSize;
  1251. if (IsBitfield) {
  1252. // Handle bitfield, assume bytes are 8 bits.
  1253. if (DD->useDWARF2Bitfields())
  1254. addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
  1255. addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
  1256. uint64_t Offset = DT->getOffsetInBits();
  1257. // We can't use DT->getAlignInBits() here: AlignInBits for member type
  1258. // is non-zero if and only if alignment was forced (e.g. _Alignas()),
  1259. // which can't be done with bitfields. Thus we use FieldSize here.
  1260. uint32_t AlignInBits = FieldSize;
  1261. uint32_t AlignMask = ~(AlignInBits - 1);
  1262. // The bits from the start of the storage unit to the start of the field.
  1263. uint64_t StartBitOffset = Offset - (Offset & AlignMask);
  1264. // The byte offset of the field's aligned storage unit inside the struct.
  1265. OffsetInBytes = (Offset - StartBitOffset) / 8;
  1266. if (DD->useDWARF2Bitfields()) {
  1267. uint64_t HiMark = (Offset + FieldSize) & AlignMask;
  1268. uint64_t FieldOffset = (HiMark - FieldSize);
  1269. Offset -= FieldOffset;
  1270. // Maybe we need to work from the other end.
  1271. if (Asm->getDataLayout().isLittleEndian())
  1272. Offset = FieldSize - (Offset + Size);
  1273. addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
  1274. OffsetInBytes = FieldOffset >> 3;
  1275. } else {
  1276. addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
  1277. }
  1278. } else {
  1279. // This is not a bitfield.
  1280. OffsetInBytes = DT->getOffsetInBits() / 8;
  1281. if (AlignInBytes)
  1282. addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
  1283. AlignInBytes);
  1284. }
  1285. if (DD->getDwarfVersion() <= 2) {
  1286. DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
  1287. addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
  1288. addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
  1289. addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
  1290. } else if (!IsBitfield || DD->useDWARF2Bitfields())
  1291. addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
  1292. OffsetInBytes);
  1293. }
  1294. if (DT->isProtected())
  1295. addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
  1296. dwarf::DW_ACCESS_protected);
  1297. else if (DT->isPrivate())
  1298. addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
  1299. dwarf::DW_ACCESS_private);
  1300. // Otherwise C++ member and base classes are considered public.
  1301. else if (DT->isPublic())
  1302. addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
  1303. dwarf::DW_ACCESS_public);
  1304. if (DT->isVirtual())
  1305. addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
  1306. dwarf::DW_VIRTUALITY_virtual);
  1307. // Objective-C properties.
  1308. if (DINode *PNode = DT->getObjCProperty())
  1309. if (DIE *PDie = getDIE(PNode))
  1310. MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
  1311. dwarf::DW_FORM_ref4, DIEEntry(*PDie));
  1312. if (DT->isArtificial())
  1313. addFlag(MemberDie, dwarf::DW_AT_artificial);
  1314. return MemberDie;
  1315. }
  1316. DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
  1317. if (!DT)
  1318. return nullptr;
  1319. // Construct the context before querying for the existence of the DIE in case
  1320. // such construction creates the DIE.
  1321. DIE *ContextDIE = getOrCreateContextDIE(DT->getScope());
  1322. assert(dwarf::isType(ContextDIE->getTag()) &&
  1323. "Static member should belong to a type.");
  1324. if (DIE *StaticMemberDIE = getDIE(DT))
  1325. return StaticMemberDIE;
  1326. DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
  1327. const DIType *Ty = DT->getBaseType();
  1328. addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
  1329. addType(StaticMemberDIE, Ty);
  1330. addSourceLine(StaticMemberDIE, DT);
  1331. addFlag(StaticMemberDIE, dwarf::DW_AT_external);
  1332. addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
  1333. // FIXME: We could omit private if the parent is a class_type, and
  1334. // public if the parent is something else.
  1335. if (DT->isProtected())
  1336. addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
  1337. dwarf::DW_ACCESS_protected);
  1338. else if (DT->isPrivate())
  1339. addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
  1340. dwarf::DW_ACCESS_private);
  1341. else if (DT->isPublic())
  1342. addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
  1343. dwarf::DW_ACCESS_public);
  1344. if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
  1345. addConstantValue(StaticMemberDIE, CI, Ty);
  1346. if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
  1347. addConstantFPValue(StaticMemberDIE, CFP);
  1348. if (uint32_t AlignInBytes = DT->getAlignInBytes())
  1349. addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
  1350. AlignInBytes);
  1351. return &StaticMemberDIE;
  1352. }
  1353. void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
  1354. // Emit size of content not including length itself
  1355. Asm->OutStreamer->AddComment("Length of Unit");
  1356. if (!DD->useSectionsAsReferences()) {
  1357. StringRef Prefix = isDwoUnit() ? "debug_info_dwo_" : "debug_info_";
  1358. MCSymbol *BeginLabel = Asm->createTempSymbol(Prefix + "start");
  1359. EndLabel = Asm->createTempSymbol(Prefix + "end");
  1360. Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
  1361. Asm->OutStreamer->EmitLabel(BeginLabel);
  1362. } else
  1363. Asm->emitInt32(getHeaderSize() + getUnitDie().getSize());
  1364. Asm->OutStreamer->AddComment("DWARF version number");
  1365. unsigned Version = DD->getDwarfVersion();
  1366. Asm->emitInt16(Version);
  1367. // DWARF v5 reorders the address size and adds a unit type.
  1368. if (Version >= 5) {
  1369. Asm->OutStreamer->AddComment("DWARF Unit Type");
  1370. Asm->emitInt8(UT);
  1371. Asm->OutStreamer->AddComment("Address Size (in bytes)");
  1372. Asm->emitInt8(Asm->MAI->getCodePointerSize());
  1373. }
  1374. // We share one abbreviations table across all units so it's always at the
  1375. // start of the section. Use a relocatable offset where needed to ensure
  1376. // linking doesn't invalidate that offset.
  1377. Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
  1378. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  1379. if (UseOffsets)
  1380. Asm->emitInt32(0);
  1381. else
  1382. Asm->emitDwarfSymbolReference(
  1383. TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
  1384. if (Version <= 4) {
  1385. Asm->OutStreamer->AddComment("Address Size (in bytes)");
  1386. Asm->emitInt8(Asm->MAI->getCodePointerSize());
  1387. }
  1388. }
  1389. void DwarfTypeUnit::emitHeader(bool UseOffsets) {
  1390. DwarfUnit::emitCommonHeader(UseOffsets,
  1391. DD->useSplitDwarf() ? dwarf::DW_UT_split_type
  1392. : dwarf::DW_UT_type);
  1393. Asm->OutStreamer->AddComment("Type Signature");
  1394. Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
  1395. Asm->OutStreamer->AddComment("Type DIE Offset");
  1396. // In a skeleton type unit there is no type DIE so emit a zero offset.
  1397. Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
  1398. sizeof(Ty->getOffset()));
  1399. }
  1400. DIE::value_iterator
  1401. DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
  1402. const MCSymbol *Hi, const MCSymbol *Lo) {
  1403. return Die.addValue(DIEValueAllocator, Attribute,
  1404. DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
  1405. : dwarf::DW_FORM_data4,
  1406. new (DIEValueAllocator) DIEDelta(Hi, Lo));
  1407. }
  1408. DIE::value_iterator
  1409. DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
  1410. const MCSymbol *Label, const MCSymbol *Sec) {
  1411. if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
  1412. return addLabel(Die, Attribute,
  1413. DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
  1414. : dwarf::DW_FORM_data4,
  1415. Label);
  1416. return addSectionDelta(Die, Attribute, Label, Sec);
  1417. }
  1418. bool DwarfTypeUnit::isDwoUnit() const {
  1419. // Since there are no skeleton type units, all type units are dwo type units
  1420. // when split DWARF is being used.
  1421. return DD->useSplitDwarf();
  1422. }
  1423. void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
  1424. const DIScope *Context) {
  1425. getCU().addGlobalNameForTypeUnit(Name, Context);
  1426. }
  1427. void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die,
  1428. const DIScope *Context) {
  1429. getCU().addGlobalTypeUnitType(Ty, Context);
  1430. }
  1431. const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const {
  1432. if (!Asm->MAI->doesDwarfUseRelocationsAcrossSections())
  1433. return nullptr;
  1434. if (isDwoUnit())
  1435. return nullptr;
  1436. return getSection()->getBeginSymbol();
  1437. }
  1438. void DwarfUnit::addStringOffsetsStart() {
  1439. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  1440. addSectionLabel(getUnitDie(), dwarf::DW_AT_str_offsets_base,
  1441. DU->getStringOffsetsStartSym(),
  1442. TLOF.getDwarfStrOffSection()->getBeginSymbol());
  1443. }
  1444. void DwarfUnit::addRnglistsBase() {
  1445. assert(DD->getDwarfVersion() >= 5 &&
  1446. "DW_AT_rnglists_base requires DWARF version 5 or later");
  1447. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  1448. addSectionLabel(getUnitDie(), dwarf::DW_AT_rnglists_base,
  1449. DU->getRnglistsTableBaseSym(),
  1450. TLOF.getDwarfRnglistsSection()->getBeginSymbol());
  1451. }
  1452. void DwarfUnit::addLoclistsBase() {
  1453. assert(DD->getDwarfVersion() >= 5 &&
  1454. "DW_AT_loclists_base requires DWARF version 5 or later");
  1455. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  1456. addSectionLabel(getUnitDie(), dwarf::DW_AT_loclists_base,
  1457. DU->getLoclistsTableBaseSym(),
  1458. TLOF.getDwarfLoclistsSection()->getBeginSymbol());
  1459. }
  1460. void DwarfTypeUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
  1461. addFlag(D, dwarf::DW_AT_declaration);
  1462. StringRef Name = CTy->getName();
  1463. if (!Name.empty())
  1464. addString(D, dwarf::DW_AT_name, Name);
  1465. getCU().createTypeDIE(CTy);
  1466. }