DwarfCompileUnit.cpp 63 KB

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