DwarfUnit.cpp 62 KB

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