DwarfDebug.cpp 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191
  1. //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains support for writing dwarf debug info into asm files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "DwarfDebug.h"
  14. #include "ByteStreamer.h"
  15. #include "DIEHash.h"
  16. #include "DwarfCompileUnit.h"
  17. #include "DwarfExpression.h"
  18. #include "DwarfUnit.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/ADT/StringExtras.h"
  22. #include "llvm/ADT/Triple.h"
  23. #include "llvm/CodeGen/DIE.h"
  24. #include "llvm/CodeGen/MachineFunction.h"
  25. #include "llvm/CodeGen/MachineModuleInfo.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DIBuilder.h"
  28. #include "llvm/IR/DataLayout.h"
  29. #include "llvm/IR/DebugInfo.h"
  30. #include "llvm/IR/Instructions.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/ValueHandle.h"
  33. #include "llvm/MC/MCAsmInfo.h"
  34. #include "llvm/MC/MCSection.h"
  35. #include "llvm/MC/MCStreamer.h"
  36. #include "llvm/MC/MCSymbol.h"
  37. #include "llvm/Support/CommandLine.h"
  38. #include "llvm/Support/Debug.h"
  39. #include "llvm/Support/Dwarf.h"
  40. #include "llvm/Support/Endian.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include "llvm/Support/FormattedStream.h"
  43. #include "llvm/Support/LEB128.h"
  44. #include "llvm/Support/MD5.h"
  45. #include "llvm/Support/Path.h"
  46. #include "llvm/Support/Timer.h"
  47. #include "llvm/Target/TargetFrameLowering.h"
  48. #include "llvm/Target/TargetLoweringObjectFile.h"
  49. #include "llvm/Target/TargetMachine.h"
  50. #include "llvm/Target/TargetOptions.h"
  51. #include "llvm/Target/TargetRegisterInfo.h"
  52. #include "llvm/Target/TargetSubtargetInfo.h"
  53. using namespace llvm;
  54. #define DEBUG_TYPE "dwarfdebug"
  55. static cl::opt<bool>
  56. DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
  57. cl::desc("Disable debug info printing"));
  58. static cl::opt<bool> UnknownLocations(
  59. "use-unknown-locations", cl::Hidden,
  60. cl::desc("Make an absence of debug location information explicit."),
  61. cl::init(false));
  62. static cl::opt<bool>
  63. GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
  64. cl::desc("Generate GNU-style pubnames and pubtypes"),
  65. cl::init(false));
  66. static cl::opt<bool> GenerateARangeSection("generate-arange-section",
  67. cl::Hidden,
  68. cl::desc("Generate dwarf aranges"),
  69. cl::init(false));
  70. namespace {
  71. enum DefaultOnOff { Default, Enable, Disable };
  72. }
  73. static cl::opt<DefaultOnOff>
  74. DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
  75. cl::desc("Output prototype dwarf accelerator tables."),
  76. cl::values(clEnumVal(Default, "Default for platform"),
  77. clEnumVal(Enable, "Enabled"),
  78. clEnumVal(Disable, "Disabled"), clEnumValEnd),
  79. cl::init(Default));
  80. static cl::opt<DefaultOnOff>
  81. SplitDwarf("split-dwarf", cl::Hidden,
  82. cl::desc("Output DWARF5 split debug info."),
  83. cl::values(clEnumVal(Default, "Default for platform"),
  84. clEnumVal(Enable, "Enabled"),
  85. clEnumVal(Disable, "Disabled"), clEnumValEnd),
  86. cl::init(Default));
  87. static cl::opt<DefaultOnOff>
  88. DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
  89. cl::desc("Generate DWARF pubnames and pubtypes sections"),
  90. cl::values(clEnumVal(Default, "Default for platform"),
  91. clEnumVal(Enable, "Enabled"),
  92. clEnumVal(Disable, "Disabled"), clEnumValEnd),
  93. cl::init(Default));
  94. static const char *const DWARFGroupName = "DWARF Emission";
  95. static const char *const DbgTimerName = "DWARF Debug Writer";
  96. //===----------------------------------------------------------------------===//
  97. /// resolve - Look in the DwarfDebug map for the MDNode that
  98. /// corresponds to the reference.
  99. template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
  100. return DD->resolve(Ref);
  101. }
  102. bool DbgVariable::isBlockByrefVariable() const {
  103. assert(Var.isVariable() && "Invalid complex DbgVariable!");
  104. return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
  105. }
  106. DIType DbgVariable::getType() const {
  107. DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
  108. // FIXME: isBlockByrefVariable should be reformulated in terms of complex
  109. // addresses instead.
  110. if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
  111. /* Byref variables, in Blocks, are declared by the programmer as
  112. "SomeType VarName;", but the compiler creates a
  113. __Block_byref_x_VarName struct, and gives the variable VarName
  114. either the struct, or a pointer to the struct, as its type. This
  115. is necessary for various behind-the-scenes things the compiler
  116. needs to do with by-reference variables in blocks.
  117. However, as far as the original *programmer* is concerned, the
  118. variable should still have type 'SomeType', as originally declared.
  119. The following function dives into the __Block_byref_x_VarName
  120. struct to find the original type of the variable. This will be
  121. passed back to the code generating the type for the Debug
  122. Information Entry for the variable 'VarName'. 'VarName' will then
  123. have the original type 'SomeType' in its debug information.
  124. The original type 'SomeType' will be the type of the field named
  125. 'VarName' inside the __Block_byref_x_VarName struct.
  126. NOTE: In order for this to not completely fail on the debugger
  127. side, the Debug Information Entry for the variable VarName needs to
  128. have a DW_AT_location that tells the debugger how to unwind through
  129. the pointers and __Block_byref_x_VarName struct to find the actual
  130. value of the variable. The function addBlockByrefType does this. */
  131. DIType subType = Ty;
  132. uint16_t tag = Ty.getTag();
  133. if (tag == dwarf::DW_TAG_pointer_type)
  134. subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
  135. DIArray Elements = DICompositeType(subType).getElements();
  136. for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
  137. DIDerivedType DT(Elements.getElement(i));
  138. if (getName() == DT.getName())
  139. return (resolve(DT.getTypeDerivedFrom()));
  140. }
  141. }
  142. return Ty;
  143. }
  144. static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
  145. DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
  146. DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
  147. DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
  148. DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
  149. : Asm(A), MMI(Asm->MMI), PrevLabel(nullptr), GlobalRangeCount(0),
  150. InfoHolder(A, *this, "info_string", DIEValueAllocator),
  151. UsedNonDefaultText(false),
  152. SkeletonHolder(A, *this, "skel_string", DIEValueAllocator),
  153. IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
  154. AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
  155. dwarf::DW_FORM_data4)),
  156. AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
  157. dwarf::DW_FORM_data4)),
  158. AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
  159. dwarf::DW_FORM_data4)),
  160. AccelTypes(TypeAtoms) {
  161. DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
  162. DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
  163. DwarfLineSectionSym = nullptr;
  164. DwarfAddrSectionSym = nullptr;
  165. DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
  166. FunctionBeginSym = FunctionEndSym = nullptr;
  167. CurFn = nullptr;
  168. CurMI = nullptr;
  169. // Turn on accelerator tables for Darwin by default, pubnames by
  170. // default for non-Darwin, and handle split dwarf.
  171. if (DwarfAccelTables == Default)
  172. HasDwarfAccelTables = IsDarwin;
  173. else
  174. HasDwarfAccelTables = DwarfAccelTables == Enable;
  175. if (SplitDwarf == Default)
  176. HasSplitDwarf = false;
  177. else
  178. HasSplitDwarf = SplitDwarf == Enable;
  179. if (DwarfPubSections == Default)
  180. HasDwarfPubSections = !IsDarwin;
  181. else
  182. HasDwarfPubSections = DwarfPubSections == Enable;
  183. unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
  184. DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
  185. : MMI->getModule()->getDwarfVersion();
  186. Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
  187. {
  188. NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
  189. beginModule();
  190. }
  191. }
  192. // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
  193. DwarfDebug::~DwarfDebug() { }
  194. // Switch to the specified MCSection and emit an assembler
  195. // temporary label to it if SymbolStem is specified.
  196. static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
  197. const char *SymbolStem = nullptr) {
  198. Asm->OutStreamer.SwitchSection(Section);
  199. if (!SymbolStem)
  200. return nullptr;
  201. MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
  202. Asm->OutStreamer.EmitLabel(TmpSym);
  203. return TmpSym;
  204. }
  205. static bool isObjCClass(StringRef Name) {
  206. return Name.startswith("+") || Name.startswith("-");
  207. }
  208. static bool hasObjCCategory(StringRef Name) {
  209. if (!isObjCClass(Name))
  210. return false;
  211. return Name.find(") ") != StringRef::npos;
  212. }
  213. static void getObjCClassCategory(StringRef In, StringRef &Class,
  214. StringRef &Category) {
  215. if (!hasObjCCategory(In)) {
  216. Class = In.slice(In.find('[') + 1, In.find(' '));
  217. Category = "";
  218. return;
  219. }
  220. Class = In.slice(In.find('[') + 1, In.find('('));
  221. Category = In.slice(In.find('[') + 1, In.find(' '));
  222. return;
  223. }
  224. static StringRef getObjCMethodName(StringRef In) {
  225. return In.slice(In.find(' ') + 1, In.find(']'));
  226. }
  227. // Helper for sorting sections into a stable output order.
  228. static bool SectionSort(const MCSection *A, const MCSection *B) {
  229. std::string LA = (A ? A->getLabelBeginName() : "");
  230. std::string LB = (B ? B->getLabelBeginName() : "");
  231. return LA < LB;
  232. }
  233. // Add the various names to the Dwarf accelerator table names.
  234. // TODO: Determine whether or not we should add names for programs
  235. // that do not have a DW_AT_name or DW_AT_linkage_name field - this
  236. // is only slightly different than the lookup of non-standard ObjC names.
  237. void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
  238. if (!SP.isDefinition())
  239. return;
  240. addAccelName(SP.getName(), Die);
  241. // If the linkage name is different than the name, go ahead and output
  242. // that as well into the name table.
  243. if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
  244. addAccelName(SP.getLinkageName(), Die);
  245. // If this is an Objective-C selector name add it to the ObjC accelerator
  246. // too.
  247. if (isObjCClass(SP.getName())) {
  248. StringRef Class, Category;
  249. getObjCClassCategory(SP.getName(), Class, Category);
  250. addAccelObjC(Class, Die);
  251. if (Category != "")
  252. addAccelObjC(Category, Die);
  253. // Also add the base method name to the name table.
  254. addAccelName(getObjCMethodName(SP.getName()), Die);
  255. }
  256. }
  257. /// isSubprogramContext - Return true if Context is either a subprogram
  258. /// or another context nested inside a subprogram.
  259. bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
  260. if (!Context)
  261. return false;
  262. DIDescriptor D(Context);
  263. if (D.isSubprogram())
  264. return true;
  265. if (D.isType())
  266. return isSubprogramContext(resolve(DIType(Context).getContext()));
  267. return false;
  268. }
  269. /// Check whether we should create a DIE for the given Scope, return true
  270. /// if we don't create a DIE (the corresponding DIE is null).
  271. bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
  272. if (Scope->isAbstractScope())
  273. return false;
  274. // We don't create a DIE if there is no Range.
  275. const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
  276. if (Ranges.empty())
  277. return true;
  278. if (Ranges.size() > 1)
  279. return false;
  280. // We don't create a DIE if we have a single Range and the end label
  281. // is null.
  282. return !getLabelAfterInsn(Ranges.front().second);
  283. }
  284. template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
  285. F(CU);
  286. if (auto *SkelCU = CU.getSkeleton())
  287. F(*SkelCU);
  288. }
  289. void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
  290. assert(Scope && Scope->getScopeNode());
  291. assert(Scope->isAbstractScope());
  292. assert(!Scope->getInlinedAt());
  293. const MDNode *SP = Scope->getScopeNode();
  294. ProcessedSPNodes.insert(SP);
  295. // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
  296. // was inlined from another compile unit.
  297. auto &CU = SPMap[SP];
  298. forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
  299. CU.constructAbstractSubprogramScopeDIE(Scope);
  300. });
  301. }
  302. void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
  303. if (!GenerateGnuPubSections)
  304. return;
  305. U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
  306. }
  307. // Create new DwarfCompileUnit for the given metadata node with tag
  308. // DW_TAG_compile_unit.
  309. DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
  310. StringRef FN = DIUnit.getFilename();
  311. CompilationDir = DIUnit.getDirectory();
  312. auto OwnedUnit = make_unique<DwarfCompileUnit>(
  313. InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
  314. DwarfCompileUnit &NewCU = *OwnedUnit;
  315. DIE &Die = NewCU.getUnitDie();
  316. InfoHolder.addUnit(std::move(OwnedUnit));
  317. if (useSplitDwarf())
  318. NewCU.setSkeleton(constructSkeletonCU(NewCU));
  319. // LTO with assembly output shares a single line table amongst multiple CUs.
  320. // To avoid the compilation directory being ambiguous, let the line table
  321. // explicitly describe the directory of all files, never relying on the
  322. // compilation directory.
  323. if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
  324. Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
  325. NewCU.getUniqueID(), CompilationDir);
  326. NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
  327. NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
  328. DIUnit.getLanguage());
  329. NewCU.addString(Die, dwarf::DW_AT_name, FN);
  330. if (!useSplitDwarf()) {
  331. NewCU.initStmtList(DwarfLineSectionSym);
  332. // If we're using split dwarf the compilation dir is going to be in the
  333. // skeleton CU and so we don't need to duplicate it here.
  334. if (!CompilationDir.empty())
  335. NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
  336. addGnuPubAttributes(NewCU, Die);
  337. }
  338. if (DIUnit.isOptimized())
  339. NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
  340. StringRef Flags = DIUnit.getFlags();
  341. if (!Flags.empty())
  342. NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
  343. if (unsigned RVer = DIUnit.getRunTimeVersion())
  344. NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
  345. dwarf::DW_FORM_data1, RVer);
  346. if (useSplitDwarf())
  347. NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
  348. DwarfInfoDWOSectionSym);
  349. else
  350. NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
  351. DwarfInfoSectionSym);
  352. CUMap.insert(std::make_pair(DIUnit, &NewCU));
  353. CUDieMap.insert(std::make_pair(&Die, &NewCU));
  354. return NewCU;
  355. }
  356. void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
  357. const MDNode *N) {
  358. DIImportedEntity Module(N);
  359. assert(Module.Verify());
  360. if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
  361. D->addChild(TheCU.constructImportedEntityDIE(Module));
  362. }
  363. // Emit all Dwarf sections that should come prior to the content. Create
  364. // global DIEs and emit initial debug info sections. This is invoked by
  365. // the target AsmPrinter.
  366. void DwarfDebug::beginModule() {
  367. if (DisableDebugInfoPrinting)
  368. return;
  369. const Module *M = MMI->getModule();
  370. FunctionDIs = makeSubprogramMap(*M);
  371. NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
  372. if (!CU_Nodes)
  373. return;
  374. TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
  375. // Emit initial sections so we can reference labels later.
  376. emitSectionLabels();
  377. SingleCU = CU_Nodes->getNumOperands() == 1;
  378. for (MDNode *N : CU_Nodes->operands()) {
  379. DICompileUnit CUNode(N);
  380. DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
  381. DIArray ImportedEntities = CUNode.getImportedEntities();
  382. for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
  383. ScopesWithImportedEntities.push_back(std::make_pair(
  384. DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
  385. ImportedEntities.getElement(i)));
  386. std::sort(ScopesWithImportedEntities.begin(),
  387. ScopesWithImportedEntities.end(), less_first());
  388. DIArray GVs = CUNode.getGlobalVariables();
  389. for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
  390. CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
  391. DIArray SPs = CUNode.getSubprograms();
  392. for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
  393. SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
  394. DIArray EnumTypes = CUNode.getEnumTypes();
  395. for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
  396. DIType Ty(EnumTypes.getElement(i));
  397. // The enum types array by design contains pointers to
  398. // MDNodes rather than DIRefs. Unique them here.
  399. DIType UniqueTy(resolve(Ty.getRef()));
  400. CU.getOrCreateTypeDIE(UniqueTy);
  401. }
  402. DIArray RetainedTypes = CUNode.getRetainedTypes();
  403. for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
  404. DIType Ty(RetainedTypes.getElement(i));
  405. // The retained types array by design contains pointers to
  406. // MDNodes rather than DIRefs. Unique them here.
  407. DIType UniqueTy(resolve(Ty.getRef()));
  408. CU.getOrCreateTypeDIE(UniqueTy);
  409. }
  410. // Emit imported_modules last so that the relevant context is already
  411. // available.
  412. for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
  413. constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
  414. }
  415. // Tell MMI that we have debug info.
  416. MMI->setDebugInfoAvailability(true);
  417. // Prime section data.
  418. SectionMap[Asm->getObjFileLowering().getTextSection()];
  419. }
  420. void DwarfDebug::finishVariableDefinitions() {
  421. for (const auto &Var : ConcreteVariables) {
  422. DIE *VariableDie = Var->getDIE();
  423. assert(VariableDie);
  424. // FIXME: Consider the time-space tradeoff of just storing the unit pointer
  425. // in the ConcreteVariables list, rather than looking it up again here.
  426. // DIE::getUnit isn't simple - it walks parent pointers, etc.
  427. DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
  428. assert(Unit);
  429. DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
  430. if (AbsVar && AbsVar->getDIE()) {
  431. Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
  432. *AbsVar->getDIE());
  433. } else
  434. Unit->applyVariableAttributes(*Var, *VariableDie);
  435. }
  436. }
  437. void DwarfDebug::finishSubprogramDefinitions() {
  438. for (const auto &P : SPMap)
  439. forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
  440. CU.finishSubprogramDefinition(DISubprogram(P.first));
  441. });
  442. }
  443. // Collect info for variables that were optimized out.
  444. void DwarfDebug::collectDeadVariables() {
  445. const Module *M = MMI->getModule();
  446. if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
  447. for (MDNode *N : CU_Nodes->operands()) {
  448. DICompileUnit TheCU(N);
  449. // Construct subprogram DIE and add variables DIEs.
  450. DwarfCompileUnit *SPCU =
  451. static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
  452. assert(SPCU && "Unable to find Compile Unit!");
  453. DIArray Subprograms = TheCU.getSubprograms();
  454. for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
  455. DISubprogram SP(Subprograms.getElement(i));
  456. if (ProcessedSPNodes.count(SP) != 0)
  457. continue;
  458. SPCU->collectDeadVariables(SP);
  459. }
  460. }
  461. }
  462. }
  463. void DwarfDebug::finalizeModuleInfo() {
  464. finishSubprogramDefinitions();
  465. finishVariableDefinitions();
  466. // Collect info for variables that were optimized out.
  467. collectDeadVariables();
  468. // Handle anything that needs to be done on a per-unit basis after
  469. // all other generation.
  470. for (const auto &P : CUMap) {
  471. auto &TheCU = *P.second;
  472. // Emit DW_AT_containing_type attribute to connect types with their
  473. // vtable holding type.
  474. TheCU.constructContainingTypeDIEs();
  475. // Add CU specific attributes if we need to add any.
  476. // If we're splitting the dwarf out now that we've got the entire
  477. // CU then add the dwo id to it.
  478. auto *SkCU = TheCU.getSkeleton();
  479. if (useSplitDwarf()) {
  480. // Emit a unique identifier for this CU.
  481. uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
  482. TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
  483. dwarf::DW_FORM_data8, ID);
  484. SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
  485. dwarf::DW_FORM_data8, ID);
  486. // We don't keep track of which addresses are used in which CU so this
  487. // is a bit pessimistic under LTO.
  488. if (!AddrPool.isEmpty())
  489. SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
  490. DwarfAddrSectionSym, DwarfAddrSectionSym);
  491. if (!SkCU->getRangeLists().empty())
  492. SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
  493. DwarfDebugRangeSectionSym,
  494. DwarfDebugRangeSectionSym);
  495. }
  496. // If we have code split among multiple sections or non-contiguous
  497. // ranges of code then emit a DW_AT_ranges attribute on the unit that will
  498. // remain in the .o file, otherwise add a DW_AT_low_pc.
  499. // FIXME: We should use ranges allow reordering of code ala
  500. // .subsections_via_symbols in mach-o. This would mean turning on
  501. // ranges for all subprogram DIEs for mach-o.
  502. DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
  503. if (unsigned NumRanges = TheCU.getRanges().size()) {
  504. if (NumRanges > 1)
  505. // A DW_AT_low_pc attribute may also be specified in combination with
  506. // DW_AT_ranges to specify the default base address for use in
  507. // location lists (see Section 2.6.2) and range lists (see Section
  508. // 2.17.3).
  509. U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
  510. else
  511. TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
  512. U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
  513. }
  514. }
  515. // Compute DIE offsets and sizes.
  516. InfoHolder.computeSizeAndOffsets();
  517. if (useSplitDwarf())
  518. SkeletonHolder.computeSizeAndOffsets();
  519. }
  520. void DwarfDebug::endSections() {
  521. // Filter labels by section.
  522. for (const SymbolCU &SCU : ArangeLabels) {
  523. if (SCU.Sym->isInSection()) {
  524. // Make a note of this symbol and it's section.
  525. const MCSection *Section = &SCU.Sym->getSection();
  526. if (!Section->getKind().isMetadata())
  527. SectionMap[Section].push_back(SCU);
  528. } else {
  529. // Some symbols (e.g. common/bss on mach-o) can have no section but still
  530. // appear in the output. This sucks as we rely on sections to build
  531. // arange spans. We can do it without, but it's icky.
  532. SectionMap[nullptr].push_back(SCU);
  533. }
  534. }
  535. // Build a list of sections used.
  536. std::vector<const MCSection *> Sections;
  537. for (const auto &it : SectionMap) {
  538. const MCSection *Section = it.first;
  539. Sections.push_back(Section);
  540. }
  541. // Sort the sections into order.
  542. // This is only done to ensure consistent output order across different runs.
  543. std::sort(Sections.begin(), Sections.end(), SectionSort);
  544. // Add terminating symbols for each section.
  545. for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
  546. const MCSection *Section = Sections[ID];
  547. MCSymbol *Sym = nullptr;
  548. if (Section) {
  549. // We can't call MCSection::getLabelEndName, as it's only safe to do so
  550. // if we know the section name up-front. For user-created sections, the
  551. // resulting label may not be valid to use as a label. (section names can
  552. // use a greater set of characters on some systems)
  553. Sym = Asm->GetTempSymbol("debug_end", ID);
  554. Asm->OutStreamer.SwitchSection(Section);
  555. Asm->OutStreamer.EmitLabel(Sym);
  556. }
  557. // Insert a final terminator.
  558. SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
  559. }
  560. }
  561. // Emit all Dwarf sections that should come after the content.
  562. void DwarfDebug::endModule() {
  563. assert(CurFn == nullptr);
  564. assert(CurMI == nullptr);
  565. // If we aren't actually generating debug info (check beginModule -
  566. // conditionalized on !DisableDebugInfoPrinting and the presence of the
  567. // llvm.dbg.cu metadata node)
  568. if (!DwarfInfoSectionSym)
  569. return;
  570. // End any existing sections.
  571. // TODO: Does this need to happen?
  572. endSections();
  573. // Finalize the debug info for the module.
  574. finalizeModuleInfo();
  575. emitDebugStr();
  576. // Emit all the DIEs into a debug info section.
  577. emitDebugInfo();
  578. // Corresponding abbreviations into a abbrev section.
  579. emitAbbreviations();
  580. // Emit info into a debug aranges section.
  581. if (GenerateARangeSection)
  582. emitDebugARanges();
  583. // Emit info into a debug ranges section.
  584. emitDebugRanges();
  585. if (useSplitDwarf()) {
  586. emitDebugStrDWO();
  587. emitDebugInfoDWO();
  588. emitDebugAbbrevDWO();
  589. emitDebugLineDWO();
  590. emitDebugLocDWO();
  591. // Emit DWO addresses.
  592. AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
  593. } else
  594. // Emit info into a debug loc section.
  595. emitDebugLoc();
  596. // Emit info into the dwarf accelerator table sections.
  597. if (useDwarfAccelTables()) {
  598. emitAccelNames();
  599. emitAccelObjC();
  600. emitAccelNamespaces();
  601. emitAccelTypes();
  602. }
  603. // Emit the pubnames and pubtypes sections if requested.
  604. if (HasDwarfPubSections) {
  605. emitDebugPubNames(GenerateGnuPubSections);
  606. emitDebugPubTypes(GenerateGnuPubSections);
  607. }
  608. // clean up.
  609. SPMap.clear();
  610. AbstractVariables.clear();
  611. }
  612. // Find abstract variable, if any, associated with Var.
  613. DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
  614. DIVariable &Cleansed) {
  615. LLVMContext &Ctx = DV->getContext();
  616. // More then one inlined variable corresponds to one abstract variable.
  617. // FIXME: This duplication of variables when inlining should probably be
  618. // removed. It's done to allow each DIVariable to describe its location
  619. // because the DebugLoc on the dbg.value/declare isn't accurate. We should
  620. // make it accurate then remove this duplication/cleansing stuff.
  621. Cleansed = cleanseInlinedVariable(DV, Ctx);
  622. auto I = AbstractVariables.find(Cleansed);
  623. if (I != AbstractVariables.end())
  624. return I->second.get();
  625. return nullptr;
  626. }
  627. DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
  628. DIVariable Cleansed;
  629. return getExistingAbstractVariable(DV, Cleansed);
  630. }
  631. void DwarfDebug::createAbstractVariable(const DIVariable &Var,
  632. LexicalScope *Scope) {
  633. auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
  634. InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
  635. AbstractVariables[Var] = std::move(AbsDbgVariable);
  636. }
  637. void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
  638. const MDNode *ScopeNode) {
  639. DIVariable Cleansed = DV;
  640. if (getExistingAbstractVariable(DV, Cleansed))
  641. return;
  642. createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
  643. }
  644. void
  645. DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
  646. const MDNode *ScopeNode) {
  647. DIVariable Cleansed = DV;
  648. if (getExistingAbstractVariable(DV, Cleansed))
  649. return;
  650. if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
  651. createAbstractVariable(Cleansed, Scope);
  652. }
  653. // Collect variable information from side table maintained by MMI.
  654. void DwarfDebug::collectVariableInfoFromMMITable(
  655. SmallPtrSetImpl<const MDNode *> &Processed) {
  656. for (const auto &VI : MMI->getVariableDbgInfo()) {
  657. if (!VI.Var)
  658. continue;
  659. Processed.insert(VI.Var);
  660. LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
  661. // If variable scope is not found then skip this variable.
  662. if (!Scope)
  663. continue;
  664. DIVariable DV(VI.Var);
  665. DIExpression Expr(VI.Expr);
  666. ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
  667. ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
  668. DbgVariable *RegVar = ConcreteVariables.back().get();
  669. RegVar->setFrameIndex(VI.Slot);
  670. InfoHolder.addScopeVariable(Scope, RegVar);
  671. }
  672. }
  673. // Get .debug_loc entry for the instruction range starting at MI.
  674. static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
  675. const MDNode *Expr = MI->getDebugExpression();
  676. const MDNode *Var = MI->getDebugVariable();
  677. assert(MI->getNumOperands() == 4);
  678. if (MI->getOperand(0).isReg()) {
  679. MachineLocation MLoc;
  680. // If the second operand is an immediate, this is a
  681. // register-indirect address.
  682. if (!MI->getOperand(1).isImm())
  683. MLoc.set(MI->getOperand(0).getReg());
  684. else
  685. MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
  686. return DebugLocEntry::Value(Var, Expr, MLoc);
  687. }
  688. if (MI->getOperand(0).isImm())
  689. return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
  690. if (MI->getOperand(0).isFPImm())
  691. return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
  692. if (MI->getOperand(0).isCImm())
  693. return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
  694. llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
  695. }
  696. /// Determine whether two variable pieces overlap.
  697. static bool piecesOverlap(DIExpression P1, DIExpression P2) {
  698. if (!P1.isVariablePiece() || !P2.isVariablePiece())
  699. return true;
  700. unsigned l1 = P1.getPieceOffset();
  701. unsigned l2 = P2.getPieceOffset();
  702. unsigned r1 = l1 + P1.getPieceSize();
  703. unsigned r2 = l2 + P2.getPieceSize();
  704. // True where [l1,r1[ and [r1,r2[ overlap.
  705. return (l1 < r2) && (l2 < r1);
  706. }
  707. /// Build the location list for all DBG_VALUEs in the function that
  708. /// describe the same variable. If the ranges of several independent
  709. /// pieces of the same variable overlap partially, split them up and
  710. /// combine the ranges. The resulting DebugLocEntries are will have
  711. /// strict monotonically increasing begin addresses and will never
  712. /// overlap.
  713. //
  714. // Input:
  715. //
  716. // Ranges History [var, loc, piece ofs size]
  717. // 0 | [x, (reg0, piece 0, 32)]
  718. // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
  719. // 2 | | ...
  720. // 3 | [clobber reg0]
  721. // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
  722. //
  723. // Output:
  724. //
  725. // [0-1] [x, (reg0, piece 0, 32)]
  726. // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
  727. // [3-4] [x, (reg1, piece 32, 32)]
  728. // [4- ] [x, (mem, piece 0, 64)]
  729. void
  730. DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
  731. const DbgValueHistoryMap::InstrRanges &Ranges) {
  732. SmallVector<DebugLocEntry::Value, 4> OpenRanges;
  733. for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
  734. const MachineInstr *Begin = I->first;
  735. const MachineInstr *End = I->second;
  736. assert(Begin->isDebugValue() && "Invalid History entry");
  737. // Check if a variable is inaccessible in this range.
  738. if (Begin->getNumOperands() > 1 &&
  739. Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
  740. OpenRanges.clear();
  741. continue;
  742. }
  743. // If this piece overlaps with any open ranges, truncate them.
  744. DIExpression DIExpr = Begin->getDebugExpression();
  745. auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
  746. [&](DebugLocEntry::Value R) {
  747. return piecesOverlap(DIExpr, R.getExpression());
  748. });
  749. OpenRanges.erase(Last, OpenRanges.end());
  750. const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
  751. assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
  752. const MCSymbol *EndLabel;
  753. if (End != nullptr)
  754. EndLabel = getLabelAfterInsn(End);
  755. else if (std::next(I) == Ranges.end())
  756. EndLabel = FunctionEndSym;
  757. else
  758. EndLabel = getLabelBeforeInsn(std::next(I)->first);
  759. assert(EndLabel && "Forgot label after instruction ending a range!");
  760. DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
  761. auto Value = getDebugLocValue(Begin);
  762. DebugLocEntry Loc(StartLabel, EndLabel, Value);
  763. bool couldMerge = false;
  764. // If this is a piece, it may belong to the current DebugLocEntry.
  765. if (DIExpr.isVariablePiece()) {
  766. // Add this value to the list of open ranges.
  767. OpenRanges.push_back(Value);
  768. // Attempt to add the piece to the last entry.
  769. if (!DebugLoc.empty())
  770. if (DebugLoc.back().MergeValues(Loc))
  771. couldMerge = true;
  772. }
  773. if (!couldMerge) {
  774. // Need to add a new DebugLocEntry. Add all values from still
  775. // valid non-overlapping pieces.
  776. if (OpenRanges.size())
  777. Loc.addValues(OpenRanges);
  778. DebugLoc.push_back(std::move(Loc));
  779. }
  780. // Attempt to coalesce the ranges of two otherwise identical
  781. // DebugLocEntries.
  782. auto CurEntry = DebugLoc.rbegin();
  783. auto PrevEntry = std::next(CurEntry);
  784. if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
  785. DebugLoc.pop_back();
  786. DEBUG({
  787. dbgs() << CurEntry->getValues().size() << " Values:\n";
  788. for (auto Value : CurEntry->getValues()) {
  789. Value.getVariable()->dump();
  790. Value.getExpression()->dump();
  791. }
  792. dbgs() << "-----\n";
  793. });
  794. }
  795. }
  796. // Find variables for each lexical scope.
  797. void
  798. DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
  799. SmallPtrSetImpl<const MDNode *> &Processed) {
  800. // Grab the variable info that was squirreled away in the MMI side-table.
  801. collectVariableInfoFromMMITable(Processed);
  802. for (const auto &I : DbgValues) {
  803. DIVariable DV(I.first);
  804. if (Processed.count(DV))
  805. continue;
  806. // Instruction ranges, specifying where DV is accessible.
  807. const auto &Ranges = I.second;
  808. if (Ranges.empty())
  809. continue;
  810. LexicalScope *Scope = nullptr;
  811. if (MDNode *IA = DV.getInlinedAt()) {
  812. DebugLoc DL = DebugLoc::getFromDILocation(IA);
  813. Scope = LScopes.findInlinedScope(DebugLoc::get(
  814. DL.getLine(), DL.getCol(), DV.getContext(), IA));
  815. } else
  816. Scope = LScopes.findLexicalScope(DV.getContext());
  817. // If variable scope is not found then skip this variable.
  818. if (!Scope)
  819. continue;
  820. Processed.insert(DV);
  821. const MachineInstr *MInsn = Ranges.front().first;
  822. assert(MInsn->isDebugValue() && "History must begin with debug value");
  823. ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
  824. ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
  825. DbgVariable *RegVar = ConcreteVariables.back().get();
  826. InfoHolder.addScopeVariable(Scope, RegVar);
  827. // Check if the first DBG_VALUE is valid for the rest of the function.
  828. if (Ranges.size() == 1 && Ranges.front().second == nullptr)
  829. continue;
  830. // Handle multiple DBG_VALUE instructions describing one variable.
  831. RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
  832. DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
  833. DebugLocList &LocList = DotDebugLocEntries.back();
  834. LocList.CU = &TheCU;
  835. LocList.Label =
  836. Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
  837. // Build the location list for this variable.
  838. buildLocationList(LocList.List, Ranges);
  839. }
  840. // Collect info for variables that were optimized out.
  841. DIArray Variables = SP.getVariables();
  842. for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
  843. DIVariable DV(Variables.getElement(i));
  844. assert(DV.isVariable());
  845. if (!Processed.insert(DV).second)
  846. continue;
  847. if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
  848. ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
  849. DIExpression NoExpr;
  850. ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
  851. InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
  852. }
  853. }
  854. }
  855. // Return Label preceding the instruction.
  856. MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
  857. MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
  858. assert(Label && "Didn't insert label before instruction");
  859. return Label;
  860. }
  861. // Return Label immediately following the instruction.
  862. MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
  863. return LabelsAfterInsn.lookup(MI);
  864. }
  865. // Process beginning of an instruction.
  866. void DwarfDebug::beginInstruction(const MachineInstr *MI) {
  867. assert(CurMI == nullptr);
  868. CurMI = MI;
  869. // Check if source location changes, but ignore DBG_VALUE locations.
  870. if (!MI->isDebugValue()) {
  871. DebugLoc DL = MI->getDebugLoc();
  872. if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
  873. unsigned Flags = 0;
  874. PrevInstLoc = DL;
  875. if (DL == PrologEndLoc) {
  876. Flags |= DWARF2_FLAG_PROLOGUE_END;
  877. PrologEndLoc = DebugLoc();
  878. Flags |= DWARF2_FLAG_IS_STMT;
  879. }
  880. if (DL.getLine() !=
  881. Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
  882. Flags |= DWARF2_FLAG_IS_STMT;
  883. if (!DL.isUnknown()) {
  884. const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
  885. recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
  886. } else
  887. recordSourceLine(0, 0, nullptr, 0);
  888. }
  889. }
  890. // Insert labels where requested.
  891. DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
  892. LabelsBeforeInsn.find(MI);
  893. // No label needed.
  894. if (I == LabelsBeforeInsn.end())
  895. return;
  896. // Label already assigned.
  897. if (I->second)
  898. return;
  899. if (!PrevLabel) {
  900. PrevLabel = MMI->getContext().CreateTempSymbol();
  901. Asm->OutStreamer.EmitLabel(PrevLabel);
  902. }
  903. I->second = PrevLabel;
  904. }
  905. // Process end of an instruction.
  906. void DwarfDebug::endInstruction() {
  907. assert(CurMI != nullptr);
  908. // Don't create a new label after DBG_VALUE instructions.
  909. // They don't generate code.
  910. if (!CurMI->isDebugValue())
  911. PrevLabel = nullptr;
  912. DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
  913. LabelsAfterInsn.find(CurMI);
  914. CurMI = nullptr;
  915. // No label needed.
  916. if (I == LabelsAfterInsn.end())
  917. return;
  918. // Label already assigned.
  919. if (I->second)
  920. return;
  921. // We need a label after this instruction.
  922. if (!PrevLabel) {
  923. PrevLabel = MMI->getContext().CreateTempSymbol();
  924. Asm->OutStreamer.EmitLabel(PrevLabel);
  925. }
  926. I->second = PrevLabel;
  927. }
  928. // Each LexicalScope has first instruction and last instruction to mark
  929. // beginning and end of a scope respectively. Create an inverse map that list
  930. // scopes starts (and ends) with an instruction. One instruction may start (or
  931. // end) multiple scopes. Ignore scopes that are not reachable.
  932. void DwarfDebug::identifyScopeMarkers() {
  933. SmallVector<LexicalScope *, 4> WorkList;
  934. WorkList.push_back(LScopes.getCurrentFunctionScope());
  935. while (!WorkList.empty()) {
  936. LexicalScope *S = WorkList.pop_back_val();
  937. const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
  938. if (!Children.empty())
  939. WorkList.append(Children.begin(), Children.end());
  940. if (S->isAbstractScope())
  941. continue;
  942. for (const InsnRange &R : S->getRanges()) {
  943. assert(R.first && "InsnRange does not have first instruction!");
  944. assert(R.second && "InsnRange does not have second instruction!");
  945. requestLabelBeforeInsn(R.first);
  946. requestLabelAfterInsn(R.second);
  947. }
  948. }
  949. }
  950. static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
  951. // First known non-DBG_VALUE and non-frame setup location marks
  952. // the beginning of the function body.
  953. for (const auto &MBB : *MF)
  954. for (const auto &MI : MBB)
  955. if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
  956. !MI.getDebugLoc().isUnknown()) {
  957. // Did the target forget to set the FrameSetup flag for CFI insns?
  958. assert(!MI.isCFIInstruction() &&
  959. "First non-frame-setup instruction is a CFI instruction.");
  960. return MI.getDebugLoc();
  961. }
  962. return DebugLoc();
  963. }
  964. // Gather pre-function debug information. Assumes being called immediately
  965. // after the function entry point has been emitted.
  966. void DwarfDebug::beginFunction(const MachineFunction *MF) {
  967. CurFn = MF;
  968. // If there's no debug info for the function we're not going to do anything.
  969. if (!MMI->hasDebugInfo())
  970. return;
  971. auto DI = FunctionDIs.find(MF->getFunction());
  972. if (DI == FunctionDIs.end())
  973. return;
  974. // Grab the lexical scopes for the function, if we don't have any of those
  975. // then we're not going to be able to do anything.
  976. LScopes.initialize(*MF);
  977. if (LScopes.empty())
  978. return;
  979. assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
  980. // Make sure that each lexical scope will have a begin/end label.
  981. identifyScopeMarkers();
  982. // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
  983. // belongs to so that we add to the correct per-cu line table in the
  984. // non-asm case.
  985. LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
  986. // FnScope->getScopeNode() and DI->second should represent the same function,
  987. // though they may not be the same MDNode due to inline functions merged in
  988. // LTO where the debug info metadata still differs (either due to distinct
  989. // written differences - two versions of a linkonce_odr function
  990. // written/copied into two separate files, or some sub-optimal metadata that
  991. // isn't structurally identical (see: file path/name info from clang, which
  992. // includes the directory of the cpp file being built, even when the file name
  993. // is absolute (such as an <> lookup header)))
  994. DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
  995. assert(TheCU && "Unable to find compile unit!");
  996. if (Asm->OutStreamer.hasRawTextSupport())
  997. // Use a single line table if we are generating assembly.
  998. Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
  999. else
  1000. Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
  1001. // Emit a label for the function so that we have a beginning address.
  1002. FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
  1003. // Assumes in correct section after the entry point.
  1004. Asm->OutStreamer.EmitLabel(FunctionBeginSym);
  1005. // Calculate history for local variables.
  1006. calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
  1007. DbgValues);
  1008. // Request labels for the full history.
  1009. for (const auto &I : DbgValues) {
  1010. const auto &Ranges = I.second;
  1011. if (Ranges.empty())
  1012. continue;
  1013. // The first mention of a function argument gets the FunctionBeginSym
  1014. // label, so arguments are visible when breaking at function entry.
  1015. DIVariable DIVar(Ranges.front().first->getDebugVariable());
  1016. if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
  1017. getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
  1018. LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
  1019. if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
  1020. // Mark all non-overlapping initial pieces.
  1021. for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
  1022. DIExpression Piece = I->first->getDebugExpression();
  1023. if (std::all_of(Ranges.begin(), I,
  1024. [&](DbgValueHistoryMap::InstrRange Pred) {
  1025. return !piecesOverlap(Piece, Pred.first->getDebugExpression());
  1026. }))
  1027. LabelsBeforeInsn[I->first] = FunctionBeginSym;
  1028. else
  1029. break;
  1030. }
  1031. }
  1032. }
  1033. for (const auto &Range : Ranges) {
  1034. requestLabelBeforeInsn(Range.first);
  1035. if (Range.second)
  1036. requestLabelAfterInsn(Range.second);
  1037. }
  1038. }
  1039. PrevInstLoc = DebugLoc();
  1040. PrevLabel = FunctionBeginSym;
  1041. // Record beginning of function.
  1042. PrologEndLoc = findPrologueEndLoc(MF);
  1043. if (!PrologEndLoc.isUnknown()) {
  1044. DebugLoc FnStartDL =
  1045. PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
  1046. recordSourceLine(
  1047. FnStartDL.getLine(), FnStartDL.getCol(),
  1048. FnStartDL.getScope(MF->getFunction()->getContext()),
  1049. // We'd like to list the prologue as "not statements" but GDB behaves
  1050. // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
  1051. DWARF2_FLAG_IS_STMT);
  1052. }
  1053. }
  1054. // Gather and emit post-function debug information.
  1055. void DwarfDebug::endFunction(const MachineFunction *MF) {
  1056. assert(CurFn == MF &&
  1057. "endFunction should be called with the same function as beginFunction");
  1058. if (!MMI->hasDebugInfo() || LScopes.empty() ||
  1059. !FunctionDIs.count(MF->getFunction())) {
  1060. // If we don't have a lexical scope for this function then there will
  1061. // be a hole in the range information. Keep note of this by setting the
  1062. // previously used section to nullptr.
  1063. PrevCU = nullptr;
  1064. CurFn = nullptr;
  1065. return;
  1066. }
  1067. // Define end label for subprogram.
  1068. FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
  1069. // Assumes in correct section after the entry point.
  1070. Asm->OutStreamer.EmitLabel(FunctionEndSym);
  1071. // Set DwarfDwarfCompileUnitID in MCContext to default value.
  1072. Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
  1073. LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
  1074. DISubprogram SP(FnScope->getScopeNode());
  1075. DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
  1076. SmallPtrSet<const MDNode *, 16> ProcessedVars;
  1077. collectVariableInfo(TheCU, SP, ProcessedVars);
  1078. // Add the range of this function to the list of ranges for the CU.
  1079. TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
  1080. // Under -gmlt, skip building the subprogram if there are no inlined
  1081. // subroutines inside it.
  1082. if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
  1083. LScopes.getAbstractScopesList().empty() && !IsDarwin) {
  1084. assert(InfoHolder.getScopeVariables().empty());
  1085. assert(DbgValues.empty());
  1086. // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
  1087. // by a -gmlt CU. Add a test and remove this assertion.
  1088. assert(AbstractVariables.empty());
  1089. LabelsBeforeInsn.clear();
  1090. LabelsAfterInsn.clear();
  1091. PrevLabel = nullptr;
  1092. CurFn = nullptr;
  1093. return;
  1094. }
  1095. #ifndef NDEBUG
  1096. size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
  1097. #endif
  1098. // Construct abstract scopes.
  1099. for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
  1100. DISubprogram SP(AScope->getScopeNode());
  1101. assert(SP.isSubprogram());
  1102. // Collect info for variables that were optimized out.
  1103. DIArray Variables = SP.getVariables();
  1104. for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
  1105. DIVariable DV(Variables.getElement(i));
  1106. assert(DV && DV.isVariable());
  1107. if (!ProcessedVars.insert(DV).second)
  1108. continue;
  1109. ensureAbstractVariableIsCreated(DV, DV.getContext());
  1110. assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
  1111. && "ensureAbstractVariableIsCreated inserted abstract scopes");
  1112. }
  1113. constructAbstractSubprogramScopeDIE(AScope);
  1114. }
  1115. TheCU.constructSubprogramScopeDIE(FnScope);
  1116. if (auto *SkelCU = TheCU.getSkeleton())
  1117. if (!LScopes.getAbstractScopesList().empty())
  1118. SkelCU->constructSubprogramScopeDIE(FnScope);
  1119. // Clear debug info
  1120. // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
  1121. // DbgVariables except those that are also in AbstractVariables (since they
  1122. // can be used cross-function)
  1123. InfoHolder.getScopeVariables().clear();
  1124. DbgValues.clear();
  1125. LabelsBeforeInsn.clear();
  1126. LabelsAfterInsn.clear();
  1127. PrevLabel = nullptr;
  1128. CurFn = nullptr;
  1129. }
  1130. // Register a source line with debug info. Returns the unique label that was
  1131. // emitted and which provides correspondence to the source line list.
  1132. void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
  1133. unsigned Flags) {
  1134. StringRef Fn;
  1135. StringRef Dir;
  1136. unsigned Src = 1;
  1137. unsigned Discriminator = 0;
  1138. if (DIScope Scope = DIScope(S)) {
  1139. assert(Scope.isScope());
  1140. Fn = Scope.getFilename();
  1141. Dir = Scope.getDirectory();
  1142. if (Scope.isLexicalBlockFile())
  1143. Discriminator = DILexicalBlockFile(S).getDiscriminator();
  1144. unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
  1145. Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
  1146. .getOrCreateSourceID(Fn, Dir);
  1147. }
  1148. Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
  1149. Discriminator, Fn);
  1150. }
  1151. //===----------------------------------------------------------------------===//
  1152. // Emit Methods
  1153. //===----------------------------------------------------------------------===//
  1154. // Emit initial Dwarf sections with a label at the start of each one.
  1155. void DwarfDebug::emitSectionLabels() {
  1156. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  1157. // Dwarf sections base addresses.
  1158. DwarfInfoSectionSym =
  1159. emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
  1160. if (useSplitDwarf()) {
  1161. DwarfInfoDWOSectionSym =
  1162. emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
  1163. DwarfTypesDWOSectionSym =
  1164. emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
  1165. }
  1166. DwarfAbbrevSectionSym =
  1167. emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
  1168. if (useSplitDwarf())
  1169. DwarfAbbrevDWOSectionSym = emitSectionSym(
  1170. Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
  1171. if (GenerateARangeSection)
  1172. emitSectionSym(Asm, TLOF.getDwarfARangesSection());
  1173. DwarfLineSectionSym =
  1174. emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
  1175. if (GenerateGnuPubSections) {
  1176. DwarfGnuPubNamesSectionSym =
  1177. emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
  1178. DwarfGnuPubTypesSectionSym =
  1179. emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
  1180. } else if (HasDwarfPubSections) {
  1181. emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
  1182. emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
  1183. }
  1184. DwarfStrSectionSym =
  1185. emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
  1186. if (useSplitDwarf()) {
  1187. DwarfStrDWOSectionSym =
  1188. emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
  1189. DwarfAddrSectionSym =
  1190. emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
  1191. DwarfDebugLocSectionSym =
  1192. emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
  1193. } else
  1194. DwarfDebugLocSectionSym =
  1195. emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
  1196. DwarfDebugRangeSectionSym =
  1197. emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
  1198. }
  1199. // Recursively emits a debug information entry.
  1200. void DwarfDebug::emitDIE(DIE &Die) {
  1201. // Get the abbreviation for this DIE.
  1202. const DIEAbbrev &Abbrev = Die.getAbbrev();
  1203. // Emit the code (index) for the abbreviation.
  1204. if (Asm->isVerbose())
  1205. Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
  1206. "] 0x" + Twine::utohexstr(Die.getOffset()) +
  1207. ":0x" + Twine::utohexstr(Die.getSize()) + " " +
  1208. dwarf::TagString(Abbrev.getTag()));
  1209. Asm->EmitULEB128(Abbrev.getNumber());
  1210. const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
  1211. const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
  1212. // Emit the DIE attribute values.
  1213. for (unsigned i = 0, N = Values.size(); i < N; ++i) {
  1214. dwarf::Attribute Attr = AbbrevData[i].getAttribute();
  1215. dwarf::Form Form = AbbrevData[i].getForm();
  1216. assert(Form && "Too many attributes for DIE (check abbreviation)");
  1217. if (Asm->isVerbose()) {
  1218. Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
  1219. if (Attr == dwarf::DW_AT_accessibility)
  1220. Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
  1221. cast<DIEInteger>(Values[i])->getValue()));
  1222. }
  1223. // Emit an attribute using the defined form.
  1224. Values[i]->EmitValue(Asm, Form);
  1225. }
  1226. // Emit the DIE children if any.
  1227. if (Abbrev.hasChildren()) {
  1228. for (auto &Child : Die.getChildren())
  1229. emitDIE(*Child);
  1230. Asm->OutStreamer.AddComment("End Of Children Mark");
  1231. Asm->EmitInt8(0);
  1232. }
  1233. }
  1234. // Emit the debug info section.
  1235. void DwarfDebug::emitDebugInfo() {
  1236. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1237. Holder.emitUnits(DwarfAbbrevSectionSym);
  1238. }
  1239. // Emit the abbreviation section.
  1240. void DwarfDebug::emitAbbreviations() {
  1241. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1242. Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
  1243. }
  1244. // Emit the last address of the section and the end of the line matrix.
  1245. void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
  1246. // Define last address of section.
  1247. Asm->OutStreamer.AddComment("Extended Op");
  1248. Asm->EmitInt8(0);
  1249. Asm->OutStreamer.AddComment("Op size");
  1250. Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
  1251. Asm->OutStreamer.AddComment("DW_LNE_set_address");
  1252. Asm->EmitInt8(dwarf::DW_LNE_set_address);
  1253. Asm->OutStreamer.AddComment("Section end label");
  1254. Asm->OutStreamer.EmitSymbolValue(
  1255. Asm->GetTempSymbol("section_end", SectionEnd),
  1256. Asm->getDataLayout().getPointerSize());
  1257. // Mark end of matrix.
  1258. Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
  1259. Asm->EmitInt8(0);
  1260. Asm->EmitInt8(1);
  1261. Asm->EmitInt8(1);
  1262. }
  1263. void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
  1264. StringRef TableName, StringRef SymName) {
  1265. Accel.FinalizeTable(Asm, TableName);
  1266. Asm->OutStreamer.SwitchSection(Section);
  1267. auto *SectionBegin = Asm->GetTempSymbol(SymName);
  1268. Asm->OutStreamer.EmitLabel(SectionBegin);
  1269. // Emit the full data.
  1270. Accel.Emit(Asm, SectionBegin, this, DwarfStrSectionSym);
  1271. }
  1272. // Emit visible names into a hashed accelerator table section.
  1273. void DwarfDebug::emitAccelNames() {
  1274. emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
  1275. "Names", "names_begin");
  1276. }
  1277. // Emit objective C classes and categories into a hashed accelerator table
  1278. // section.
  1279. void DwarfDebug::emitAccelObjC() {
  1280. emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
  1281. "ObjC", "objc_begin");
  1282. }
  1283. // Emit namespace dies into a hashed accelerator table.
  1284. void DwarfDebug::emitAccelNamespaces() {
  1285. emitAccel(AccelNamespace,
  1286. Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
  1287. "namespac", "namespac_begin");
  1288. }
  1289. // Emit type dies into a hashed accelerator table.
  1290. void DwarfDebug::emitAccelTypes() {
  1291. emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
  1292. "types", "types_begin");
  1293. }
  1294. // Public name handling.
  1295. // The format for the various pubnames:
  1296. //
  1297. // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
  1298. // for the DIE that is named.
  1299. //
  1300. // gnu pubnames - offset/index value/name tuples where the offset is the offset
  1301. // into the CU and the index value is computed according to the type of value
  1302. // for the DIE that is named.
  1303. //
  1304. // For type units the offset is the offset of the skeleton DIE. For split dwarf
  1305. // it's the offset within the debug_info/debug_types dwo section, however, the
  1306. // reference in the pubname header doesn't change.
  1307. /// computeIndexValue - Compute the gdb index value for the DIE and CU.
  1308. static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
  1309. const DIE *Die) {
  1310. dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
  1311. // We could have a specification DIE that has our most of our knowledge,
  1312. // look for that now.
  1313. DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
  1314. if (SpecVal) {
  1315. DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
  1316. if (SpecDIE.findAttribute(dwarf::DW_AT_external))
  1317. Linkage = dwarf::GIEL_EXTERNAL;
  1318. } else if (Die->findAttribute(dwarf::DW_AT_external))
  1319. Linkage = dwarf::GIEL_EXTERNAL;
  1320. switch (Die->getTag()) {
  1321. case dwarf::DW_TAG_class_type:
  1322. case dwarf::DW_TAG_structure_type:
  1323. case dwarf::DW_TAG_union_type:
  1324. case dwarf::DW_TAG_enumeration_type:
  1325. return dwarf::PubIndexEntryDescriptor(
  1326. dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
  1327. ? dwarf::GIEL_STATIC
  1328. : dwarf::GIEL_EXTERNAL);
  1329. case dwarf::DW_TAG_typedef:
  1330. case dwarf::DW_TAG_base_type:
  1331. case dwarf::DW_TAG_subrange_type:
  1332. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
  1333. case dwarf::DW_TAG_namespace:
  1334. return dwarf::GIEK_TYPE;
  1335. case dwarf::DW_TAG_subprogram:
  1336. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
  1337. case dwarf::DW_TAG_constant:
  1338. case dwarf::DW_TAG_variable:
  1339. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
  1340. case dwarf::DW_TAG_enumerator:
  1341. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
  1342. dwarf::GIEL_STATIC);
  1343. default:
  1344. return dwarf::GIEK_NONE;
  1345. }
  1346. }
  1347. /// emitDebugPubNames - Emit visible names into a debug pubnames section.
  1348. ///
  1349. void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
  1350. const MCSection *PSec =
  1351. GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
  1352. : Asm->getObjFileLowering().getDwarfPubNamesSection();
  1353. emitDebugPubSection(GnuStyle, PSec, "Names",
  1354. &DwarfCompileUnit::getGlobalNames);
  1355. }
  1356. void DwarfDebug::emitDebugPubSection(
  1357. bool GnuStyle, const MCSection *PSec, StringRef Name,
  1358. const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
  1359. for (const auto &NU : CUMap) {
  1360. DwarfCompileUnit *TheU = NU.second;
  1361. const auto &Globals = (TheU->*Accessor)();
  1362. if (Globals.empty())
  1363. continue;
  1364. if (auto *Skeleton = TheU->getSkeleton())
  1365. TheU = Skeleton;
  1366. unsigned ID = TheU->getUniqueID();
  1367. // Start the dwarf pubnames section.
  1368. Asm->OutStreamer.SwitchSection(PSec);
  1369. // Emit the header.
  1370. Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
  1371. MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
  1372. MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
  1373. Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
  1374. Asm->OutStreamer.EmitLabel(BeginLabel);
  1375. Asm->OutStreamer.AddComment("DWARF Version");
  1376. Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
  1377. Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
  1378. Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
  1379. Asm->OutStreamer.AddComment("Compilation Unit Length");
  1380. Asm->EmitInt32(TheU->getLength());
  1381. // Emit the pubnames for this compilation unit.
  1382. for (const auto &GI : Globals) {
  1383. const char *Name = GI.getKeyData();
  1384. const DIE *Entity = GI.second;
  1385. Asm->OutStreamer.AddComment("DIE offset");
  1386. Asm->EmitInt32(Entity->getOffset());
  1387. if (GnuStyle) {
  1388. dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
  1389. Asm->OutStreamer.AddComment(
  1390. Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
  1391. dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
  1392. Asm->EmitInt8(Desc.toBits());
  1393. }
  1394. Asm->OutStreamer.AddComment("External Name");
  1395. Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
  1396. }
  1397. Asm->OutStreamer.AddComment("End Mark");
  1398. Asm->EmitInt32(0);
  1399. Asm->OutStreamer.EmitLabel(EndLabel);
  1400. }
  1401. }
  1402. void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
  1403. const MCSection *PSec =
  1404. GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
  1405. : Asm->getObjFileLowering().getDwarfPubTypesSection();
  1406. emitDebugPubSection(GnuStyle, PSec, "Types",
  1407. &DwarfCompileUnit::getGlobalTypes);
  1408. }
  1409. // Emit visible names into a debug str section.
  1410. void DwarfDebug::emitDebugStr() {
  1411. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1412. Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
  1413. }
  1414. /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
  1415. void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
  1416. const DITypeIdentifierMap &Map,
  1417. ArrayRef<DebugLocEntry::Value> Values) {
  1418. assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
  1419. return P.isVariablePiece();
  1420. }) && "all values are expected to be pieces");
  1421. assert(std::is_sorted(Values.begin(), Values.end()) &&
  1422. "pieces are expected to be sorted");
  1423. unsigned Offset = 0;
  1424. for (auto Piece : Values) {
  1425. const unsigned SizeOfByte = 8;
  1426. DIExpression Expr = Piece.getExpression();
  1427. unsigned PieceOffset = Expr.getPieceOffset();
  1428. unsigned PieceSize = Expr.getPieceSize();
  1429. assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
  1430. if (Offset < PieceOffset) {
  1431. // The DWARF spec seriously mandates pieces with no locations for gaps.
  1432. Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*SizeOfByte);
  1433. Offset += PieceOffset-Offset;
  1434. }
  1435. Offset += PieceSize;
  1436. #ifndef NDEBUG
  1437. DIVariable Var = Piece.getVariable();
  1438. assert(!Var.isIndirect() && "indirect address for piece");
  1439. unsigned VarSize = Var.getSizeInBits(Map);
  1440. assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
  1441. && "piece is larger than or outside of variable");
  1442. assert(PieceSize*SizeOfByte != VarSize
  1443. && "piece covers entire variable");
  1444. #endif
  1445. emitDebugLocValue(Streamer, Piece, PieceOffset*SizeOfByte);
  1446. }
  1447. }
  1448. void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
  1449. const DebugLocEntry &Entry) {
  1450. const DebugLocEntry::Value Value = Entry.getValues()[0];
  1451. if (Value.isVariablePiece())
  1452. // Emit all pieces that belong to the same variable and range.
  1453. return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
  1454. assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
  1455. emitDebugLocValue(Streamer, Value);
  1456. }
  1457. void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
  1458. const DebugLocEntry::Value &Value,
  1459. unsigned PieceOffsetInBits) {
  1460. DIVariable DV = Value.getVariable();
  1461. DebugLocDwarfExpression DwarfExpr(*Asm, Streamer);
  1462. // Regular entry.
  1463. if (Value.isInt()) {
  1464. DIBasicType BTy(resolve(DV.getType()));
  1465. if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
  1466. BTy.getEncoding() == dwarf::DW_ATE_signed_char))
  1467. DwarfExpr.AddSignedConstant(Value.getInt());
  1468. else
  1469. DwarfExpr.AddUnsignedConstant(Value.getInt());
  1470. } else if (Value.isLocation()) {
  1471. MachineLocation Loc = Value.getLoc();
  1472. DIExpression Expr = Value.getExpression();
  1473. if (!Expr || (Expr.getNumElements() == 0))
  1474. // Regular entry.
  1475. Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
  1476. else {
  1477. // Complex address entry.
  1478. if (Loc.getOffset()) {
  1479. DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
  1480. DwarfExpr.AddExpression(Expr, PieceOffsetInBits);
  1481. } else
  1482. DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
  1483. PieceOffsetInBits);
  1484. if (DV.isIndirect())
  1485. DwarfExpr.EmitOp(dwarf::DW_OP_deref);
  1486. }
  1487. }
  1488. // else ... ignore constant fp. There is not any good way to
  1489. // to represent them here in dwarf.
  1490. // FIXME: ^
  1491. }
  1492. void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
  1493. Asm->OutStreamer.AddComment("Loc expr size");
  1494. MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
  1495. MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
  1496. Asm->EmitLabelDifference(end, begin, 2);
  1497. Asm->OutStreamer.EmitLabel(begin);
  1498. // Emit the entry.
  1499. APByteStreamer Streamer(*Asm);
  1500. emitDebugLocEntry(Streamer, Entry);
  1501. // Close the range.
  1502. Asm->OutStreamer.EmitLabel(end);
  1503. }
  1504. // Emit locations into the debug loc section.
  1505. void DwarfDebug::emitDebugLoc() {
  1506. // Start the dwarf loc section.
  1507. Asm->OutStreamer.SwitchSection(
  1508. Asm->getObjFileLowering().getDwarfLocSection());
  1509. unsigned char Size = Asm->getDataLayout().getPointerSize();
  1510. for (const auto &DebugLoc : DotDebugLocEntries) {
  1511. Asm->OutStreamer.EmitLabel(DebugLoc.Label);
  1512. const DwarfCompileUnit *CU = DebugLoc.CU;
  1513. for (const auto &Entry : DebugLoc.List) {
  1514. // Set up the range. This range is relative to the entry point of the
  1515. // compile unit. This is a hard coded 0 for low_pc when we're emitting
  1516. // ranges, or the DW_AT_low_pc on the compile unit otherwise.
  1517. if (auto *Base = CU->getBaseAddress()) {
  1518. Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
  1519. Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
  1520. } else {
  1521. Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
  1522. Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
  1523. }
  1524. emitDebugLocEntryLocation(Entry);
  1525. }
  1526. Asm->OutStreamer.EmitIntValue(0, Size);
  1527. Asm->OutStreamer.EmitIntValue(0, Size);
  1528. }
  1529. }
  1530. void DwarfDebug::emitDebugLocDWO() {
  1531. Asm->OutStreamer.SwitchSection(
  1532. Asm->getObjFileLowering().getDwarfLocDWOSection());
  1533. for (const auto &DebugLoc : DotDebugLocEntries) {
  1534. Asm->OutStreamer.EmitLabel(DebugLoc.Label);
  1535. for (const auto &Entry : DebugLoc.List) {
  1536. // Just always use start_length for now - at least that's one address
  1537. // rather than two. We could get fancier and try to, say, reuse an
  1538. // address we know we've emitted elsewhere (the start of the function?
  1539. // The start of the CU or CU subrange that encloses this range?)
  1540. Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
  1541. unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
  1542. Asm->EmitULEB128(idx);
  1543. Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
  1544. emitDebugLocEntryLocation(Entry);
  1545. }
  1546. Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
  1547. }
  1548. }
  1549. struct ArangeSpan {
  1550. const MCSymbol *Start, *End;
  1551. };
  1552. // Emit a debug aranges section, containing a CU lookup for any
  1553. // address we can tie back to a CU.
  1554. void DwarfDebug::emitDebugARanges() {
  1555. // Start the dwarf aranges section.
  1556. Asm->OutStreamer.SwitchSection(
  1557. Asm->getObjFileLowering().getDwarfARangesSection());
  1558. typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
  1559. SpansType Spans;
  1560. // Build a list of sections used.
  1561. std::vector<const MCSection *> Sections;
  1562. for (const auto &it : SectionMap) {
  1563. const MCSection *Section = it.first;
  1564. Sections.push_back(Section);
  1565. }
  1566. // Sort the sections into order.
  1567. // This is only done to ensure consistent output order across different runs.
  1568. std::sort(Sections.begin(), Sections.end(), SectionSort);
  1569. // Build a set of address spans, sorted by CU.
  1570. for (const MCSection *Section : Sections) {
  1571. SmallVector<SymbolCU, 8> &List = SectionMap[Section];
  1572. if (List.size() < 2)
  1573. continue;
  1574. // Sort the symbols by offset within the section.
  1575. std::sort(List.begin(), List.end(),
  1576. [&](const SymbolCU &A, const SymbolCU &B) {
  1577. unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
  1578. unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
  1579. // Symbols with no order assigned should be placed at the end.
  1580. // (e.g. section end labels)
  1581. if (IA == 0)
  1582. return false;
  1583. if (IB == 0)
  1584. return true;
  1585. return IA < IB;
  1586. });
  1587. // If we have no section (e.g. common), just write out
  1588. // individual spans for each symbol.
  1589. if (!Section) {
  1590. for (const SymbolCU &Cur : List) {
  1591. ArangeSpan Span;
  1592. Span.Start = Cur.Sym;
  1593. Span.End = nullptr;
  1594. if (Cur.CU)
  1595. Spans[Cur.CU].push_back(Span);
  1596. }
  1597. } else {
  1598. // Build spans between each label.
  1599. const MCSymbol *StartSym = List[0].Sym;
  1600. for (size_t n = 1, e = List.size(); n < e; n++) {
  1601. const SymbolCU &Prev = List[n - 1];
  1602. const SymbolCU &Cur = List[n];
  1603. // Try and build the longest span we can within the same CU.
  1604. if (Cur.CU != Prev.CU) {
  1605. ArangeSpan Span;
  1606. Span.Start = StartSym;
  1607. Span.End = Cur.Sym;
  1608. Spans[Prev.CU].push_back(Span);
  1609. StartSym = Cur.Sym;
  1610. }
  1611. }
  1612. }
  1613. }
  1614. unsigned PtrSize = Asm->getDataLayout().getPointerSize();
  1615. // Build a list of CUs used.
  1616. std::vector<DwarfCompileUnit *> CUs;
  1617. for (const auto &it : Spans) {
  1618. DwarfCompileUnit *CU = it.first;
  1619. CUs.push_back(CU);
  1620. }
  1621. // Sort the CU list (again, to ensure consistent output order).
  1622. std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
  1623. return A->getUniqueID() < B->getUniqueID();
  1624. });
  1625. // Emit an arange table for each CU we used.
  1626. for (DwarfCompileUnit *CU : CUs) {
  1627. std::vector<ArangeSpan> &List = Spans[CU];
  1628. // Describe the skeleton CU's offset and length, not the dwo file's.
  1629. if (auto *Skel = CU->getSkeleton())
  1630. CU = Skel;
  1631. // Emit size of content not including length itself.
  1632. unsigned ContentSize =
  1633. sizeof(int16_t) + // DWARF ARange version number
  1634. sizeof(int32_t) + // Offset of CU in the .debug_info section
  1635. sizeof(int8_t) + // Pointer Size (in bytes)
  1636. sizeof(int8_t); // Segment Size (in bytes)
  1637. unsigned TupleSize = PtrSize * 2;
  1638. // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
  1639. unsigned Padding =
  1640. OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
  1641. ContentSize += Padding;
  1642. ContentSize += (List.size() + 1) * TupleSize;
  1643. // For each compile unit, write the list of spans it covers.
  1644. Asm->OutStreamer.AddComment("Length of ARange Set");
  1645. Asm->EmitInt32(ContentSize);
  1646. Asm->OutStreamer.AddComment("DWARF Arange version number");
  1647. Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
  1648. Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
  1649. Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
  1650. Asm->OutStreamer.AddComment("Address Size (in bytes)");
  1651. Asm->EmitInt8(PtrSize);
  1652. Asm->OutStreamer.AddComment("Segment Size (in bytes)");
  1653. Asm->EmitInt8(0);
  1654. Asm->OutStreamer.EmitFill(Padding, 0xff);
  1655. for (const ArangeSpan &Span : List) {
  1656. Asm->EmitLabelReference(Span.Start, PtrSize);
  1657. // Calculate the size as being from the span start to it's end.
  1658. if (Span.End) {
  1659. Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
  1660. } else {
  1661. // For symbols without an end marker (e.g. common), we
  1662. // write a single arange entry containing just that one symbol.
  1663. uint64_t Size = SymSize[Span.Start];
  1664. if (Size == 0)
  1665. Size = 1;
  1666. Asm->OutStreamer.EmitIntValue(Size, PtrSize);
  1667. }
  1668. }
  1669. Asm->OutStreamer.AddComment("ARange terminator");
  1670. Asm->OutStreamer.EmitIntValue(0, PtrSize);
  1671. Asm->OutStreamer.EmitIntValue(0, PtrSize);
  1672. }
  1673. }
  1674. // Emit visible names into a debug ranges section.
  1675. void DwarfDebug::emitDebugRanges() {
  1676. // Start the dwarf ranges section.
  1677. Asm->OutStreamer.SwitchSection(
  1678. Asm->getObjFileLowering().getDwarfRangesSection());
  1679. // Size for our labels.
  1680. unsigned char Size = Asm->getDataLayout().getPointerSize();
  1681. // Grab the specific ranges for the compile units in the module.
  1682. for (const auto &I : CUMap) {
  1683. DwarfCompileUnit *TheCU = I.second;
  1684. if (auto *Skel = TheCU->getSkeleton())
  1685. TheCU = Skel;
  1686. // Iterate over the misc ranges for the compile units in the module.
  1687. for (const RangeSpanList &List : TheCU->getRangeLists()) {
  1688. // Emit our symbol so we can find the beginning of the range.
  1689. Asm->OutStreamer.EmitLabel(List.getSym());
  1690. for (const RangeSpan &Range : List.getRanges()) {
  1691. const MCSymbol *Begin = Range.getStart();
  1692. const MCSymbol *End = Range.getEnd();
  1693. assert(Begin && "Range without a begin symbol?");
  1694. assert(End && "Range without an end symbol?");
  1695. if (auto *Base = TheCU->getBaseAddress()) {
  1696. Asm->EmitLabelDifference(Begin, Base, Size);
  1697. Asm->EmitLabelDifference(End, Base, Size);
  1698. } else {
  1699. Asm->OutStreamer.EmitSymbolValue(Begin, Size);
  1700. Asm->OutStreamer.EmitSymbolValue(End, Size);
  1701. }
  1702. }
  1703. // And terminate the list with two 0 values.
  1704. Asm->OutStreamer.EmitIntValue(0, Size);
  1705. Asm->OutStreamer.EmitIntValue(0, Size);
  1706. }
  1707. }
  1708. }
  1709. // DWARF5 Experimental Separate Dwarf emitters.
  1710. void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
  1711. std::unique_ptr<DwarfUnit> NewU) {
  1712. NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
  1713. U.getCUNode().getSplitDebugFilename());
  1714. if (!CompilationDir.empty())
  1715. NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
  1716. addGnuPubAttributes(*NewU, Die);
  1717. SkeletonHolder.addUnit(std::move(NewU));
  1718. }
  1719. // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
  1720. // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
  1721. // DW_AT_addr_base, DW_AT_ranges_base.
  1722. DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
  1723. auto OwnedUnit = make_unique<DwarfCompileUnit>(
  1724. CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
  1725. DwarfCompileUnit &NewCU = *OwnedUnit;
  1726. NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
  1727. DwarfInfoSectionSym);
  1728. NewCU.initStmtList(DwarfLineSectionSym);
  1729. initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
  1730. return NewCU;
  1731. }
  1732. // Emit the .debug_info.dwo section for separated dwarf. This contains the
  1733. // compile units that would normally be in debug_info.
  1734. void DwarfDebug::emitDebugInfoDWO() {
  1735. assert(useSplitDwarf() && "No split dwarf debug info?");
  1736. // Don't pass an abbrev symbol, using a constant zero instead so as not to
  1737. // emit relocations into the dwo file.
  1738. InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
  1739. }
  1740. // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
  1741. // abbreviations for the .debug_info.dwo section.
  1742. void DwarfDebug::emitDebugAbbrevDWO() {
  1743. assert(useSplitDwarf() && "No split dwarf?");
  1744. InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
  1745. }
  1746. void DwarfDebug::emitDebugLineDWO() {
  1747. assert(useSplitDwarf() && "No split dwarf?");
  1748. Asm->OutStreamer.SwitchSection(
  1749. Asm->getObjFileLowering().getDwarfLineDWOSection());
  1750. SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
  1751. }
  1752. // Emit the .debug_str.dwo section for separated dwarf. This contains the
  1753. // string section and is identical in format to traditional .debug_str
  1754. // sections.
  1755. void DwarfDebug::emitDebugStrDWO() {
  1756. assert(useSplitDwarf() && "No split dwarf?");
  1757. const MCSection *OffSec =
  1758. Asm->getObjFileLowering().getDwarfStrOffDWOSection();
  1759. InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
  1760. OffSec);
  1761. }
  1762. MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
  1763. if (!useSplitDwarf())
  1764. return nullptr;
  1765. if (SingleCU)
  1766. SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
  1767. return &SplitTypeUnitFileTable;
  1768. }
  1769. static uint64_t makeTypeSignature(StringRef Identifier) {
  1770. MD5 Hash;
  1771. Hash.update(Identifier);
  1772. // ... take the least significant 8 bytes and return those. Our MD5
  1773. // implementation always returns its results in little endian, swap bytes
  1774. // appropriately.
  1775. MD5::MD5Result Result;
  1776. Hash.final(Result);
  1777. return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
  1778. }
  1779. void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
  1780. StringRef Identifier, DIE &RefDie,
  1781. DICompositeType CTy) {
  1782. // Fast path if we're building some type units and one has already used the
  1783. // address pool we know we're going to throw away all this work anyway, so
  1784. // don't bother building dependent types.
  1785. if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
  1786. return;
  1787. const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
  1788. if (TU) {
  1789. CU.addDIETypeSignature(RefDie, *TU);
  1790. return;
  1791. }
  1792. bool TopLevelType = TypeUnitsUnderConstruction.empty();
  1793. AddrPool.resetUsedFlag();
  1794. auto OwnedUnit = make_unique<DwarfTypeUnit>(
  1795. InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
  1796. this, &InfoHolder, getDwoLineTable(CU));
  1797. DwarfTypeUnit &NewTU = *OwnedUnit;
  1798. DIE &UnitDie = NewTU.getUnitDie();
  1799. TU = &NewTU;
  1800. TypeUnitsUnderConstruction.push_back(
  1801. std::make_pair(std::move(OwnedUnit), CTy));
  1802. NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
  1803. CU.getLanguage());
  1804. uint64_t Signature = makeTypeSignature(Identifier);
  1805. NewTU.setTypeSignature(Signature);
  1806. if (useSplitDwarf())
  1807. NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
  1808. else {
  1809. CU.applyStmtList(UnitDie);
  1810. NewTU.initSection(
  1811. Asm->getObjFileLowering().getDwarfTypesSection(Signature));
  1812. }
  1813. NewTU.setType(NewTU.createTypeDIE(CTy));
  1814. if (TopLevelType) {
  1815. auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
  1816. TypeUnitsUnderConstruction.clear();
  1817. // Types referencing entries in the address table cannot be placed in type
  1818. // units.
  1819. if (AddrPool.hasBeenUsed()) {
  1820. // Remove all the types built while building this type.
  1821. // This is pessimistic as some of these types might not be dependent on
  1822. // the type that used an address.
  1823. for (const auto &TU : TypeUnitsToAdd)
  1824. DwarfTypeUnits.erase(TU.second);
  1825. // Construct this type in the CU directly.
  1826. // This is inefficient because all the dependent types will be rebuilt
  1827. // from scratch, including building them in type units, discovering that
  1828. // they depend on addresses, throwing them out and rebuilding them.
  1829. CU.constructTypeDIE(RefDie, CTy);
  1830. return;
  1831. }
  1832. // If the type wasn't dependent on fission addresses, finish adding the type
  1833. // and all its dependent types.
  1834. for (auto &TU : TypeUnitsToAdd)
  1835. InfoHolder.addUnit(std::move(TU.first));
  1836. }
  1837. CU.addDIETypeSignature(RefDie, NewTU);
  1838. }
  1839. // Accelerator table mutators - add each name along with its companion
  1840. // DIE to the proper table while ensuring that the name that we're going
  1841. // to reference is in the string table. We do this since the names we
  1842. // add may not only be identical to the names in the DIE.
  1843. void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
  1844. if (!useDwarfAccelTables())
  1845. return;
  1846. AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
  1847. &Die);
  1848. }
  1849. void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
  1850. if (!useDwarfAccelTables())
  1851. return;
  1852. AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
  1853. &Die);
  1854. }
  1855. void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
  1856. if (!useDwarfAccelTables())
  1857. return;
  1858. AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
  1859. &Die);
  1860. }
  1861. void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
  1862. if (!useDwarfAccelTables())
  1863. return;
  1864. AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
  1865. &Die);
  1866. }