DwarfCompileUnit.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  1. //===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf 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 "DwarfCompileUnit.h"
  13. #include "AddressPool.h"
  14. #include "DwarfExpression.h"
  15. #include "llvm/ADT/None.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/BinaryFormat/Dwarf.h"
  19. #include "llvm/CodeGen/AsmPrinter.h"
  20. #include "llvm/CodeGen/DIE.h"
  21. #include "llvm/CodeGen/MachineFunction.h"
  22. #include "llvm/CodeGen/MachineInstr.h"
  23. #include "llvm/CodeGen/MachineOperand.h"
  24. #include "llvm/CodeGen/TargetFrameLowering.h"
  25. #include "llvm/CodeGen/TargetRegisterInfo.h"
  26. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/DebugInfo.h"
  29. #include "llvm/IR/GlobalVariable.h"
  30. #include "llvm/MC/MCSection.h"
  31. #include "llvm/MC/MCStreamer.h"
  32. #include "llvm/MC/MCSymbol.h"
  33. #include "llvm/MC/MCSymbolWasm.h"
  34. #include "llvm/MC/MachineLocation.h"
  35. #include "llvm/Target/TargetLoweringObjectFile.h"
  36. #include "llvm/Target/TargetMachine.h"
  37. #include "llvm/Target/TargetOptions.h"
  38. #include <iterator>
  39. #include <string>
  40. #include <utility>
  41. using namespace llvm;
  42. static dwarf::Tag GetCompileUnitType(UnitKind Kind, DwarfDebug *DW) {
  43. // According to DWARF Debugging Information Format Version 5,
  44. // 3.1.2 Skeleton Compilation Unit Entries:
  45. // "When generating a split DWARF object file (see Section 7.3.2
  46. // on page 187), the compilation unit in the .debug_info section
  47. // is a "skeleton" compilation unit with the tag DW_TAG_skeleton_unit"
  48. if (DW->getDwarfVersion() >= 5 && Kind == UnitKind::Skeleton)
  49. return dwarf::DW_TAG_skeleton_unit;
  50. return dwarf::DW_TAG_compile_unit;
  51. }
  52. DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
  53. AsmPrinter *A, DwarfDebug *DW,
  54. DwarfFile *DWU, UnitKind Kind)
  55. : DwarfUnit(GetCompileUnitType(Kind, DW), Node, A, DW, DWU), UniqueID(UID) {
  56. insertDIE(Node, &getUnitDie());
  57. MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
  58. }
  59. /// addLabelAddress - Add a dwarf label attribute data and value using
  60. /// DW_FORM_addr or DW_FORM_GNU_addr_index.
  61. void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
  62. const MCSymbol *Label) {
  63. // Don't use the address pool in non-fission or in the skeleton unit itself.
  64. if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
  65. return addLocalLabelAddress(Die, Attribute, Label);
  66. if (Label)
  67. DD->addArangeLabel(SymbolCU(this, Label));
  68. bool UseAddrOffsetFormOrExpressions =
  69. DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
  70. const MCSymbol *Base = nullptr;
  71. if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
  72. Base = DD->getSectionLabel(&Label->getSection());
  73. if (!Base || Base == Label) {
  74. unsigned idx = DD->getAddressPool().getIndex(Label);
  75. addAttribute(Die, Attribute,
  76. DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
  77. : dwarf::DW_FORM_GNU_addr_index,
  78. DIEInteger(idx));
  79. return;
  80. }
  81. // Could be extended to work with DWARFv4 Split DWARF if that's important for
  82. // someone. In that case DW_FORM_data would be used.
  83. assert(DD->getDwarfVersion() >= 5 &&
  84. "Addr+offset expressions are only valuable when using debug_addr (to "
  85. "reduce relocations) available in DWARFv5 or higher");
  86. if (DD->useAddrOffsetExpressions()) {
  87. auto *Loc = new (DIEValueAllocator) DIEBlock();
  88. addPoolOpAddress(*Loc, Label);
  89. addBlock(Die, Attribute, dwarf::DW_FORM_exprloc, Loc);
  90. } else
  91. addAttribute(Die, Attribute, dwarf::DW_FORM_LLVM_addrx_offset,
  92. new (DIEValueAllocator) DIEAddrOffset(
  93. DD->getAddressPool().getIndex(Base), Label, Base));
  94. }
  95. void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
  96. dwarf::Attribute Attribute,
  97. const MCSymbol *Label) {
  98. if (Label)
  99. DD->addArangeLabel(SymbolCU(this, Label));
  100. if (Label)
  101. addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIELabel(Label));
  102. else
  103. addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIEInteger(0));
  104. }
  105. unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
  106. // If we print assembly, we can't separate .file entries according to
  107. // compile units. Thus all files will belong to the default compile unit.
  108. // FIXME: add a better feature test than hasRawTextSupport. Even better,
  109. // extend .file to support this.
  110. unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
  111. if (!File)
  112. return Asm->OutStreamer->emitDwarfFileDirective(0, "", "", None, None,
  113. CUID);
  114. if (LastFile != File) {
  115. LastFile = File;
  116. LastFileID = Asm->OutStreamer->emitDwarfFileDirective(
  117. 0, File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File),
  118. File->getSource(), CUID);
  119. }
  120. return LastFileID;
  121. }
  122. DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
  123. const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
  124. // Check for pre-existence.
  125. if (DIE *Die = getDIE(GV))
  126. return Die;
  127. assert(GV);
  128. auto *GVContext = GV->getScope();
  129. const DIType *GTy = GV->getType();
  130. auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
  131. DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
  132. : getOrCreateContextDIE(GVContext);
  133. // Add to map.
  134. DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
  135. DIScope *DeclContext;
  136. if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
  137. DeclContext = SDMDecl->getScope();
  138. assert(SDMDecl->isStaticMember() && "Expected static member decl");
  139. assert(GV->isDefinition());
  140. // We need the declaration DIE that is in the static member's class.
  141. DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
  142. addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
  143. // If the global variable's type is different from the one in the class
  144. // member type, assume that it's more specific and also emit it.
  145. if (GTy != SDMDecl->getBaseType())
  146. addType(*VariableDIE, GTy);
  147. } else {
  148. DeclContext = GV->getScope();
  149. // Add name and type.
  150. addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
  151. if (GTy)
  152. addType(*VariableDIE, GTy);
  153. // Add scoping info.
  154. if (!GV->isLocalToUnit())
  155. addFlag(*VariableDIE, dwarf::DW_AT_external);
  156. // Add line number info.
  157. addSourceLine(*VariableDIE, GV);
  158. }
  159. if (!GV->isDefinition())
  160. addFlag(*VariableDIE, dwarf::DW_AT_declaration);
  161. else
  162. addGlobalName(GV->getName(), *VariableDIE, DeclContext);
  163. addAnnotation(*VariableDIE, GV->getAnnotations());
  164. if (uint32_t AlignInBytes = GV->getAlignInBytes())
  165. addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
  166. AlignInBytes);
  167. if (MDTuple *TP = GV->getTemplateParams())
  168. addTemplateParams(*VariableDIE, DINodeArray(TP));
  169. // Add location.
  170. addLocationAttribute(VariableDIE, GV, GlobalExprs);
  171. return VariableDIE;
  172. }
  173. void DwarfCompileUnit::addLocationAttribute(
  174. DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
  175. bool addToAccelTable = false;
  176. DIELoc *Loc = nullptr;
  177. Optional<unsigned> NVPTXAddressSpace;
  178. std::unique_ptr<DIEDwarfExpression> DwarfExpr;
  179. for (const auto &GE : GlobalExprs) {
  180. const GlobalVariable *Global = GE.Var;
  181. const DIExpression *Expr = GE.Expr;
  182. // For compatibility with DWARF 3 and earlier,
  183. // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) or
  184. // DW_AT_location(DW_OP_consts, X, DW_OP_stack_value) becomes
  185. // DW_AT_const_value(X).
  186. if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
  187. addToAccelTable = true;
  188. addConstantValue(
  189. *VariableDIE,
  190. DIExpression::SignedOrUnsignedConstant::UnsignedConstant ==
  191. *Expr->isConstant(),
  192. Expr->getElement(1));
  193. break;
  194. }
  195. // We cannot describe the location of dllimport'd variables: the
  196. // computation of their address requires loads from the IAT.
  197. if (Global && Global->hasDLLImportStorageClass())
  198. continue;
  199. // Nothing to describe without address or constant.
  200. if (!Global && (!Expr || !Expr->isConstant()))
  201. continue;
  202. if (Global && Global->isThreadLocal() &&
  203. !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
  204. continue;
  205. if (!Loc) {
  206. addToAccelTable = true;
  207. Loc = new (DIEValueAllocator) DIELoc;
  208. DwarfExpr = std::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
  209. }
  210. if (Expr) {
  211. // According to
  212. // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
  213. // cuda-gdb requires DW_AT_address_class for all variables to be able to
  214. // correctly interpret address space of the variable address.
  215. // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
  216. // sequence for the NVPTX + gdb target.
  217. unsigned LocalNVPTXAddressSpace;
  218. if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
  219. const DIExpression *NewExpr =
  220. DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
  221. if (NewExpr != Expr) {
  222. Expr = NewExpr;
  223. NVPTXAddressSpace = LocalNVPTXAddressSpace;
  224. }
  225. }
  226. DwarfExpr->addFragmentOffset(Expr);
  227. }
  228. if (Global) {
  229. const MCSymbol *Sym = Asm->getSymbol(Global);
  230. // 16-bit platforms like MSP430 and AVR take this path, so sink this
  231. // assert to platforms that use it.
  232. auto GetPointerSizedFormAndOp = [this]() {
  233. unsigned PointerSize = Asm->getDataLayout().getPointerSize();
  234. assert((PointerSize == 4 || PointerSize == 8) &&
  235. "Add support for other sizes if necessary");
  236. struct FormAndOp {
  237. dwarf::Form Form;
  238. dwarf::LocationAtom Op;
  239. };
  240. return PointerSize == 4
  241. ? FormAndOp{dwarf::DW_FORM_data4, dwarf::DW_OP_const4u}
  242. : FormAndOp{dwarf::DW_FORM_data8, dwarf::DW_OP_const8u};
  243. };
  244. if (Global->isThreadLocal()) {
  245. if (Asm->TM.useEmulatedTLS()) {
  246. // TODO: add debug info for emulated thread local mode.
  247. } else {
  248. // FIXME: Make this work with -gsplit-dwarf.
  249. // Based on GCC's support for TLS:
  250. if (!DD->useSplitDwarf()) {
  251. auto FormAndOp = GetPointerSizedFormAndOp();
  252. // 1) Start with a constNu of the appropriate pointer size
  253. addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
  254. // 2) containing the (relocated) offset of the TLS variable
  255. // within the module's TLS block.
  256. addExpr(*Loc, FormAndOp.Form,
  257. Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
  258. } else {
  259. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
  260. addUInt(*Loc, dwarf::DW_FORM_udata,
  261. DD->getAddressPool().getIndex(Sym, /* TLS */ true));
  262. }
  263. // 3) followed by an OP to make the debugger do a TLS lookup.
  264. addUInt(*Loc, dwarf::DW_FORM_data1,
  265. DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
  266. : dwarf::DW_OP_form_tls_address);
  267. }
  268. } else if (Asm->TM.getRelocationModel() == Reloc::RWPI ||
  269. Asm->TM.getRelocationModel() == Reloc::ROPI_RWPI) {
  270. auto FormAndOp = GetPointerSizedFormAndOp();
  271. // Constant
  272. addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
  273. // Relocation offset
  274. addExpr(*Loc, FormAndOp.Form,
  275. Asm->getObjFileLowering().getIndirectSymViaRWPI(Sym));
  276. // Base register
  277. Register BaseReg = Asm->getObjFileLowering().getStaticBase();
  278. BaseReg = Asm->TM.getMCRegisterInfo()->getDwarfRegNum(BaseReg, false);
  279. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + BaseReg);
  280. // Offset from base register
  281. addSInt(*Loc, dwarf::DW_FORM_sdata, 0);
  282. // Operation
  283. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
  284. } else {
  285. DD->addArangeLabel(SymbolCU(this, Sym));
  286. addOpAddress(*Loc, Sym);
  287. }
  288. }
  289. // Global variables attached to symbols are memory locations.
  290. // It would be better if this were unconditional, but malformed input that
  291. // mixes non-fragments and fragments for the same variable is too expensive
  292. // to detect in the verifier.
  293. if (DwarfExpr->isUnknownLocation())
  294. DwarfExpr->setMemoryLocationKind();
  295. DwarfExpr->addExpression(Expr);
  296. }
  297. if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
  298. // According to
  299. // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
  300. // cuda-gdb requires DW_AT_address_class for all variables to be able to
  301. // correctly interpret address space of the variable address.
  302. const unsigned NVPTX_ADDR_global_space = 5;
  303. addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
  304. NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space);
  305. }
  306. if (Loc)
  307. addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
  308. if (DD->useAllLinkageNames())
  309. addLinkageName(*VariableDIE, GV->getLinkageName());
  310. if (addToAccelTable) {
  311. DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
  312. // If the linkage name is different than the name, go ahead and output
  313. // that as well into the name table.
  314. if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
  315. DD->useAllLinkageNames())
  316. DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
  317. }
  318. }
  319. DIE *DwarfCompileUnit::getOrCreateCommonBlock(
  320. const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
  321. // Check for pre-existence.
  322. if (DIE *NDie = getDIE(CB))
  323. return NDie;
  324. DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
  325. DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
  326. StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
  327. addString(NDie, dwarf::DW_AT_name, Name);
  328. addGlobalName(Name, NDie, CB->getScope());
  329. if (CB->getFile())
  330. addSourceLine(NDie, CB->getLineNo(), CB->getFile());
  331. if (DIGlobalVariable *V = CB->getDecl())
  332. getCU().addLocationAttribute(&NDie, V, GlobalExprs);
  333. return &NDie;
  334. }
  335. void DwarfCompileUnit::addRange(RangeSpan Range) {
  336. DD->insertSectionLabel(Range.Begin);
  337. auto *PrevCU = DD->getPrevCU();
  338. bool SameAsPrevCU = this == PrevCU;
  339. DD->setPrevCU(this);
  340. // If we have no current ranges just add the range and return, otherwise,
  341. // check the current section and CU against the previous section and CU we
  342. // emitted into and the subprogram was contained within. If these are the
  343. // same then extend our current range, otherwise add this as a new range.
  344. if (CURanges.empty() || !SameAsPrevCU ||
  345. (&CURanges.back().End->getSection() !=
  346. &Range.End->getSection())) {
  347. // Before a new range is added, always terminate the prior line table.
  348. if (PrevCU)
  349. DD->terminateLineTable(PrevCU);
  350. CURanges.push_back(Range);
  351. return;
  352. }
  353. CURanges.back().End = Range.End;
  354. }
  355. void DwarfCompileUnit::initStmtList() {
  356. if (CUNode->isDebugDirectivesOnly())
  357. return;
  358. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  359. if (DD->useSectionsAsReferences()) {
  360. LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
  361. } else {
  362. LineTableStartSym =
  363. Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
  364. }
  365. // DW_AT_stmt_list is a offset of line number information for this
  366. // compile unit in debug_line section. For split dwarf this is
  367. // left in the skeleton CU and so not included.
  368. // The line table entries are not always emitted in assembly, so it
  369. // is not okay to use line_table_start here.
  370. addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
  371. TLOF.getDwarfLineSection()->getBeginSymbol());
  372. }
  373. void DwarfCompileUnit::applyStmtList(DIE &D) {
  374. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  375. addSectionLabel(D, dwarf::DW_AT_stmt_list, LineTableStartSym,
  376. TLOF.getDwarfLineSection()->getBeginSymbol());
  377. }
  378. void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
  379. const MCSymbol *End) {
  380. assert(Begin && "Begin label should not be null!");
  381. assert(End && "End label should not be null!");
  382. assert(Begin->isDefined() && "Invalid starting label");
  383. assert(End->isDefined() && "Invalid end label");
  384. addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
  385. if (DD->getDwarfVersion() < 4)
  386. addLabelAddress(D, dwarf::DW_AT_high_pc, End);
  387. else
  388. addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
  389. }
  390. // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
  391. // and DW_AT_high_pc attributes. If there are global variables in this
  392. // scope then create and insert DIEs for these variables.
  393. DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
  394. DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
  395. SmallVector<RangeSpan, 2> BB_List;
  396. // If basic block sections are on, ranges for each basic block section has
  397. // to be emitted separately.
  398. for (const auto &R : Asm->MBBSectionRanges)
  399. BB_List.push_back({R.second.BeginLabel, R.second.EndLabel});
  400. attachRangesOrLowHighPC(*SPDie, BB_List);
  401. if (DD->useAppleExtensionAttributes() &&
  402. !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
  403. *DD->getCurrentFunction()))
  404. addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
  405. // Only include DW_AT_frame_base in full debug info
  406. if (!includeMinimalInlineScopes()) {
  407. const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
  408. TargetFrameLowering::DwarfFrameBase FrameBase =
  409. TFI->getDwarfFrameBase(*Asm->MF);
  410. switch (FrameBase.Kind) {
  411. case TargetFrameLowering::DwarfFrameBase::Register: {
  412. if (Register::isPhysicalRegister(FrameBase.Location.Reg)) {
  413. MachineLocation Location(FrameBase.Location.Reg);
  414. addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
  415. }
  416. break;
  417. }
  418. case TargetFrameLowering::DwarfFrameBase::CFA: {
  419. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  420. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
  421. addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
  422. break;
  423. }
  424. case TargetFrameLowering::DwarfFrameBase::WasmFrameBase: {
  425. // FIXME: duplicated from Target/WebAssembly/WebAssembly.h
  426. // don't want to depend on target specific headers in this code?
  427. const unsigned TI_GLOBAL_RELOC = 3;
  428. if (FrameBase.Location.WasmLoc.Kind == TI_GLOBAL_RELOC) {
  429. // These need to be relocatable.
  430. assert(FrameBase.Location.WasmLoc.Index == 0); // Only SP so far.
  431. auto SPSym = cast<MCSymbolWasm>(
  432. Asm->GetExternalSymbolSymbol("__stack_pointer"));
  433. // FIXME: this repeats what WebAssemblyMCInstLower::
  434. // GetExternalSymbolSymbol does, since if there's no code that
  435. // refers to this symbol, we have to set it here.
  436. SPSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
  437. SPSym->setGlobalType(wasm::WasmGlobalType{
  438. uint8_t(Asm->getSubtargetInfo().getTargetTriple().getArch() ==
  439. Triple::wasm64
  440. ? wasm::WASM_TYPE_I64
  441. : wasm::WASM_TYPE_I32),
  442. true});
  443. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  444. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_WASM_location);
  445. addSInt(*Loc, dwarf::DW_FORM_sdata, TI_GLOBAL_RELOC);
  446. if (!isDwoUnit()) {
  447. addLabel(*Loc, dwarf::DW_FORM_data4, SPSym);
  448. } else {
  449. // FIXME: when writing dwo, we need to avoid relocations. Probably
  450. // the "right" solution is to treat globals the way func and data
  451. // symbols are (with entries in .debug_addr).
  452. // For now, since we only ever use index 0, this should work as-is.
  453. addUInt(*Loc, dwarf::DW_FORM_data4, FrameBase.Location.WasmLoc.Index);
  454. }
  455. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
  456. addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
  457. } else {
  458. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  459. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  460. DIExpressionCursor Cursor({});
  461. DwarfExpr.addWasmLocation(FrameBase.Location.WasmLoc.Kind,
  462. FrameBase.Location.WasmLoc.Index);
  463. DwarfExpr.addExpression(std::move(Cursor));
  464. addBlock(*SPDie, dwarf::DW_AT_frame_base, DwarfExpr.finalize());
  465. }
  466. break;
  467. }
  468. }
  469. }
  470. // Add name to the name table, we do this here because we're guaranteed
  471. // to have concrete versions of our DW_TAG_subprogram nodes.
  472. DD->addSubprogramNames(*CUNode, SP, *SPDie);
  473. return *SPDie;
  474. }
  475. // Construct a DIE for this scope.
  476. void DwarfCompileUnit::constructScopeDIE(LexicalScope *Scope,
  477. DIE &ParentScopeDIE) {
  478. if (!Scope || !Scope->getScopeNode())
  479. return;
  480. auto *DS = Scope->getScopeNode();
  481. assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
  482. "Only handle inlined subprograms here, use "
  483. "constructSubprogramScopeDIE for non-inlined "
  484. "subprograms");
  485. // Emit inlined subprograms.
  486. if (Scope->getParent() && isa<DISubprogram>(DS)) {
  487. DIE *ScopeDIE = constructInlinedScopeDIE(Scope);
  488. if (!ScopeDIE)
  489. return;
  490. ParentScopeDIE.addChild(ScopeDIE);
  491. createAndAddScopeChildren(Scope, *ScopeDIE);
  492. return;
  493. }
  494. // Early exit when we know the scope DIE is going to be null.
  495. if (DD->isLexicalScopeDIENull(Scope))
  496. return;
  497. // Emit lexical blocks.
  498. DIE *ScopeDIE = constructLexicalScopeDIE(Scope);
  499. assert(ScopeDIE && "Scope DIE should not be null.");
  500. ParentScopeDIE.addChild(ScopeDIE);
  501. createAndAddScopeChildren(Scope, *ScopeDIE);
  502. }
  503. void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
  504. SmallVector<RangeSpan, 2> Range) {
  505. HasRangeLists = true;
  506. // Add the range list to the set of ranges to be emitted.
  507. auto IndexAndList =
  508. (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
  509. ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
  510. uint32_t Index = IndexAndList.first;
  511. auto &List = *IndexAndList.second;
  512. // Under fission, ranges are specified by constant offsets relative to the
  513. // CU's DW_AT_GNU_ranges_base.
  514. // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
  515. // fission until we support the forms using the .debug_addr section
  516. // (DW_RLE_startx_endx etc.).
  517. if (DD->getDwarfVersion() >= 5)
  518. addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
  519. else {
  520. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  521. const MCSymbol *RangeSectionSym =
  522. TLOF.getDwarfRangesSection()->getBeginSymbol();
  523. if (isDwoUnit())
  524. addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
  525. RangeSectionSym);
  526. else
  527. addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
  528. RangeSectionSym);
  529. }
  530. }
  531. void DwarfCompileUnit::attachRangesOrLowHighPC(
  532. DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
  533. assert(!Ranges.empty());
  534. if (!DD->useRangesSection() ||
  535. (Ranges.size() == 1 &&
  536. (!DD->alwaysUseRanges() ||
  537. DD->getSectionLabel(&Ranges.front().Begin->getSection()) ==
  538. Ranges.front().Begin))) {
  539. const RangeSpan &Front = Ranges.front();
  540. const RangeSpan &Back = Ranges.back();
  541. attachLowHighPC(Die, Front.Begin, Back.End);
  542. } else
  543. addScopeRangeList(Die, std::move(Ranges));
  544. }
  545. void DwarfCompileUnit::attachRangesOrLowHighPC(
  546. DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
  547. SmallVector<RangeSpan, 2> List;
  548. List.reserve(Ranges.size());
  549. for (const InsnRange &R : Ranges) {
  550. auto *BeginLabel = DD->getLabelBeforeInsn(R.first);
  551. auto *EndLabel = DD->getLabelAfterInsn(R.second);
  552. const auto *BeginMBB = R.first->getParent();
  553. const auto *EndMBB = R.second->getParent();
  554. const auto *MBB = BeginMBB;
  555. // Basic block sections allows basic block subsets to be placed in unique
  556. // sections. For each section, the begin and end label must be added to the
  557. // list. If there is more than one range, debug ranges must be used.
  558. // Otherwise, low/high PC can be used.
  559. // FIXME: Debug Info Emission depends on block order and this assumes that
  560. // the order of blocks will be frozen beyond this point.
  561. do {
  562. if (MBB->sameSection(EndMBB) || MBB->isEndSection()) {
  563. auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionIDNum()];
  564. List.push_back(
  565. {MBB->sameSection(BeginMBB) ? BeginLabel
  566. : MBBSectionRange.BeginLabel,
  567. MBB->sameSection(EndMBB) ? EndLabel : MBBSectionRange.EndLabel});
  568. }
  569. if (MBB->sameSection(EndMBB))
  570. break;
  571. MBB = MBB->getNextNode();
  572. } while (true);
  573. }
  574. attachRangesOrLowHighPC(Die, std::move(List));
  575. }
  576. // This scope represents inlined body of a function. Construct DIE to
  577. // represent this concrete inlined copy of the function.
  578. DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
  579. assert(Scope->getScopeNode());
  580. auto *DS = Scope->getScopeNode();
  581. auto *InlinedSP = getDISubprogram(DS);
  582. // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
  583. // was inlined from another compile unit.
  584. DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
  585. assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
  586. auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
  587. addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
  588. attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
  589. // Add the call site information to the DIE.
  590. const DILocation *IA = Scope->getInlinedAt();
  591. addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
  592. getOrCreateSourceID(IA->getFile()));
  593. addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
  594. if (IA->getColumn())
  595. addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn());
  596. if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
  597. addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
  598. IA->getDiscriminator());
  599. // Add name to the name table, we do this here because we're guaranteed
  600. // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
  601. DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
  602. return ScopeDIE;
  603. }
  604. // Construct new DW_TAG_lexical_block for this scope and attach
  605. // DW_AT_low_pc/DW_AT_high_pc labels.
  606. DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
  607. if (DD->isLexicalScopeDIENull(Scope))
  608. return nullptr;
  609. auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
  610. if (Scope->isAbstractScope())
  611. return ScopeDIE;
  612. attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
  613. return ScopeDIE;
  614. }
  615. /// constructVariableDIE - Construct a DIE for the given DbgVariable.
  616. DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
  617. auto D = constructVariableDIEImpl(DV, Abstract);
  618. DV.setDIE(*D);
  619. return D;
  620. }
  621. DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
  622. const LexicalScope &Scope) {
  623. auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
  624. insertDIE(DL.getLabel(), LabelDie);
  625. DL.setDIE(*LabelDie);
  626. if (Scope.isAbstractScope())
  627. applyLabelAttributes(DL, *LabelDie);
  628. return LabelDie;
  629. }
  630. DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
  631. bool Abstract) {
  632. // Define variable debug information entry.
  633. auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
  634. insertDIE(DV.getVariable(), VariableDie);
  635. if (Abstract) {
  636. applyVariableAttributes(DV, *VariableDie);
  637. return VariableDie;
  638. }
  639. // Add variable address.
  640. unsigned Index = DV.getDebugLocListIndex();
  641. if (Index != ~0U) {
  642. addLocationList(*VariableDie, dwarf::DW_AT_location, Index);
  643. auto TagOffset = DV.getDebugLocListTagOffset();
  644. if (TagOffset)
  645. addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
  646. *TagOffset);
  647. return VariableDie;
  648. }
  649. // Check if variable has a single location description.
  650. if (auto *DVal = DV.getValueLoc()) {
  651. if (!DVal->isVariadic()) {
  652. const DbgValueLocEntry *Entry = DVal->getLocEntries().begin();
  653. if (Entry->isLocation()) {
  654. addVariableAddress(DV, *VariableDie, Entry->getLoc());
  655. } else if (Entry->isInt()) {
  656. auto *Expr = DV.getSingleExpression();
  657. if (Expr && Expr->getNumElements()) {
  658. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  659. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  660. // If there is an expression, emit raw unsigned bytes.
  661. DwarfExpr.addFragmentOffset(Expr);
  662. DwarfExpr.addUnsignedConstant(Entry->getInt());
  663. DwarfExpr.addExpression(Expr);
  664. addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
  665. if (DwarfExpr.TagOffset)
  666. addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset,
  667. dwarf::DW_FORM_data1, *DwarfExpr.TagOffset);
  668. } else
  669. addConstantValue(*VariableDie, Entry->getInt(), DV.getType());
  670. } else if (Entry->isConstantFP()) {
  671. addConstantFPValue(*VariableDie, Entry->getConstantFP());
  672. } else if (Entry->isConstantInt()) {
  673. addConstantValue(*VariableDie, Entry->getConstantInt(), DV.getType());
  674. } else if (Entry->isTargetIndexLocation()) {
  675. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  676. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  677. const DIBasicType *BT = dyn_cast<DIBasicType>(
  678. static_cast<const Metadata *>(DV.getVariable()->getType()));
  679. DwarfDebug::emitDebugLocValue(*Asm, BT, *DVal, DwarfExpr);
  680. addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
  681. }
  682. return VariableDie;
  683. }
  684. // If any of the location entries are registers with the value 0, then the
  685. // location is undefined.
  686. if (any_of(DVal->getLocEntries(), [](const DbgValueLocEntry &Entry) {
  687. return Entry.isLocation() && !Entry.getLoc().getReg();
  688. }))
  689. return VariableDie;
  690. const DIExpression *Expr = DV.getSingleExpression();
  691. assert(Expr && "Variadic Debug Value must have an Expression.");
  692. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  693. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  694. DwarfExpr.addFragmentOffset(Expr);
  695. DIExpressionCursor Cursor(Expr);
  696. const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
  697. auto AddEntry = [&](const DbgValueLocEntry &Entry,
  698. DIExpressionCursor &Cursor) {
  699. if (Entry.isLocation()) {
  700. if (!DwarfExpr.addMachineRegExpression(TRI, Cursor,
  701. Entry.getLoc().getReg()))
  702. return false;
  703. } else if (Entry.isInt()) {
  704. // If there is an expression, emit raw unsigned bytes.
  705. DwarfExpr.addUnsignedConstant(Entry.getInt());
  706. } else if (Entry.isConstantFP()) {
  707. // DwarfExpression does not support arguments wider than 64 bits
  708. // (see PR52584).
  709. // TODO: Consider chunking expressions containing overly wide
  710. // arguments into separate pointer-sized fragment expressions.
  711. APInt RawBytes = Entry.getConstantFP()->getValueAPF().bitcastToAPInt();
  712. if (RawBytes.getBitWidth() > 64)
  713. return false;
  714. DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
  715. } else if (Entry.isConstantInt()) {
  716. APInt RawBytes = Entry.getConstantInt()->getValue();
  717. if (RawBytes.getBitWidth() > 64)
  718. return false;
  719. DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
  720. } else if (Entry.isTargetIndexLocation()) {
  721. TargetIndexLocation Loc = Entry.getTargetIndexLocation();
  722. // TODO TargetIndexLocation is a target-independent. Currently only the
  723. // WebAssembly-specific encoding is supported.
  724. assert(Asm->TM.getTargetTriple().isWasm());
  725. DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
  726. } else {
  727. llvm_unreachable("Unsupported Entry type.");
  728. }
  729. return true;
  730. };
  731. if (!DwarfExpr.addExpression(
  732. std::move(Cursor),
  733. [&](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
  734. return AddEntry(DVal->getLocEntries()[Idx], Cursor);
  735. }))
  736. return VariableDie;
  737. // Now attach the location information to the DIE.
  738. addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
  739. if (DwarfExpr.TagOffset)
  740. addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
  741. *DwarfExpr.TagOffset);
  742. return VariableDie;
  743. }
  744. // .. else use frame index.
  745. if (!DV.hasFrameIndexExprs())
  746. return VariableDie;
  747. Optional<unsigned> NVPTXAddressSpace;
  748. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  749. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  750. for (auto &Fragment : DV.getFrameIndexExprs()) {
  751. Register FrameReg;
  752. const DIExpression *Expr = Fragment.Expr;
  753. const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
  754. StackOffset Offset =
  755. TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
  756. DwarfExpr.addFragmentOffset(Expr);
  757. auto *TRI = Asm->MF->getSubtarget().getRegisterInfo();
  758. SmallVector<uint64_t, 8> Ops;
  759. TRI->getOffsetOpcodes(Offset, Ops);
  760. // According to
  761. // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
  762. // cuda-gdb requires DW_AT_address_class for all variables to be able to
  763. // correctly interpret address space of the variable address.
  764. // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
  765. // sequence for the NVPTX + gdb target.
  766. unsigned LocalNVPTXAddressSpace;
  767. if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
  768. const DIExpression *NewExpr =
  769. DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
  770. if (NewExpr != Expr) {
  771. Expr = NewExpr;
  772. NVPTXAddressSpace = LocalNVPTXAddressSpace;
  773. }
  774. }
  775. if (Expr)
  776. Ops.append(Expr->elements_begin(), Expr->elements_end());
  777. DIExpressionCursor Cursor(Ops);
  778. DwarfExpr.setMemoryLocationKind();
  779. if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
  780. addOpAddress(*Loc, FrameSymbol);
  781. else
  782. DwarfExpr.addMachineRegExpression(
  783. *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
  784. DwarfExpr.addExpression(std::move(Cursor));
  785. }
  786. if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
  787. // According to
  788. // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
  789. // cuda-gdb requires DW_AT_address_class for all variables to be able to
  790. // correctly interpret address space of the variable address.
  791. const unsigned NVPTX_ADDR_local_space = 6;
  792. addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
  793. NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
  794. }
  795. addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
  796. if (DwarfExpr.TagOffset)
  797. addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
  798. *DwarfExpr.TagOffset);
  799. return VariableDie;
  800. }
  801. DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
  802. const LexicalScope &Scope,
  803. DIE *&ObjectPointer) {
  804. auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
  805. if (DV.isObjectPointer())
  806. ObjectPointer = Var;
  807. return Var;
  808. }
  809. /// Return all DIVariables that appear in count: expressions.
  810. static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
  811. SmallVector<const DIVariable *, 2> Result;
  812. auto *Array = dyn_cast<DICompositeType>(Var->getType());
  813. if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
  814. return Result;
  815. if (auto *DLVar = Array->getDataLocation())
  816. Result.push_back(DLVar);
  817. if (auto *AsVar = Array->getAssociated())
  818. Result.push_back(AsVar);
  819. if (auto *AlVar = Array->getAllocated())
  820. Result.push_back(AlVar);
  821. for (auto *El : Array->getElements()) {
  822. if (auto *Subrange = dyn_cast<DISubrange>(El)) {
  823. if (auto Count = Subrange->getCount())
  824. if (auto *Dependency = Count.dyn_cast<DIVariable *>())
  825. Result.push_back(Dependency);
  826. if (auto LB = Subrange->getLowerBound())
  827. if (auto *Dependency = LB.dyn_cast<DIVariable *>())
  828. Result.push_back(Dependency);
  829. if (auto UB = Subrange->getUpperBound())
  830. if (auto *Dependency = UB.dyn_cast<DIVariable *>())
  831. Result.push_back(Dependency);
  832. if (auto ST = Subrange->getStride())
  833. if (auto *Dependency = ST.dyn_cast<DIVariable *>())
  834. Result.push_back(Dependency);
  835. } else if (auto *GenericSubrange = dyn_cast<DIGenericSubrange>(El)) {
  836. if (auto Count = GenericSubrange->getCount())
  837. if (auto *Dependency = Count.dyn_cast<DIVariable *>())
  838. Result.push_back(Dependency);
  839. if (auto LB = GenericSubrange->getLowerBound())
  840. if (auto *Dependency = LB.dyn_cast<DIVariable *>())
  841. Result.push_back(Dependency);
  842. if (auto UB = GenericSubrange->getUpperBound())
  843. if (auto *Dependency = UB.dyn_cast<DIVariable *>())
  844. Result.push_back(Dependency);
  845. if (auto ST = GenericSubrange->getStride())
  846. if (auto *Dependency = ST.dyn_cast<DIVariable *>())
  847. Result.push_back(Dependency);
  848. }
  849. }
  850. return Result;
  851. }
  852. /// Sort local variables so that variables appearing inside of helper
  853. /// expressions come first.
  854. static SmallVector<DbgVariable *, 8>
  855. sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
  856. SmallVector<DbgVariable *, 8> Result;
  857. SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
  858. // Map back from a DIVariable to its containing DbgVariable.
  859. SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
  860. // Set of DbgVariables in Result.
  861. SmallDenseSet<DbgVariable *, 8> Visited;
  862. // For cycle detection.
  863. SmallDenseSet<DbgVariable *, 8> Visiting;
  864. // Initialize the worklist and the DIVariable lookup table.
  865. for (auto Var : reverse(Input)) {
  866. DbgVar.insert({Var->getVariable(), Var});
  867. WorkList.push_back({Var, 0});
  868. }
  869. // Perform a stable topological sort by doing a DFS.
  870. while (!WorkList.empty()) {
  871. auto Item = WorkList.back();
  872. DbgVariable *Var = Item.getPointer();
  873. bool visitedAllDependencies = Item.getInt();
  874. WorkList.pop_back();
  875. assert(Var);
  876. // Already handled.
  877. if (Visited.count(Var))
  878. continue;
  879. // Add to Result if all dependencies are visited.
  880. if (visitedAllDependencies) {
  881. Visited.insert(Var);
  882. Result.push_back(Var);
  883. continue;
  884. }
  885. // Detect cycles.
  886. auto Res = Visiting.insert(Var);
  887. if (!Res.second) {
  888. assert(false && "dependency cycle in local variables");
  889. return Result;
  890. }
  891. // Push dependencies and this node onto the worklist, so that this node is
  892. // visited again after all of its dependencies are handled.
  893. WorkList.push_back({Var, 1});
  894. for (auto *Dependency : dependencies(Var)) {
  895. // Don't add dependency if it is in a different lexical scope or a global.
  896. if (const auto *Dep = dyn_cast<const DILocalVariable>(Dependency))
  897. if (DbgVariable *Var = DbgVar.lookup(Dep))
  898. WorkList.push_back({Var, 0});
  899. }
  900. }
  901. return Result;
  902. }
  903. DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
  904. LexicalScope *Scope) {
  905. DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
  906. if (Scope) {
  907. assert(!Scope->getInlinedAt());
  908. assert(!Scope->isAbstractScope());
  909. // Collect lexical scope children first.
  910. // ObjectPointer might be a local (non-argument) local variable if it's a
  911. // block's synthetic this pointer.
  912. if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
  913. addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
  914. }
  915. // If this is a variadic function, add an unspecified parameter.
  916. DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
  917. // If we have a single element of null, it is a function that returns void.
  918. // If we have more than one elements and the last one is null, it is a
  919. // variadic function.
  920. if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
  921. !includeMinimalInlineScopes())
  922. ScopeDIE.addChild(
  923. DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
  924. return ScopeDIE;
  925. }
  926. DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
  927. DIE &ScopeDIE) {
  928. DIE *ObjectPointer = nullptr;
  929. // Emit function arguments (order is significant).
  930. auto Vars = DU->getScopeVariables().lookup(Scope);
  931. for (auto &DV : Vars.Args)
  932. ScopeDIE.addChild(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
  933. // Emit local variables.
  934. auto Locals = sortLocalVars(Vars.Locals);
  935. for (DbgVariable *DV : Locals)
  936. ScopeDIE.addChild(constructVariableDIE(*DV, *Scope, ObjectPointer));
  937. // Emit imported entities (skipped in gmlt-like data).
  938. if (!includeMinimalInlineScopes()) {
  939. for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
  940. ScopeDIE.addChild(constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
  941. }
  942. // Emit labels.
  943. for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
  944. ScopeDIE.addChild(constructLabelDIE(*DL, *Scope));
  945. // Emit inner lexical scopes.
  946. auto needToEmitLexicalScope = [this](LexicalScope *LS) {
  947. if (isa<DISubprogram>(LS->getScopeNode()))
  948. return true;
  949. auto Vars = DU->getScopeVariables().lookup(LS);
  950. if (!Vars.Args.empty() || !Vars.Locals.empty())
  951. return true;
  952. if (!includeMinimalInlineScopes() &&
  953. !ImportedEntities[LS->getScopeNode()].empty())
  954. return true;
  955. return false;
  956. };
  957. for (LexicalScope *LS : Scope->getChildren()) {
  958. // If the lexical block doesn't have non-scope children, skip
  959. // its emission and put its children directly to the parent scope.
  960. if (needToEmitLexicalScope(LS))
  961. constructScopeDIE(LS, ScopeDIE);
  962. else
  963. createAndAddScopeChildren(LS, ScopeDIE);
  964. }
  965. return ObjectPointer;
  966. }
  967. void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
  968. LexicalScope *Scope) {
  969. DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
  970. if (AbsDef)
  971. return;
  972. auto *SP = cast<DISubprogram>(Scope->getScopeNode());
  973. DIE *ContextDIE;
  974. DwarfCompileUnit *ContextCU = this;
  975. if (includeMinimalInlineScopes())
  976. ContextDIE = &getUnitDie();
  977. // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
  978. // the important distinction that the debug node is not associated with the
  979. // DIE (since the debug node will be associated with the concrete DIE, if
  980. // any). It could be refactored to some common utility function.
  981. else if (auto *SPDecl = SP->getDeclaration()) {
  982. ContextDIE = &getUnitDie();
  983. getOrCreateSubprogramDIE(SPDecl);
  984. } else {
  985. ContextDIE = getOrCreateContextDIE(SP->getScope());
  986. // The scope may be shared with a subprogram that has already been
  987. // constructed in another CU, in which case we need to construct this
  988. // subprogram in the same CU.
  989. ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
  990. }
  991. // Passing null as the associated node because the abstract definition
  992. // shouldn't be found by lookup.
  993. AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
  994. ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
  995. ContextCU->addSInt(*AbsDef, dwarf::DW_AT_inline,
  996. DD->getDwarfVersion() <= 4 ? Optional<dwarf::Form>()
  997. : dwarf::DW_FORM_implicit_const,
  998. dwarf::DW_INL_inlined);
  999. if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
  1000. ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
  1001. }
  1002. bool DwarfCompileUnit::useGNUAnalogForDwarf5Feature() const {
  1003. return DD->getDwarfVersion() == 4 && !DD->tuneForLLDB();
  1004. }
  1005. dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const {
  1006. if (!useGNUAnalogForDwarf5Feature())
  1007. return Tag;
  1008. switch (Tag) {
  1009. case dwarf::DW_TAG_call_site:
  1010. return dwarf::DW_TAG_GNU_call_site;
  1011. case dwarf::DW_TAG_call_site_parameter:
  1012. return dwarf::DW_TAG_GNU_call_site_parameter;
  1013. default:
  1014. llvm_unreachable("DWARF5 tag with no GNU analog");
  1015. }
  1016. }
  1017. dwarf::Attribute
  1018. DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const {
  1019. if (!useGNUAnalogForDwarf5Feature())
  1020. return Attr;
  1021. switch (Attr) {
  1022. case dwarf::DW_AT_call_all_calls:
  1023. return dwarf::DW_AT_GNU_all_call_sites;
  1024. case dwarf::DW_AT_call_target:
  1025. return dwarf::DW_AT_GNU_call_site_target;
  1026. case dwarf::DW_AT_call_origin:
  1027. return dwarf::DW_AT_abstract_origin;
  1028. case dwarf::DW_AT_call_return_pc:
  1029. return dwarf::DW_AT_low_pc;
  1030. case dwarf::DW_AT_call_value:
  1031. return dwarf::DW_AT_GNU_call_site_value;
  1032. case dwarf::DW_AT_call_tail_call:
  1033. return dwarf::DW_AT_GNU_tail_call;
  1034. default:
  1035. llvm_unreachable("DWARF5 attribute with no GNU analog");
  1036. }
  1037. }
  1038. dwarf::LocationAtom
  1039. DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const {
  1040. if (!useGNUAnalogForDwarf5Feature())
  1041. return Loc;
  1042. switch (Loc) {
  1043. case dwarf::DW_OP_entry_value:
  1044. return dwarf::DW_OP_GNU_entry_value;
  1045. default:
  1046. llvm_unreachable("DWARF5 location atom with no GNU analog");
  1047. }
  1048. }
  1049. DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE,
  1050. const DISubprogram *CalleeSP,
  1051. bool IsTail,
  1052. const MCSymbol *PCAddr,
  1053. const MCSymbol *CallAddr,
  1054. unsigned CallReg) {
  1055. // Insert a call site entry DIE within ScopeDIE.
  1056. DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site),
  1057. ScopeDIE, nullptr);
  1058. if (CallReg) {
  1059. // Indirect call.
  1060. addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target),
  1061. MachineLocation(CallReg));
  1062. } else {
  1063. DIE *CalleeDIE = getOrCreateSubprogramDIE(CalleeSP);
  1064. assert(CalleeDIE && "Could not create DIE for call site entry origin");
  1065. addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin),
  1066. *CalleeDIE);
  1067. }
  1068. if (IsTail) {
  1069. // Attach DW_AT_call_tail_call to tail calls for standards compliance.
  1070. addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call));
  1071. // Attach the address of the branch instruction to allow the debugger to
  1072. // show where the tail call occurred. This attribute has no GNU analog.
  1073. //
  1074. // GDB works backwards from non-standard usage of DW_AT_low_pc (in DWARF4
  1075. // mode -- equivalently, in DWARF5 mode, DW_AT_call_return_pc) at tail-call
  1076. // site entries to figure out the PC of tail-calling branch instructions.
  1077. // This means it doesn't need the compiler to emit DW_AT_call_pc, so we
  1078. // don't emit it here.
  1079. //
  1080. // There's no need to tie non-GDB debuggers to this non-standardness, as it
  1081. // adds unnecessary complexity to the debugger. For non-GDB debuggers, emit
  1082. // the standard DW_AT_call_pc info.
  1083. if (!useGNUAnalogForDwarf5Feature())
  1084. addLabelAddress(CallSiteDIE, dwarf::DW_AT_call_pc, CallAddr);
  1085. }
  1086. // Attach the return PC to allow the debugger to disambiguate call paths
  1087. // from one function to another.
  1088. //
  1089. // The return PC is only really needed when the call /isn't/ a tail call, but
  1090. // GDB expects it in DWARF4 mode, even for tail calls (see the comment above
  1091. // the DW_AT_call_pc emission logic for an explanation).
  1092. if (!IsTail || useGNUAnalogForDwarf5Feature()) {
  1093. assert(PCAddr && "Missing return PC information for a call");
  1094. addLabelAddress(CallSiteDIE,
  1095. getDwarf5OrGNUAttr(dwarf::DW_AT_call_return_pc), PCAddr);
  1096. }
  1097. return CallSiteDIE;
  1098. }
  1099. void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
  1100. DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
  1101. for (const auto &Param : Params) {
  1102. unsigned Register = Param.getRegister();
  1103. auto CallSiteDieParam =
  1104. DIE::get(DIEValueAllocator,
  1105. getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter));
  1106. insertDIE(CallSiteDieParam);
  1107. addAddress(*CallSiteDieParam, dwarf::DW_AT_location,
  1108. MachineLocation(Register));
  1109. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  1110. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  1111. DwarfExpr.setCallSiteParamValueFlag();
  1112. DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr);
  1113. addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value),
  1114. DwarfExpr.finalize());
  1115. CallSiteDIE.addChild(CallSiteDieParam);
  1116. }
  1117. }
  1118. DIE *DwarfCompileUnit::constructImportedEntityDIE(
  1119. const DIImportedEntity *Module) {
  1120. DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
  1121. insertDIE(Module, IMDie);
  1122. DIE *EntityDie;
  1123. auto *Entity = Module->getEntity();
  1124. if (auto *NS = dyn_cast<DINamespace>(Entity))
  1125. EntityDie = getOrCreateNameSpace(NS);
  1126. else if (auto *M = dyn_cast<DIModule>(Entity))
  1127. EntityDie = getOrCreateModule(M);
  1128. else if (auto *SP = dyn_cast<DISubprogram>(Entity))
  1129. EntityDie = getOrCreateSubprogramDIE(SP);
  1130. else if (auto *T = dyn_cast<DIType>(Entity))
  1131. EntityDie = getOrCreateTypeDIE(T);
  1132. else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
  1133. EntityDie = getOrCreateGlobalVariableDIE(GV, {});
  1134. else
  1135. EntityDie = getDIE(Entity);
  1136. assert(EntityDie);
  1137. addSourceLine(*IMDie, Module->getLine(), Module->getFile());
  1138. addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
  1139. StringRef Name = Module->getName();
  1140. if (!Name.empty())
  1141. addString(*IMDie, dwarf::DW_AT_name, Name);
  1142. // This is for imported module with renamed entities (such as variables and
  1143. // subprograms).
  1144. DINodeArray Elements = Module->getElements();
  1145. for (const auto *Element : Elements) {
  1146. if (!Element)
  1147. continue;
  1148. IMDie->addChild(
  1149. constructImportedEntityDIE(cast<DIImportedEntity>(Element)));
  1150. }
  1151. return IMDie;
  1152. }
  1153. void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
  1154. DIE *D = getDIE(SP);
  1155. if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
  1156. if (D)
  1157. // If this subprogram has an abstract definition, reference that
  1158. addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
  1159. } else {
  1160. assert(D || includeMinimalInlineScopes());
  1161. if (D)
  1162. // And attach the attributes
  1163. applySubprogramAttributesToDefinition(SP, *D);
  1164. }
  1165. }
  1166. void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
  1167. DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
  1168. auto *Die = Entity->getDIE();
  1169. /// Label may be used to generate DW_AT_low_pc, so put it outside
  1170. /// if/else block.
  1171. const DbgLabel *Label = nullptr;
  1172. if (AbsEntity && AbsEntity->getDIE()) {
  1173. addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
  1174. Label = dyn_cast<const DbgLabel>(Entity);
  1175. } else {
  1176. if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
  1177. applyVariableAttributes(*Var, *Die);
  1178. else if ((Label = dyn_cast<const DbgLabel>(Entity)))
  1179. applyLabelAttributes(*Label, *Die);
  1180. else
  1181. llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
  1182. }
  1183. if (Label)
  1184. if (const auto *Sym = Label->getSymbol())
  1185. addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
  1186. }
  1187. DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
  1188. auto &AbstractEntities = getAbstractEntities();
  1189. auto I = AbstractEntities.find(Node);
  1190. if (I != AbstractEntities.end())
  1191. return I->second.get();
  1192. return nullptr;
  1193. }
  1194. void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
  1195. LexicalScope *Scope) {
  1196. assert(Scope && Scope->isAbstractScope());
  1197. auto &Entity = getAbstractEntities()[Node];
  1198. if (isa<const DILocalVariable>(Node)) {
  1199. Entity = std::make_unique<DbgVariable>(
  1200. cast<const DILocalVariable>(Node), nullptr /* IA */);;
  1201. DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
  1202. } else if (isa<const DILabel>(Node)) {
  1203. Entity = std::make_unique<DbgLabel>(
  1204. cast<const DILabel>(Node), nullptr /* IA */);
  1205. DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
  1206. }
  1207. }
  1208. void DwarfCompileUnit::emitHeader(bool UseOffsets) {
  1209. // Don't bother labeling the .dwo unit, as its offset isn't used.
  1210. if (!Skeleton && !DD->useSectionsAsReferences()) {
  1211. LabelBegin = Asm->createTempSymbol("cu_begin");
  1212. Asm->OutStreamer->emitLabel(LabelBegin);
  1213. }
  1214. dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
  1215. : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
  1216. : dwarf::DW_UT_compile;
  1217. DwarfUnit::emitCommonHeader(UseOffsets, UT);
  1218. if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
  1219. Asm->emitInt64(getDWOId());
  1220. }
  1221. bool DwarfCompileUnit::hasDwarfPubSections() const {
  1222. switch (CUNode->getNameTableKind()) {
  1223. case DICompileUnit::DebugNameTableKind::None:
  1224. return false;
  1225. // Opting in to GNU Pubnames/types overrides the default to ensure these are
  1226. // generated for things like Gold's gdb_index generation.
  1227. case DICompileUnit::DebugNameTableKind::GNU:
  1228. return true;
  1229. case DICompileUnit::DebugNameTableKind::Default:
  1230. return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
  1231. !CUNode->isDebugDirectivesOnly() &&
  1232. DD->getAccelTableKind() != AccelTableKind::Apple &&
  1233. DD->getDwarfVersion() < 5;
  1234. }
  1235. llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
  1236. }
  1237. /// addGlobalName - Add a new global name to the compile unit.
  1238. void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
  1239. const DIScope *Context) {
  1240. if (!hasDwarfPubSections())
  1241. return;
  1242. std::string FullName = getParentContextString(Context) + Name.str();
  1243. GlobalNames[FullName] = &Die;
  1244. }
  1245. void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
  1246. const DIScope *Context) {
  1247. if (!hasDwarfPubSections())
  1248. return;
  1249. std::string FullName = getParentContextString(Context) + Name.str();
  1250. // Insert, allowing the entry to remain as-is if it's already present
  1251. // This way the CU-level type DIE is preferred over the "can't describe this
  1252. // type as a unit offset because it's not really in the CU at all, it's only
  1253. // in a type unit"
  1254. GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
  1255. }
  1256. /// Add a new global type to the unit.
  1257. void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
  1258. const DIScope *Context) {
  1259. if (!hasDwarfPubSections())
  1260. return;
  1261. std::string FullName = getParentContextString(Context) + Ty->getName().str();
  1262. GlobalTypes[FullName] = &Die;
  1263. }
  1264. void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
  1265. const DIScope *Context) {
  1266. if (!hasDwarfPubSections())
  1267. return;
  1268. std::string FullName = getParentContextString(Context) + Ty->getName().str();
  1269. // Insert, allowing the entry to remain as-is if it's already present
  1270. // This way the CU-level type DIE is preferred over the "can't describe this
  1271. // type as a unit offset because it's not really in the CU at all, it's only
  1272. // in a type unit"
  1273. GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
  1274. }
  1275. void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
  1276. MachineLocation Location) {
  1277. if (DV.hasComplexAddress())
  1278. addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
  1279. else
  1280. addAddress(Die, dwarf::DW_AT_location, Location);
  1281. }
  1282. /// Add an address attribute to a die based on the location provided.
  1283. void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
  1284. const MachineLocation &Location) {
  1285. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  1286. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  1287. if (Location.isIndirect())
  1288. DwarfExpr.setMemoryLocationKind();
  1289. DIExpressionCursor Cursor({});
  1290. const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
  1291. if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
  1292. return;
  1293. DwarfExpr.addExpression(std::move(Cursor));
  1294. // Now attach the location information to the DIE.
  1295. addBlock(Die, Attribute, DwarfExpr.finalize());
  1296. if (DwarfExpr.TagOffset)
  1297. addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
  1298. *DwarfExpr.TagOffset);
  1299. }
  1300. /// Start with the address based on the location provided, and generate the
  1301. /// DWARF information necessary to find the actual variable given the extra
  1302. /// address information encoded in the DbgVariable, starting from the starting
  1303. /// location. Add the DWARF information to the die.
  1304. void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
  1305. dwarf::Attribute Attribute,
  1306. const MachineLocation &Location) {
  1307. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  1308. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  1309. const DIExpression *DIExpr = DV.getSingleExpression();
  1310. DwarfExpr.addFragmentOffset(DIExpr);
  1311. DwarfExpr.setLocation(Location, DIExpr);
  1312. DIExpressionCursor Cursor(DIExpr);
  1313. if (DIExpr->isEntryValue())
  1314. DwarfExpr.beginEntryValueExpression(Cursor);
  1315. const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
  1316. if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
  1317. return;
  1318. DwarfExpr.addExpression(std::move(Cursor));
  1319. // Now attach the location information to the DIE.
  1320. addBlock(Die, Attribute, DwarfExpr.finalize());
  1321. if (DwarfExpr.TagOffset)
  1322. addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
  1323. *DwarfExpr.TagOffset);
  1324. }
  1325. /// Add a Dwarf loclistptr attribute data and value.
  1326. void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
  1327. unsigned Index) {
  1328. dwarf::Form Form = (DD->getDwarfVersion() >= 5)
  1329. ? dwarf::DW_FORM_loclistx
  1330. : DD->getDwarfSectionOffsetForm();
  1331. addAttribute(Die, Attribute, Form, DIELocList(Index));
  1332. }
  1333. void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
  1334. DIE &VariableDie) {
  1335. StringRef Name = Var.getName();
  1336. if (!Name.empty())
  1337. addString(VariableDie, dwarf::DW_AT_name, Name);
  1338. const auto *DIVar = Var.getVariable();
  1339. if (DIVar) {
  1340. if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
  1341. addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
  1342. AlignInBytes);
  1343. addAnnotation(VariableDie, DIVar->getAnnotations());
  1344. }
  1345. addSourceLine(VariableDie, DIVar);
  1346. addType(VariableDie, Var.getType());
  1347. if (Var.isArtificial())
  1348. addFlag(VariableDie, dwarf::DW_AT_artificial);
  1349. }
  1350. void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
  1351. DIE &LabelDie) {
  1352. StringRef Name = Label.getName();
  1353. if (!Name.empty())
  1354. addString(LabelDie, dwarf::DW_AT_name, Name);
  1355. const auto *DILabel = Label.getLabel();
  1356. addSourceLine(LabelDie, DILabel);
  1357. }
  1358. /// Add a Dwarf expression attribute data and value.
  1359. void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
  1360. const MCExpr *Expr) {
  1361. addAttribute(Die, (dwarf::Attribute)0, Form, DIEExpr(Expr));
  1362. }
  1363. void DwarfCompileUnit::applySubprogramAttributesToDefinition(
  1364. const DISubprogram *SP, DIE &SPDie) {
  1365. auto *SPDecl = SP->getDeclaration();
  1366. auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
  1367. applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
  1368. addGlobalName(SP->getName(), SPDie, Context);
  1369. }
  1370. bool DwarfCompileUnit::isDwoUnit() const {
  1371. return DD->useSplitDwarf() && Skeleton;
  1372. }
  1373. void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
  1374. constructTypeDIE(D, CTy);
  1375. }
  1376. bool DwarfCompileUnit::includeMinimalInlineScopes() const {
  1377. return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
  1378. (DD->useSplitDwarf() && !Skeleton);
  1379. }
  1380. void DwarfCompileUnit::addAddrTableBase() {
  1381. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  1382. MCSymbol *Label = DD->getAddressPool().getLabel();
  1383. addSectionLabel(getUnitDie(),
  1384. DD->getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
  1385. : dwarf::DW_AT_GNU_addr_base,
  1386. Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
  1387. }
  1388. void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
  1389. addAttribute(Die, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
  1390. new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
  1391. }
  1392. void DwarfCompileUnit::createBaseTypeDIEs() {
  1393. // Insert the base_type DIEs directly after the CU so that their offsets will
  1394. // fit in the fixed size ULEB128 used inside the location expressions.
  1395. // Maintain order by iterating backwards and inserting to the front of CU
  1396. // child list.
  1397. for (auto &Btr : reverse(ExprRefedBaseTypes)) {
  1398. DIE &Die = getUnitDie().addChildFront(
  1399. DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
  1400. SmallString<32> Str;
  1401. addString(Die, dwarf::DW_AT_name,
  1402. Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
  1403. "_" + Twine(Btr.BitSize)).toStringRef(Str));
  1404. addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
  1405. // Round up to smallest number of bytes that contains this number of bits.
  1406. addUInt(Die, dwarf::DW_AT_byte_size, None, divideCeil(Btr.BitSize, 8));
  1407. Btr.Die = &Die;
  1408. }
  1409. }