MCDwarf.cpp 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012
  1. //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/MC/MCDwarf.h"
  9. #include "llvm/ADT/ArrayRef.h"
  10. #include "llvm/ADT/DenseMap.h"
  11. #include "llvm/ADT/Hashing.h"
  12. #include "llvm/ADT/Optional.h"
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/ADT/SmallString.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include "llvm/BinaryFormat/Dwarf.h"
  19. #include "llvm/Config/config.h"
  20. #include "llvm/MC/MCAsmInfo.h"
  21. #include "llvm/MC/MCContext.h"
  22. #include "llvm/MC/MCExpr.h"
  23. #include "llvm/MC/MCObjectFileInfo.h"
  24. #include "llvm/MC/MCObjectStreamer.h"
  25. #include "llvm/MC/MCRegisterInfo.h"
  26. #include "llvm/MC/MCSection.h"
  27. #include "llvm/MC/MCStreamer.h"
  28. #include "llvm/MC/MCSymbol.h"
  29. #include "llvm/MC/StringTableBuilder.h"
  30. #include "llvm/Support/Casting.h"
  31. #include "llvm/Support/Endian.h"
  32. #include "llvm/Support/EndianStream.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/LEB128.h"
  35. #include "llvm/Support/MathExtras.h"
  36. #include "llvm/Support/Path.h"
  37. #include "llvm/Support/SourceMgr.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include <cassert>
  40. #include <cstdint>
  41. #include <string>
  42. #include <utility>
  43. #include <vector>
  44. using namespace llvm;
  45. MCSymbol *mcdwarf::emitListsTableHeaderStart(MCStreamer &S) {
  46. MCSymbol *Start = S.getContext().createTempSymbol("debug_list_header_start");
  47. MCSymbol *End = S.getContext().createTempSymbol("debug_list_header_end");
  48. auto DwarfFormat = S.getContext().getDwarfFormat();
  49. if (DwarfFormat == dwarf::DWARF64) {
  50. S.AddComment("DWARF64 mark");
  51. S.emitInt32(dwarf::DW_LENGTH_DWARF64);
  52. }
  53. S.AddComment("Length");
  54. S.emitAbsoluteSymbolDiff(End, Start,
  55. dwarf::getDwarfOffsetByteSize(DwarfFormat));
  56. S.emitLabel(Start);
  57. S.AddComment("Version");
  58. S.emitInt16(S.getContext().getDwarfVersion());
  59. S.AddComment("Address size");
  60. S.emitInt8(S.getContext().getAsmInfo()->getCodePointerSize());
  61. S.AddComment("Segment selector size");
  62. S.emitInt8(0);
  63. return End;
  64. }
  65. /// Manage the .debug_line_str section contents, if we use it.
  66. class llvm::MCDwarfLineStr {
  67. MCSymbol *LineStrLabel = nullptr;
  68. StringTableBuilder LineStrings{StringTableBuilder::DWARF};
  69. bool UseRelocs = false;
  70. public:
  71. /// Construct an instance that can emit .debug_line_str (for use in a normal
  72. /// v5 line table).
  73. explicit MCDwarfLineStr(MCContext &Ctx) {
  74. UseRelocs = Ctx.getAsmInfo()->doesDwarfUseRelocationsAcrossSections();
  75. if (UseRelocs)
  76. LineStrLabel =
  77. Ctx.getObjectFileInfo()->getDwarfLineStrSection()->getBeginSymbol();
  78. }
  79. /// Emit a reference to the string.
  80. void emitRef(MCStreamer *MCOS, StringRef Path);
  81. /// Emit the .debug_line_str section if appropriate.
  82. void emitSection(MCStreamer *MCOS);
  83. };
  84. static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
  85. unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
  86. if (MinInsnLength == 1)
  87. return AddrDelta;
  88. if (AddrDelta % MinInsnLength != 0) {
  89. // TODO: report this error, but really only once.
  90. ;
  91. }
  92. return AddrDelta / MinInsnLength;
  93. }
  94. //
  95. // This is called when an instruction is assembled into the specified section
  96. // and if there is information from the last .loc directive that has yet to have
  97. // a line entry made for it is made.
  98. //
  99. void MCDwarfLineEntry::Make(MCObjectStreamer *MCOS, MCSection *Section) {
  100. if (!MCOS->getContext().getDwarfLocSeen())
  101. return;
  102. // Create a symbol at in the current section for use in the line entry.
  103. MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
  104. // Set the value of the symbol to use for the MCDwarfLineEntry.
  105. MCOS->emitLabel(LineSym);
  106. // Get the current .loc info saved in the context.
  107. const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
  108. // Create a (local) line entry with the symbol and the current .loc info.
  109. MCDwarfLineEntry LineEntry(LineSym, DwarfLoc);
  110. // clear DwarfLocSeen saying the current .loc info is now used.
  111. MCOS->getContext().clearDwarfLocSeen();
  112. // Add the line entry to this section's entries.
  113. MCOS->getContext()
  114. .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
  115. .getMCLineSections()
  116. .addLineEntry(LineEntry, Section);
  117. }
  118. //
  119. // This helper routine returns an expression of End - Start + IntVal .
  120. //
  121. static inline const MCExpr *makeEndMinusStartExpr(MCContext &Ctx,
  122. const MCSymbol &Start,
  123. const MCSymbol &End,
  124. int IntVal) {
  125. MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
  126. const MCExpr *Res = MCSymbolRefExpr::create(&End, Variant, Ctx);
  127. const MCExpr *RHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
  128. const MCExpr *Res1 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, Ctx);
  129. const MCExpr *Res2 = MCConstantExpr::create(IntVal, Ctx);
  130. const MCExpr *Res3 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, Ctx);
  131. return Res3;
  132. }
  133. //
  134. // This helper routine returns an expression of Start + IntVal .
  135. //
  136. static inline const MCExpr *
  137. makeStartPlusIntExpr(MCContext &Ctx, const MCSymbol &Start, int IntVal) {
  138. MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
  139. const MCExpr *LHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
  140. const MCExpr *RHS = MCConstantExpr::create(IntVal, Ctx);
  141. const MCExpr *Res = MCBinaryExpr::create(MCBinaryExpr::Add, LHS, RHS, Ctx);
  142. return Res;
  143. }
  144. //
  145. // This emits the Dwarf line table for the specified section from the entries
  146. // in the LineSection.
  147. //
  148. static inline void emitDwarfLineTable(
  149. MCObjectStreamer *MCOS, MCSection *Section,
  150. const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {
  151. unsigned FileNum = 1;
  152. unsigned LastLine = 1;
  153. unsigned Column = 0;
  154. unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
  155. unsigned Isa = 0;
  156. unsigned Discriminator = 0;
  157. MCSymbol *LastLabel = nullptr;
  158. // Loop through each MCDwarfLineEntry and encode the dwarf line number table.
  159. for (const MCDwarfLineEntry &LineEntry : LineEntries) {
  160. int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;
  161. if (FileNum != LineEntry.getFileNum()) {
  162. FileNum = LineEntry.getFileNum();
  163. MCOS->emitInt8(dwarf::DW_LNS_set_file);
  164. MCOS->emitULEB128IntValue(FileNum);
  165. }
  166. if (Column != LineEntry.getColumn()) {
  167. Column = LineEntry.getColumn();
  168. MCOS->emitInt8(dwarf::DW_LNS_set_column);
  169. MCOS->emitULEB128IntValue(Column);
  170. }
  171. if (Discriminator != LineEntry.getDiscriminator() &&
  172. MCOS->getContext().getDwarfVersion() >= 4) {
  173. Discriminator = LineEntry.getDiscriminator();
  174. unsigned Size = getULEB128Size(Discriminator);
  175. MCOS->emitInt8(dwarf::DW_LNS_extended_op);
  176. MCOS->emitULEB128IntValue(Size + 1);
  177. MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);
  178. MCOS->emitULEB128IntValue(Discriminator);
  179. }
  180. if (Isa != LineEntry.getIsa()) {
  181. Isa = LineEntry.getIsa();
  182. MCOS->emitInt8(dwarf::DW_LNS_set_isa);
  183. MCOS->emitULEB128IntValue(Isa);
  184. }
  185. if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
  186. Flags = LineEntry.getFlags();
  187. MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);
  188. }
  189. if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)
  190. MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);
  191. if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)
  192. MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);
  193. if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
  194. MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);
  195. MCSymbol *Label = LineEntry.getLabel();
  196. // At this point we want to emit/create the sequence to encode the delta in
  197. // line numbers and the increment of the address from the previous Label
  198. // and the current Label.
  199. const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
  200. MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
  201. asmInfo->getCodePointerSize());
  202. Discriminator = 0;
  203. LastLine = LineEntry.getLine();
  204. LastLabel = Label;
  205. }
  206. // Emit a DW_LNE_end_sequence for the end of the section.
  207. // Use the section end label to compute the address delta and use INT64_MAX
  208. // as the line delta which is the signal that this is actually a
  209. // DW_LNE_end_sequence.
  210. MCSymbol *SectionEnd = MCOS->endSection(Section);
  211. // Switch back the dwarf line section, in case endSection had to switch the
  212. // section.
  213. MCContext &Ctx = MCOS->getContext();
  214. MCOS->SwitchSection(Ctx.getObjectFileInfo()->getDwarfLineSection());
  215. const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
  216. MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
  217. AsmInfo->getCodePointerSize());
  218. }
  219. //
  220. // This emits the Dwarf file and the line tables.
  221. //
  222. void MCDwarfLineTable::Emit(MCObjectStreamer *MCOS,
  223. MCDwarfLineTableParams Params) {
  224. MCContext &context = MCOS->getContext();
  225. auto &LineTables = context.getMCDwarfLineTables();
  226. // Bail out early so we don't switch to the debug_line section needlessly and
  227. // in doing so create an unnecessary (if empty) section.
  228. if (LineTables.empty())
  229. return;
  230. // In a v5 non-split line table, put the strings in a separate section.
  231. Optional<MCDwarfLineStr> LineStr;
  232. if (context.getDwarfVersion() >= 5)
  233. LineStr = MCDwarfLineStr(context);
  234. // Switch to the section where the table will be emitted into.
  235. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
  236. // Handle the rest of the Compile Units.
  237. for (const auto &CUIDTablePair : LineTables) {
  238. CUIDTablePair.second.EmitCU(MCOS, Params, LineStr);
  239. }
  240. if (LineStr)
  241. LineStr->emitSection(MCOS);
  242. }
  243. void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params,
  244. MCSection *Section) const {
  245. if (!HasSplitLineTable)
  246. return;
  247. Optional<MCDwarfLineStr> NoLineStr(None);
  248. MCOS.SwitchSection(Section);
  249. MCOS.emitLabel(Header.Emit(&MCOS, Params, None, NoLineStr).second);
  250. }
  251. std::pair<MCSymbol *, MCSymbol *>
  252. MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
  253. Optional<MCDwarfLineStr> &LineStr) const {
  254. static const char StandardOpcodeLengths[] = {
  255. 0, // length of DW_LNS_copy
  256. 1, // length of DW_LNS_advance_pc
  257. 1, // length of DW_LNS_advance_line
  258. 1, // length of DW_LNS_set_file
  259. 1, // length of DW_LNS_set_column
  260. 0, // length of DW_LNS_negate_stmt
  261. 0, // length of DW_LNS_set_basic_block
  262. 0, // length of DW_LNS_const_add_pc
  263. 1, // length of DW_LNS_fixed_advance_pc
  264. 0, // length of DW_LNS_set_prologue_end
  265. 0, // length of DW_LNS_set_epilogue_begin
  266. 1 // DW_LNS_set_isa
  267. };
  268. assert(array_lengthof(StandardOpcodeLengths) >=
  269. (Params.DWARF2LineOpcodeBase - 1U));
  270. return Emit(
  271. MCOS, Params,
  272. makeArrayRef(StandardOpcodeLengths, Params.DWARF2LineOpcodeBase - 1),
  273. LineStr);
  274. }
  275. static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
  276. MCContext &Context = OS.getContext();
  277. assert(!isa<MCSymbolRefExpr>(Expr));
  278. if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
  279. return Expr;
  280. MCSymbol *ABS = Context.createTempSymbol();
  281. OS.emitAssignment(ABS, Expr);
  282. return MCSymbolRefExpr::create(ABS, Context);
  283. }
  284. static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
  285. const MCExpr *ABS = forceExpAbs(OS, Value);
  286. OS.emitValue(ABS, Size);
  287. }
  288. void MCDwarfLineStr::emitSection(MCStreamer *MCOS) {
  289. // Switch to the .debug_line_str section.
  290. MCOS->SwitchSection(
  291. MCOS->getContext().getObjectFileInfo()->getDwarfLineStrSection());
  292. // Emit the strings without perturbing the offsets we used.
  293. LineStrings.finalizeInOrder();
  294. SmallString<0> Data;
  295. Data.resize(LineStrings.getSize());
  296. LineStrings.write((uint8_t *)Data.data());
  297. MCOS->emitBinaryData(Data.str());
  298. }
  299. void MCDwarfLineStr::emitRef(MCStreamer *MCOS, StringRef Path) {
  300. int RefSize =
  301. dwarf::getDwarfOffsetByteSize(MCOS->getContext().getDwarfFormat());
  302. size_t Offset = LineStrings.add(Path);
  303. if (UseRelocs) {
  304. MCContext &Ctx = MCOS->getContext();
  305. MCOS->emitValue(makeStartPlusIntExpr(Ctx, *LineStrLabel, Offset), RefSize);
  306. } else
  307. MCOS->emitIntValue(Offset, RefSize);
  308. }
  309. void MCDwarfLineTableHeader::emitV2FileDirTables(MCStreamer *MCOS) const {
  310. // First the directory table.
  311. for (auto &Dir : MCDwarfDirs) {
  312. MCOS->emitBytes(Dir); // The DirectoryName, and...
  313. MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
  314. }
  315. MCOS->emitInt8(0); // Terminate the directory list.
  316. // Second the file table.
  317. for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
  318. assert(!MCDwarfFiles[i].Name.empty());
  319. MCOS->emitBytes(MCDwarfFiles[i].Name); // FileName and...
  320. MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
  321. MCOS->emitULEB128IntValue(MCDwarfFiles[i].DirIndex); // Directory number.
  322. MCOS->emitInt8(0); // Last modification timestamp (always 0).
  323. MCOS->emitInt8(0); // File size (always 0).
  324. }
  325. MCOS->emitInt8(0); // Terminate the file list.
  326. }
  327. static void emitOneV5FileEntry(MCStreamer *MCOS, const MCDwarfFile &DwarfFile,
  328. bool EmitMD5, bool HasSource,
  329. Optional<MCDwarfLineStr> &LineStr) {
  330. assert(!DwarfFile.Name.empty());
  331. if (LineStr)
  332. LineStr->emitRef(MCOS, DwarfFile.Name);
  333. else {
  334. MCOS->emitBytes(DwarfFile.Name); // FileName and...
  335. MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
  336. }
  337. MCOS->emitULEB128IntValue(DwarfFile.DirIndex); // Directory number.
  338. if (EmitMD5) {
  339. const MD5::MD5Result &Cksum = *DwarfFile.Checksum;
  340. MCOS->emitBinaryData(
  341. StringRef(reinterpret_cast<const char *>(Cksum.Bytes.data()),
  342. Cksum.Bytes.size()));
  343. }
  344. if (HasSource) {
  345. if (LineStr)
  346. LineStr->emitRef(MCOS, DwarfFile.Source.getValueOr(StringRef()));
  347. else {
  348. MCOS->emitBytes(
  349. DwarfFile.Source.getValueOr(StringRef())); // Source and...
  350. MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
  351. }
  352. }
  353. }
  354. void MCDwarfLineTableHeader::emitV5FileDirTables(
  355. MCStreamer *MCOS, Optional<MCDwarfLineStr> &LineStr) const {
  356. // The directory format, which is just a list of the directory paths. In a
  357. // non-split object, these are references to .debug_line_str; in a split
  358. // object, they are inline strings.
  359. MCOS->emitInt8(1);
  360. MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
  361. MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
  362. : dwarf::DW_FORM_string);
  363. MCOS->emitULEB128IntValue(MCDwarfDirs.size() + 1);
  364. // Try not to emit an empty compilation directory.
  365. const StringRef CompDir = CompilationDir.empty()
  366. ? MCOS->getContext().getCompilationDir()
  367. : StringRef(CompilationDir);
  368. if (LineStr) {
  369. // Record path strings, emit references here.
  370. LineStr->emitRef(MCOS, CompDir);
  371. for (const auto &Dir : MCDwarfDirs)
  372. LineStr->emitRef(MCOS, Dir);
  373. } else {
  374. // The list of directory paths. Compilation directory comes first.
  375. MCOS->emitBytes(CompDir);
  376. MCOS->emitBytes(StringRef("\0", 1));
  377. for (const auto &Dir : MCDwarfDirs) {
  378. MCOS->emitBytes(Dir); // The DirectoryName, and...
  379. MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
  380. }
  381. }
  382. // The file format, which is the inline null-terminated filename and a
  383. // directory index. We don't track file size/timestamp so don't emit them
  384. // in the v5 table. Emit MD5 checksums and source if we have them.
  385. uint64_t Entries = 2;
  386. if (HasAllMD5)
  387. Entries += 1;
  388. if (HasSource)
  389. Entries += 1;
  390. MCOS->emitInt8(Entries);
  391. MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
  392. MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
  393. : dwarf::DW_FORM_string);
  394. MCOS->emitULEB128IntValue(dwarf::DW_LNCT_directory_index);
  395. MCOS->emitULEB128IntValue(dwarf::DW_FORM_udata);
  396. if (HasAllMD5) {
  397. MCOS->emitULEB128IntValue(dwarf::DW_LNCT_MD5);
  398. MCOS->emitULEB128IntValue(dwarf::DW_FORM_data16);
  399. }
  400. if (HasSource) {
  401. MCOS->emitULEB128IntValue(dwarf::DW_LNCT_LLVM_source);
  402. MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
  403. : dwarf::DW_FORM_string);
  404. }
  405. // Then the counted list of files. The root file is file #0, then emit the
  406. // files as provide by .file directives.
  407. // MCDwarfFiles has an unused element [0] so use size() not size()+1.
  408. // But sometimes MCDwarfFiles is empty, in which case we still emit one file.
  409. MCOS->emitULEB128IntValue(MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size());
  410. // To accommodate assembler source written for DWARF v4 but trying to emit
  411. // v5: If we didn't see a root file explicitly, replicate file #1.
  412. assert((!RootFile.Name.empty() || MCDwarfFiles.size() >= 1) &&
  413. "No root file and no .file directives");
  414. emitOneV5FileEntry(MCOS, RootFile.Name.empty() ? MCDwarfFiles[1] : RootFile,
  415. HasAllMD5, HasSource, LineStr);
  416. for (unsigned i = 1; i < MCDwarfFiles.size(); ++i)
  417. emitOneV5FileEntry(MCOS, MCDwarfFiles[i], HasAllMD5, HasSource, LineStr);
  418. }
  419. std::pair<MCSymbol *, MCSymbol *>
  420. MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
  421. ArrayRef<char> StandardOpcodeLengths,
  422. Optional<MCDwarfLineStr> &LineStr) const {
  423. MCContext &context = MCOS->getContext();
  424. // Create a symbol at the beginning of the line table.
  425. MCSymbol *LineStartSym = Label;
  426. if (!LineStartSym)
  427. LineStartSym = context.createTempSymbol();
  428. // Set the value of the symbol, as we are at the start of the line table.
  429. MCOS->emitLabel(LineStartSym);
  430. // Create a symbol for the end of the section (to be set when we get there).
  431. MCSymbol *LineEndSym = context.createTempSymbol();
  432. unsigned UnitLengthBytes =
  433. dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
  434. unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
  435. if (context.getDwarfFormat() == dwarf::DWARF64)
  436. // Emit DWARF64 mark.
  437. MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
  438. // The length field does not include itself and, in case of the 64-bit DWARF
  439. // format, the DWARF64 mark.
  440. emitAbsValue(*MCOS,
  441. makeEndMinusStartExpr(context, *LineStartSym, *LineEndSym,
  442. UnitLengthBytes),
  443. OffsetSize);
  444. // Next 2 bytes is the Version.
  445. unsigned LineTableVersion = context.getDwarfVersion();
  446. MCOS->emitInt16(LineTableVersion);
  447. // Keep track of the bytes between the very start and where the header length
  448. // comes out.
  449. unsigned PreHeaderLengthBytes = UnitLengthBytes + 2;
  450. // In v5, we get address info next.
  451. if (LineTableVersion >= 5) {
  452. MCOS->emitInt8(context.getAsmInfo()->getCodePointerSize());
  453. MCOS->emitInt8(0); // Segment selector; same as EmitGenDwarfAranges.
  454. PreHeaderLengthBytes += 2;
  455. }
  456. // Create a symbol for the end of the prologue (to be set when we get there).
  457. MCSymbol *ProEndSym = context.createTempSymbol(); // Lprologue_end
  458. // Length of the prologue, is the next 4 bytes (8 bytes for DWARF64). This is
  459. // actually the length from after the length word, to the end of the prologue.
  460. emitAbsValue(*MCOS,
  461. makeEndMinusStartExpr(context, *LineStartSym, *ProEndSym,
  462. (PreHeaderLengthBytes + OffsetSize)),
  463. OffsetSize);
  464. // Parameters of the state machine, are next.
  465. MCOS->emitInt8(context.getAsmInfo()->getMinInstAlignment());
  466. // maximum_operations_per_instruction
  467. // For non-VLIW architectures this field is always 1.
  468. // FIXME: VLIW architectures need to update this field accordingly.
  469. if (LineTableVersion >= 4)
  470. MCOS->emitInt8(1);
  471. MCOS->emitInt8(DWARF2_LINE_DEFAULT_IS_STMT);
  472. MCOS->emitInt8(Params.DWARF2LineBase);
  473. MCOS->emitInt8(Params.DWARF2LineRange);
  474. MCOS->emitInt8(StandardOpcodeLengths.size() + 1);
  475. // Standard opcode lengths
  476. for (char Length : StandardOpcodeLengths)
  477. MCOS->emitInt8(Length);
  478. // Put out the directory and file tables. The formats vary depending on
  479. // the version.
  480. if (LineTableVersion >= 5)
  481. emitV5FileDirTables(MCOS, LineStr);
  482. else
  483. emitV2FileDirTables(MCOS);
  484. // This is the end of the prologue, so set the value of the symbol at the
  485. // end of the prologue (that was used in a previous expression).
  486. MCOS->emitLabel(ProEndSym);
  487. return std::make_pair(LineStartSym, LineEndSym);
  488. }
  489. void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS,
  490. MCDwarfLineTableParams Params,
  491. Optional<MCDwarfLineStr> &LineStr) const {
  492. MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;
  493. // Put out the line tables.
  494. for (const auto &LineSec : MCLineSections.getMCLineEntries())
  495. emitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
  496. // This is the end of the section, so set the value of the symbol at the end
  497. // of this section (that was used in a previous expression).
  498. MCOS->emitLabel(LineEndSym);
  499. }
  500. Expected<unsigned> MCDwarfLineTable::tryGetFile(StringRef &Directory,
  501. StringRef &FileName,
  502. Optional<MD5::MD5Result> Checksum,
  503. Optional<StringRef> Source,
  504. uint16_t DwarfVersion,
  505. unsigned FileNumber) {
  506. return Header.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
  507. FileNumber);
  508. }
  509. static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory,
  510. StringRef &FileName, Optional<MD5::MD5Result> Checksum) {
  511. if (RootFile.Name.empty() || RootFile.Name != FileName.data())
  512. return false;
  513. return RootFile.Checksum == Checksum;
  514. }
  515. Expected<unsigned>
  516. MCDwarfLineTableHeader::tryGetFile(StringRef &Directory,
  517. StringRef &FileName,
  518. Optional<MD5::MD5Result> Checksum,
  519. Optional<StringRef> Source,
  520. uint16_t DwarfVersion,
  521. unsigned FileNumber) {
  522. if (Directory == CompilationDir)
  523. Directory = "";
  524. if (FileName.empty()) {
  525. FileName = "<stdin>";
  526. Directory = "";
  527. }
  528. assert(!FileName.empty());
  529. // Keep track of whether any or all files have an MD5 checksum.
  530. // If any files have embedded source, they all must.
  531. if (MCDwarfFiles.empty()) {
  532. trackMD5Usage(Checksum.hasValue());
  533. HasSource = (Source != None);
  534. }
  535. if (isRootFile(RootFile, Directory, FileName, Checksum) && DwarfVersion >= 5)
  536. return 0;
  537. if (FileNumber == 0) {
  538. // File numbers start with 1 and/or after any file numbers
  539. // allocated by inline-assembler .file directives.
  540. FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size();
  541. SmallString<256> Buffer;
  542. auto IterBool = SourceIdMap.insert(
  543. std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),
  544. FileNumber));
  545. if (!IterBool.second)
  546. return IterBool.first->second;
  547. }
  548. // Make space for this FileNumber in the MCDwarfFiles vector if needed.
  549. if (FileNumber >= MCDwarfFiles.size())
  550. MCDwarfFiles.resize(FileNumber + 1);
  551. // Get the new MCDwarfFile slot for this FileNumber.
  552. MCDwarfFile &File = MCDwarfFiles[FileNumber];
  553. // It is an error to see the same number more than once.
  554. if (!File.Name.empty())
  555. return make_error<StringError>("file number already allocated",
  556. inconvertibleErrorCode());
  557. // If any files have embedded source, they all must.
  558. if (HasSource != (Source != None))
  559. return make_error<StringError>("inconsistent use of embedded source",
  560. inconvertibleErrorCode());
  561. if (Directory.empty()) {
  562. // Separate the directory part from the basename of the FileName.
  563. StringRef tFileName = sys::path::filename(FileName);
  564. if (!tFileName.empty()) {
  565. Directory = sys::path::parent_path(FileName);
  566. if (!Directory.empty())
  567. FileName = tFileName;
  568. }
  569. }
  570. // Find or make an entry in the MCDwarfDirs vector for this Directory.
  571. // Capture directory name.
  572. unsigned DirIndex;
  573. if (Directory.empty()) {
  574. // For FileNames with no directories a DirIndex of 0 is used.
  575. DirIndex = 0;
  576. } else {
  577. DirIndex = llvm::find(MCDwarfDirs, Directory) - MCDwarfDirs.begin();
  578. if (DirIndex >= MCDwarfDirs.size())
  579. MCDwarfDirs.push_back(std::string(Directory));
  580. // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
  581. // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
  582. // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
  583. // are stored at MCDwarfFiles[FileNumber].Name .
  584. DirIndex++;
  585. }
  586. File.Name = std::string(FileName);
  587. File.DirIndex = DirIndex;
  588. File.Checksum = Checksum;
  589. trackMD5Usage(Checksum.hasValue());
  590. File.Source = Source;
  591. if (Source)
  592. HasSource = true;
  593. // return the allocated FileNumber.
  594. return FileNumber;
  595. }
  596. /// Utility function to emit the encoding to a streamer.
  597. void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
  598. int64_t LineDelta, uint64_t AddrDelta) {
  599. MCContext &Context = MCOS->getContext();
  600. SmallString<256> Tmp;
  601. raw_svector_ostream OS(Tmp);
  602. MCDwarfLineAddr::Encode(Context, Params, LineDelta, AddrDelta, OS);
  603. MCOS->emitBytes(OS.str());
  604. }
  605. /// Given a special op, return the address skip amount (in units of
  606. /// DWARF2_LINE_MIN_INSN_LENGTH).
  607. static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) {
  608. return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange;
  609. }
  610. /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
  611. void MCDwarfLineAddr::Encode(MCContext &Context, MCDwarfLineTableParams Params,
  612. int64_t LineDelta, uint64_t AddrDelta,
  613. raw_ostream &OS) {
  614. uint64_t Temp, Opcode;
  615. bool NeedCopy = false;
  616. // The maximum address skip amount that can be encoded with a special op.
  617. uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255);
  618. // Scale the address delta by the minimum instruction length.
  619. AddrDelta = ScaleAddrDelta(Context, AddrDelta);
  620. // A LineDelta of INT64_MAX is a signal that this is actually a
  621. // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
  622. // end_sequence to emit the matrix entry.
  623. if (LineDelta == INT64_MAX) {
  624. if (AddrDelta == MaxSpecialAddrDelta)
  625. OS << char(dwarf::DW_LNS_const_add_pc);
  626. else if (AddrDelta) {
  627. OS << char(dwarf::DW_LNS_advance_pc);
  628. encodeULEB128(AddrDelta, OS);
  629. }
  630. OS << char(dwarf::DW_LNS_extended_op);
  631. OS << char(1);
  632. OS << char(dwarf::DW_LNE_end_sequence);
  633. return;
  634. }
  635. // Bias the line delta by the base.
  636. Temp = LineDelta - Params.DWARF2LineBase;
  637. // If the line increment is out of range of a special opcode, we must encode
  638. // it with DW_LNS_advance_line.
  639. if (Temp >= Params.DWARF2LineRange ||
  640. Temp + Params.DWARF2LineOpcodeBase > 255) {
  641. OS << char(dwarf::DW_LNS_advance_line);
  642. encodeSLEB128(LineDelta, OS);
  643. LineDelta = 0;
  644. Temp = 0 - Params.DWARF2LineBase;
  645. NeedCopy = true;
  646. }
  647. // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
  648. if (LineDelta == 0 && AddrDelta == 0) {
  649. OS << char(dwarf::DW_LNS_copy);
  650. return;
  651. }
  652. // Bias the opcode by the special opcode base.
  653. Temp += Params.DWARF2LineOpcodeBase;
  654. // Avoid overflow when addr_delta is large.
  655. if (AddrDelta < 256 + MaxSpecialAddrDelta) {
  656. // Try using a special opcode.
  657. Opcode = Temp + AddrDelta * Params.DWARF2LineRange;
  658. if (Opcode <= 255) {
  659. OS << char(Opcode);
  660. return;
  661. }
  662. // Try using DW_LNS_const_add_pc followed by special op.
  663. Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange;
  664. if (Opcode <= 255) {
  665. OS << char(dwarf::DW_LNS_const_add_pc);
  666. OS << char(Opcode);
  667. return;
  668. }
  669. }
  670. // Otherwise use DW_LNS_advance_pc.
  671. OS << char(dwarf::DW_LNS_advance_pc);
  672. encodeULEB128(AddrDelta, OS);
  673. if (NeedCopy)
  674. OS << char(dwarf::DW_LNS_copy);
  675. else {
  676. assert(Temp <= 255 && "Buggy special opcode encoding.");
  677. OS << char(Temp);
  678. }
  679. }
  680. std::tuple<uint32_t, uint32_t, bool>
  681. MCDwarfLineAddr::fixedEncode(MCContext &Context, int64_t LineDelta,
  682. uint64_t AddrDelta, raw_ostream &OS) {
  683. uint32_t Offset, Size;
  684. if (LineDelta != INT64_MAX) {
  685. OS << char(dwarf::DW_LNS_advance_line);
  686. encodeSLEB128(LineDelta, OS);
  687. }
  688. // Use address delta to adjust address or use absolute address to adjust
  689. // address.
  690. bool SetDelta;
  691. // According to DWARF spec., the DW_LNS_fixed_advance_pc opcode takes a
  692. // single uhalf (unencoded) operand. So, the maximum value of AddrDelta
  693. // is 65535. We set a conservative upper bound for it for relaxation.
  694. if (AddrDelta > 60000) {
  695. const MCAsmInfo *asmInfo = Context.getAsmInfo();
  696. unsigned AddrSize = asmInfo->getCodePointerSize();
  697. OS << char(dwarf::DW_LNS_extended_op);
  698. encodeULEB128(1 + AddrSize, OS);
  699. OS << char(dwarf::DW_LNE_set_address);
  700. // Generate fixup for the address.
  701. Offset = OS.tell();
  702. Size = AddrSize;
  703. SetDelta = false;
  704. OS.write_zeros(AddrSize);
  705. } else {
  706. OS << char(dwarf::DW_LNS_fixed_advance_pc);
  707. // Generate fixup for 2-bytes address delta.
  708. Offset = OS.tell();
  709. Size = 2;
  710. SetDelta = true;
  711. OS << char(0);
  712. OS << char(0);
  713. }
  714. if (LineDelta == INT64_MAX) {
  715. OS << char(dwarf::DW_LNS_extended_op);
  716. OS << char(1);
  717. OS << char(dwarf::DW_LNE_end_sequence);
  718. } else {
  719. OS << char(dwarf::DW_LNS_copy);
  720. }
  721. return std::make_tuple(Offset, Size, SetDelta);
  722. }
  723. // Utility function to write a tuple for .debug_abbrev.
  724. static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
  725. MCOS->emitULEB128IntValue(Name);
  726. MCOS->emitULEB128IntValue(Form);
  727. }
  728. // When generating dwarf for assembly source files this emits
  729. // the data for .debug_abbrev section which contains three DIEs.
  730. static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
  731. MCContext &context = MCOS->getContext();
  732. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
  733. // DW_TAG_compile_unit DIE abbrev (1).
  734. MCOS->emitULEB128IntValue(1);
  735. MCOS->emitULEB128IntValue(dwarf::DW_TAG_compile_unit);
  736. MCOS->emitInt8(dwarf::DW_CHILDREN_yes);
  737. dwarf::Form SecOffsetForm =
  738. context.getDwarfVersion() >= 4
  739. ? dwarf::DW_FORM_sec_offset
  740. : (context.getDwarfFormat() == dwarf::DWARF64 ? dwarf::DW_FORM_data8
  741. : dwarf::DW_FORM_data4);
  742. EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, SecOffsetForm);
  743. if (context.getGenDwarfSectionSyms().size() > 1 &&
  744. context.getDwarfVersion() >= 3) {
  745. EmitAbbrev(MCOS, dwarf::DW_AT_ranges, SecOffsetForm);
  746. } else {
  747. EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
  748. EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
  749. }
  750. EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
  751. if (!context.getCompilationDir().empty())
  752. EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
  753. StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
  754. if (!DwarfDebugFlags.empty())
  755. EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
  756. EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
  757. EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
  758. EmitAbbrev(MCOS, 0, 0);
  759. // DW_TAG_label DIE abbrev (2).
  760. MCOS->emitULEB128IntValue(2);
  761. MCOS->emitULEB128IntValue(dwarf::DW_TAG_label);
  762. MCOS->emitInt8(dwarf::DW_CHILDREN_no);
  763. EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
  764. EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
  765. EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
  766. EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
  767. EmitAbbrev(MCOS, 0, 0);
  768. // Terminate the abbreviations for this compilation unit.
  769. MCOS->emitInt8(0);
  770. }
  771. // When generating dwarf for assembly source files this emits the data for
  772. // .debug_aranges section. This section contains a header and a table of pairs
  773. // of PointerSize'ed values for the address and size of section(s) with line
  774. // table entries.
  775. static void EmitGenDwarfAranges(MCStreamer *MCOS,
  776. const MCSymbol *InfoSectionSymbol) {
  777. MCContext &context = MCOS->getContext();
  778. auto &Sections = context.getGenDwarfSectionSyms();
  779. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
  780. unsigned UnitLengthBytes =
  781. dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
  782. unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
  783. // This will be the length of the .debug_aranges section, first account for
  784. // the size of each item in the header (see below where we emit these items).
  785. int Length = UnitLengthBytes + 2 + OffsetSize + 1 + 1;
  786. // Figure the padding after the header before the table of address and size
  787. // pairs who's values are PointerSize'ed.
  788. const MCAsmInfo *asmInfo = context.getAsmInfo();
  789. int AddrSize = asmInfo->getCodePointerSize();
  790. int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
  791. if (Pad == 2 * AddrSize)
  792. Pad = 0;
  793. Length += Pad;
  794. // Add the size of the pair of PointerSize'ed values for the address and size
  795. // of each section we have in the table.
  796. Length += 2 * AddrSize * Sections.size();
  797. // And the pair of terminating zeros.
  798. Length += 2 * AddrSize;
  799. // Emit the header for this section.
  800. if (context.getDwarfFormat() == dwarf::DWARF64)
  801. // The DWARF64 mark.
  802. MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
  803. // The 4 (8 for DWARF64) byte length not including the length of the unit
  804. // length field itself.
  805. MCOS->emitIntValue(Length - UnitLengthBytes, OffsetSize);
  806. // The 2 byte version, which is 2.
  807. MCOS->emitInt16(2);
  808. // The 4 (8 for DWARF64) byte offset to the compile unit in the .debug_info
  809. // from the start of the .debug_info.
  810. if (InfoSectionSymbol)
  811. MCOS->emitSymbolValue(InfoSectionSymbol, OffsetSize,
  812. asmInfo->needsDwarfSectionOffsetDirective());
  813. else
  814. MCOS->emitIntValue(0, OffsetSize);
  815. // The 1 byte size of an address.
  816. MCOS->emitInt8(AddrSize);
  817. // The 1 byte size of a segment descriptor, we use a value of zero.
  818. MCOS->emitInt8(0);
  819. // Align the header with the padding if needed, before we put out the table.
  820. for(int i = 0; i < Pad; i++)
  821. MCOS->emitInt8(0);
  822. // Now emit the table of pairs of PointerSize'ed values for the section
  823. // addresses and sizes.
  824. for (MCSection *Sec : Sections) {
  825. const MCSymbol *StartSymbol = Sec->getBeginSymbol();
  826. MCSymbol *EndSymbol = Sec->getEndSymbol(context);
  827. assert(StartSymbol && "StartSymbol must not be NULL");
  828. assert(EndSymbol && "EndSymbol must not be NULL");
  829. const MCExpr *Addr = MCSymbolRefExpr::create(
  830. StartSymbol, MCSymbolRefExpr::VK_None, context);
  831. const MCExpr *Size =
  832. makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
  833. MCOS->emitValue(Addr, AddrSize);
  834. emitAbsValue(*MCOS, Size, AddrSize);
  835. }
  836. // And finally the pair of terminating zeros.
  837. MCOS->emitIntValue(0, AddrSize);
  838. MCOS->emitIntValue(0, AddrSize);
  839. }
  840. // When generating dwarf for assembly source files this emits the data for
  841. // .debug_info section which contains three parts. The header, the compile_unit
  842. // DIE and a list of label DIEs.
  843. static void EmitGenDwarfInfo(MCStreamer *MCOS,
  844. const MCSymbol *AbbrevSectionSymbol,
  845. const MCSymbol *LineSectionSymbol,
  846. const MCSymbol *RangesSymbol) {
  847. MCContext &context = MCOS->getContext();
  848. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
  849. // Create a symbol at the start and end of this section used in here for the
  850. // expression to calculate the length in the header.
  851. MCSymbol *InfoStart = context.createTempSymbol();
  852. MCOS->emitLabel(InfoStart);
  853. MCSymbol *InfoEnd = context.createTempSymbol();
  854. // First part: the header.
  855. unsigned UnitLengthBytes =
  856. dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
  857. unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
  858. if (context.getDwarfFormat() == dwarf::DWARF64)
  859. // Emit DWARF64 mark.
  860. MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
  861. // The 4 (8 for DWARF64) byte total length of the information for this
  862. // compilation unit, not including the unit length field itself.
  863. const MCExpr *Length =
  864. makeEndMinusStartExpr(context, *InfoStart, *InfoEnd, UnitLengthBytes);
  865. emitAbsValue(*MCOS, Length, OffsetSize);
  866. // The 2 byte DWARF version.
  867. MCOS->emitInt16(context.getDwarfVersion());
  868. // The DWARF v5 header has unit type, address size, abbrev offset.
  869. // Earlier versions have abbrev offset, address size.
  870. const MCAsmInfo &AsmInfo = *context.getAsmInfo();
  871. int AddrSize = AsmInfo.getCodePointerSize();
  872. if (context.getDwarfVersion() >= 5) {
  873. MCOS->emitInt8(dwarf::DW_UT_compile);
  874. MCOS->emitInt8(AddrSize);
  875. }
  876. // The 4 (8 for DWARF64) byte offset to the debug abbrevs from the start of
  877. // the .debug_abbrev.
  878. if (AbbrevSectionSymbol)
  879. MCOS->emitSymbolValue(AbbrevSectionSymbol, OffsetSize,
  880. AsmInfo.needsDwarfSectionOffsetDirective());
  881. else
  882. // Since the abbrevs are at the start of the section, the offset is zero.
  883. MCOS->emitIntValue(0, OffsetSize);
  884. if (context.getDwarfVersion() <= 4)
  885. MCOS->emitInt8(AddrSize);
  886. // Second part: the compile_unit DIE.
  887. // The DW_TAG_compile_unit DIE abbrev (1).
  888. MCOS->emitULEB128IntValue(1);
  889. // DW_AT_stmt_list, a 4 (8 for DWARF64) byte offset from the start of the
  890. // .debug_line section.
  891. if (LineSectionSymbol)
  892. MCOS->emitSymbolValue(LineSectionSymbol, OffsetSize,
  893. AsmInfo.needsDwarfSectionOffsetDirective());
  894. else
  895. // The line table is at the start of the section, so the offset is zero.
  896. MCOS->emitIntValue(0, OffsetSize);
  897. if (RangesSymbol) {
  898. // There are multiple sections containing code, so we must use
  899. // .debug_ranges/.debug_rnglists. AT_ranges, the 4/8 byte offset from the
  900. // start of the .debug_ranges/.debug_rnglists.
  901. MCOS->emitSymbolValue(RangesSymbol, OffsetSize);
  902. } else {
  903. // If we only have one non-empty code section, we can use the simpler
  904. // AT_low_pc and AT_high_pc attributes.
  905. // Find the first (and only) non-empty text section
  906. auto &Sections = context.getGenDwarfSectionSyms();
  907. const auto TextSection = Sections.begin();
  908. assert(TextSection != Sections.end() && "No text section found");
  909. MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
  910. MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);
  911. assert(StartSymbol && "StartSymbol must not be NULL");
  912. assert(EndSymbol && "EndSymbol must not be NULL");
  913. // AT_low_pc, the first address of the default .text section.
  914. const MCExpr *Start = MCSymbolRefExpr::create(
  915. StartSymbol, MCSymbolRefExpr::VK_None, context);
  916. MCOS->emitValue(Start, AddrSize);
  917. // AT_high_pc, the last address of the default .text section.
  918. const MCExpr *End = MCSymbolRefExpr::create(
  919. EndSymbol, MCSymbolRefExpr::VK_None, context);
  920. MCOS->emitValue(End, AddrSize);
  921. }
  922. // AT_name, the name of the source file. Reconstruct from the first directory
  923. // and file table entries.
  924. const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
  925. if (MCDwarfDirs.size() > 0) {
  926. MCOS->emitBytes(MCDwarfDirs[0]);
  927. MCOS->emitBytes(sys::path::get_separator());
  928. }
  929. const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = context.getMCDwarfFiles();
  930. // MCDwarfFiles might be empty if we have an empty source file.
  931. // If it's not empty, [0] is unused and [1] is the first actual file.
  932. assert(MCDwarfFiles.empty() || MCDwarfFiles.size() >= 2);
  933. const MCDwarfFile &RootFile =
  934. MCDwarfFiles.empty()
  935. ? context.getMCDwarfLineTable(/*CUID=*/0).getRootFile()
  936. : MCDwarfFiles[1];
  937. MCOS->emitBytes(RootFile.Name);
  938. MCOS->emitInt8(0); // NULL byte to terminate the string.
  939. // AT_comp_dir, the working directory the assembly was done in.
  940. if (!context.getCompilationDir().empty()) {
  941. MCOS->emitBytes(context.getCompilationDir());
  942. MCOS->emitInt8(0); // NULL byte to terminate the string.
  943. }
  944. // AT_APPLE_flags, the command line arguments of the assembler tool.
  945. StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
  946. if (!DwarfDebugFlags.empty()){
  947. MCOS->emitBytes(DwarfDebugFlags);
  948. MCOS->emitInt8(0); // NULL byte to terminate the string.
  949. }
  950. // AT_producer, the version of the assembler tool.
  951. StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
  952. if (!DwarfDebugProducer.empty())
  953. MCOS->emitBytes(DwarfDebugProducer);
  954. else
  955. MCOS->emitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
  956. MCOS->emitInt8(0); // NULL byte to terminate the string.
  957. // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
  958. // draft has no standard code for assembler.
  959. MCOS->emitInt16(dwarf::DW_LANG_Mips_Assembler);
  960. // Third part: the list of label DIEs.
  961. // Loop on saved info for dwarf labels and create the DIEs for them.
  962. const std::vector<MCGenDwarfLabelEntry> &Entries =
  963. MCOS->getContext().getMCGenDwarfLabelEntries();
  964. for (const auto &Entry : Entries) {
  965. // The DW_TAG_label DIE abbrev (2).
  966. MCOS->emitULEB128IntValue(2);
  967. // AT_name, of the label without any leading underbar.
  968. MCOS->emitBytes(Entry.getName());
  969. MCOS->emitInt8(0); // NULL byte to terminate the string.
  970. // AT_decl_file, index into the file table.
  971. MCOS->emitInt32(Entry.getFileNumber());
  972. // AT_decl_line, source line number.
  973. MCOS->emitInt32(Entry.getLineNumber());
  974. // AT_low_pc, start address of the label.
  975. const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
  976. MCSymbolRefExpr::VK_None, context);
  977. MCOS->emitValue(AT_low_pc, AddrSize);
  978. }
  979. // Add the NULL DIE terminating the Compile Unit DIE's.
  980. MCOS->emitInt8(0);
  981. // Now set the value of the symbol at the end of the info section.
  982. MCOS->emitLabel(InfoEnd);
  983. }
  984. // When generating dwarf for assembly source files this emits the data for
  985. // .debug_ranges section. We only emit one range list, which spans all of the
  986. // executable sections of this file.
  987. static MCSymbol *emitGenDwarfRanges(MCStreamer *MCOS) {
  988. MCContext &context = MCOS->getContext();
  989. auto &Sections = context.getGenDwarfSectionSyms();
  990. const MCAsmInfo *AsmInfo = context.getAsmInfo();
  991. int AddrSize = AsmInfo->getCodePointerSize();
  992. MCSymbol *RangesSymbol;
  993. if (MCOS->getContext().getDwarfVersion() >= 5) {
  994. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRnglistsSection());
  995. MCSymbol *EndSymbol = mcdwarf::emitListsTableHeaderStart(*MCOS);
  996. MCOS->AddComment("Offset entry count");
  997. MCOS->emitInt32(0);
  998. RangesSymbol = context.createTempSymbol("debug_rnglist0_start");
  999. MCOS->emitLabel(RangesSymbol);
  1000. for (MCSection *Sec : Sections) {
  1001. const MCSymbol *StartSymbol = Sec->getBeginSymbol();
  1002. const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
  1003. const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
  1004. StartSymbol, MCSymbolRefExpr::VK_None, context);
  1005. const MCExpr *SectionSize =
  1006. makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
  1007. MCOS->emitInt8(dwarf::DW_RLE_start_length);
  1008. MCOS->emitValue(SectionStartAddr, AddrSize);
  1009. MCOS->emitULEB128Value(SectionSize);
  1010. }
  1011. MCOS->emitInt8(dwarf::DW_RLE_end_of_list);
  1012. MCOS->emitLabel(EndSymbol);
  1013. } else {
  1014. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
  1015. RangesSymbol = context.createTempSymbol("debug_ranges_start");
  1016. MCOS->emitLabel(RangesSymbol);
  1017. for (MCSection *Sec : Sections) {
  1018. const MCSymbol *StartSymbol = Sec->getBeginSymbol();
  1019. const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
  1020. // Emit a base address selection entry for the section start.
  1021. const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
  1022. StartSymbol, MCSymbolRefExpr::VK_None, context);
  1023. MCOS->emitFill(AddrSize, 0xFF);
  1024. MCOS->emitValue(SectionStartAddr, AddrSize);
  1025. // Emit a range list entry spanning this section.
  1026. const MCExpr *SectionSize =
  1027. makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
  1028. MCOS->emitIntValue(0, AddrSize);
  1029. emitAbsValue(*MCOS, SectionSize, AddrSize);
  1030. }
  1031. // Emit end of list entry
  1032. MCOS->emitIntValue(0, AddrSize);
  1033. MCOS->emitIntValue(0, AddrSize);
  1034. }
  1035. return RangesSymbol;
  1036. }
  1037. //
  1038. // When generating dwarf for assembly source files this emits the Dwarf
  1039. // sections.
  1040. //
  1041. void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
  1042. MCContext &context = MCOS->getContext();
  1043. // Create the dwarf sections in this order (.debug_line already created).
  1044. const MCAsmInfo *AsmInfo = context.getAsmInfo();
  1045. bool CreateDwarfSectionSymbols =
  1046. AsmInfo->doesDwarfUseRelocationsAcrossSections();
  1047. MCSymbol *LineSectionSymbol = nullptr;
  1048. if (CreateDwarfSectionSymbols)
  1049. LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
  1050. MCSymbol *AbbrevSectionSymbol = nullptr;
  1051. MCSymbol *InfoSectionSymbol = nullptr;
  1052. MCSymbol *RangesSymbol = nullptr;
  1053. // Create end symbols for each section, and remove empty sections
  1054. MCOS->getContext().finalizeDwarfSections(*MCOS);
  1055. // If there are no sections to generate debug info for, we don't need
  1056. // to do anything
  1057. if (MCOS->getContext().getGenDwarfSectionSyms().empty())
  1058. return;
  1059. // We only use the .debug_ranges section if we have multiple code sections,
  1060. // and we are emitting a DWARF version which supports it.
  1061. const bool UseRangesSection =
  1062. MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
  1063. MCOS->getContext().getDwarfVersion() >= 3;
  1064. CreateDwarfSectionSymbols |= UseRangesSection;
  1065. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
  1066. if (CreateDwarfSectionSymbols) {
  1067. InfoSectionSymbol = context.createTempSymbol();
  1068. MCOS->emitLabel(InfoSectionSymbol);
  1069. }
  1070. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
  1071. if (CreateDwarfSectionSymbols) {
  1072. AbbrevSectionSymbol = context.createTempSymbol();
  1073. MCOS->emitLabel(AbbrevSectionSymbol);
  1074. }
  1075. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
  1076. // Output the data for .debug_aranges section.
  1077. EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
  1078. if (UseRangesSection) {
  1079. RangesSymbol = emitGenDwarfRanges(MCOS);
  1080. assert(RangesSymbol);
  1081. }
  1082. // Output the data for .debug_abbrev section.
  1083. EmitGenDwarfAbbrev(MCOS);
  1084. // Output the data for .debug_info section.
  1085. EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, RangesSymbol);
  1086. }
  1087. //
  1088. // When generating dwarf for assembly source files this is called when symbol
  1089. // for a label is created. If this symbol is not a temporary and is in the
  1090. // section that dwarf is being generated for, save the needed info to create
  1091. // a dwarf label.
  1092. //
  1093. void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
  1094. SourceMgr &SrcMgr, SMLoc &Loc) {
  1095. // We won't create dwarf labels for temporary symbols.
  1096. if (Symbol->isTemporary())
  1097. return;
  1098. MCContext &context = MCOS->getContext();
  1099. // We won't create dwarf labels for symbols in sections that we are not
  1100. // generating debug info for.
  1101. if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSectionOnly()))
  1102. return;
  1103. // The dwarf label's name does not have the symbol name's leading
  1104. // underbar if any.
  1105. StringRef Name = Symbol->getName();
  1106. if (Name.startswith("_"))
  1107. Name = Name.substr(1, Name.size()-1);
  1108. // Get the dwarf file number to be used for the dwarf label.
  1109. unsigned FileNumber = context.getGenDwarfFileNumber();
  1110. // Finding the line number is the expensive part which is why we just don't
  1111. // pass it in as for some symbols we won't create a dwarf label.
  1112. unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
  1113. unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
  1114. // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
  1115. // values so that they don't have things like an ARM thumb bit from the
  1116. // original symbol. So when used they won't get a low bit set after
  1117. // relocation.
  1118. MCSymbol *Label = context.createTempSymbol();
  1119. MCOS->emitLabel(Label);
  1120. // Create and entry for the info and add it to the other entries.
  1121. MCOS->getContext().addMCGenDwarfLabelEntry(
  1122. MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
  1123. }
  1124. static int getDataAlignmentFactor(MCStreamer &streamer) {
  1125. MCContext &context = streamer.getContext();
  1126. const MCAsmInfo *asmInfo = context.getAsmInfo();
  1127. int size = asmInfo->getCalleeSaveStackSlotSize();
  1128. if (asmInfo->isStackGrowthDirectionUp())
  1129. return size;
  1130. else
  1131. return -size;
  1132. }
  1133. static unsigned getSizeForEncoding(MCStreamer &streamer,
  1134. unsigned symbolEncoding) {
  1135. MCContext &context = streamer.getContext();
  1136. unsigned format = symbolEncoding & 0x0f;
  1137. switch (format) {
  1138. default: llvm_unreachable("Unknown Encoding");
  1139. case dwarf::DW_EH_PE_absptr:
  1140. case dwarf::DW_EH_PE_signed:
  1141. return context.getAsmInfo()->getCodePointerSize();
  1142. case dwarf::DW_EH_PE_udata2:
  1143. case dwarf::DW_EH_PE_sdata2:
  1144. return 2;
  1145. case dwarf::DW_EH_PE_udata4:
  1146. case dwarf::DW_EH_PE_sdata4:
  1147. return 4;
  1148. case dwarf::DW_EH_PE_udata8:
  1149. case dwarf::DW_EH_PE_sdata8:
  1150. return 8;
  1151. }
  1152. }
  1153. static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
  1154. unsigned symbolEncoding, bool isEH) {
  1155. MCContext &context = streamer.getContext();
  1156. const MCAsmInfo *asmInfo = context.getAsmInfo();
  1157. const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
  1158. symbolEncoding,
  1159. streamer);
  1160. unsigned size = getSizeForEncoding(streamer, symbolEncoding);
  1161. if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
  1162. emitAbsValue(streamer, v, size);
  1163. else
  1164. streamer.emitValue(v, size);
  1165. }
  1166. static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
  1167. unsigned symbolEncoding) {
  1168. MCContext &context = streamer.getContext();
  1169. const MCAsmInfo *asmInfo = context.getAsmInfo();
  1170. const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
  1171. symbolEncoding,
  1172. streamer);
  1173. unsigned size = getSizeForEncoding(streamer, symbolEncoding);
  1174. streamer.emitValue(v, size);
  1175. }
  1176. namespace {
  1177. class FrameEmitterImpl {
  1178. int CFAOffset = 0;
  1179. int InitialCFAOffset = 0;
  1180. bool IsEH;
  1181. MCObjectStreamer &Streamer;
  1182. public:
  1183. FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer)
  1184. : IsEH(IsEH), Streamer(Streamer) {}
  1185. /// Emit the unwind information in a compact way.
  1186. void EmitCompactUnwind(const MCDwarfFrameInfo &frame);
  1187. const MCSymbol &EmitCIE(const MCDwarfFrameInfo &F);
  1188. void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame,
  1189. bool LastInSection, const MCSymbol &SectionStart);
  1190. void emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
  1191. MCSymbol *BaseLabel);
  1192. void emitCFIInstruction(const MCCFIInstruction &Instr);
  1193. };
  1194. } // end anonymous namespace
  1195. static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
  1196. Streamer.emitInt8(Encoding);
  1197. }
  1198. void FrameEmitterImpl::emitCFIInstruction(const MCCFIInstruction &Instr) {
  1199. int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
  1200. auto *MRI = Streamer.getContext().getRegisterInfo();
  1201. switch (Instr.getOperation()) {
  1202. case MCCFIInstruction::OpRegister: {
  1203. unsigned Reg1 = Instr.getRegister();
  1204. unsigned Reg2 = Instr.getRegister2();
  1205. if (!IsEH) {
  1206. Reg1 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg1);
  1207. Reg2 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg2);
  1208. }
  1209. Streamer.emitInt8(dwarf::DW_CFA_register);
  1210. Streamer.emitULEB128IntValue(Reg1);
  1211. Streamer.emitULEB128IntValue(Reg2);
  1212. return;
  1213. }
  1214. case MCCFIInstruction::OpWindowSave:
  1215. Streamer.emitInt8(dwarf::DW_CFA_GNU_window_save);
  1216. return;
  1217. case MCCFIInstruction::OpNegateRAState:
  1218. Streamer.emitInt8(dwarf::DW_CFA_AARCH64_negate_ra_state);
  1219. return;
  1220. case MCCFIInstruction::OpUndefined: {
  1221. unsigned Reg = Instr.getRegister();
  1222. Streamer.emitInt8(dwarf::DW_CFA_undefined);
  1223. Streamer.emitULEB128IntValue(Reg);
  1224. return;
  1225. }
  1226. case MCCFIInstruction::OpAdjustCfaOffset:
  1227. case MCCFIInstruction::OpDefCfaOffset: {
  1228. const bool IsRelative =
  1229. Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
  1230. Streamer.emitInt8(dwarf::DW_CFA_def_cfa_offset);
  1231. if (IsRelative)
  1232. CFAOffset += Instr.getOffset();
  1233. else
  1234. CFAOffset = Instr.getOffset();
  1235. Streamer.emitULEB128IntValue(CFAOffset);
  1236. return;
  1237. }
  1238. case MCCFIInstruction::OpDefCfa: {
  1239. unsigned Reg = Instr.getRegister();
  1240. if (!IsEH)
  1241. Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
  1242. Streamer.emitInt8(dwarf::DW_CFA_def_cfa);
  1243. Streamer.emitULEB128IntValue(Reg);
  1244. CFAOffset = Instr.getOffset();
  1245. Streamer.emitULEB128IntValue(CFAOffset);
  1246. return;
  1247. }
  1248. case MCCFIInstruction::OpDefCfaRegister: {
  1249. unsigned Reg = Instr.getRegister();
  1250. if (!IsEH)
  1251. Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
  1252. Streamer.emitInt8(dwarf::DW_CFA_def_cfa_register);
  1253. Streamer.emitULEB128IntValue(Reg);
  1254. return;
  1255. }
  1256. case MCCFIInstruction::OpOffset:
  1257. case MCCFIInstruction::OpRelOffset: {
  1258. const bool IsRelative =
  1259. Instr.getOperation() == MCCFIInstruction::OpRelOffset;
  1260. unsigned Reg = Instr.getRegister();
  1261. if (!IsEH)
  1262. Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
  1263. int Offset = Instr.getOffset();
  1264. if (IsRelative)
  1265. Offset -= CFAOffset;
  1266. Offset = Offset / dataAlignmentFactor;
  1267. if (Offset < 0) {
  1268. Streamer.emitInt8(dwarf::DW_CFA_offset_extended_sf);
  1269. Streamer.emitULEB128IntValue(Reg);
  1270. Streamer.emitSLEB128IntValue(Offset);
  1271. } else if (Reg < 64) {
  1272. Streamer.emitInt8(dwarf::DW_CFA_offset + Reg);
  1273. Streamer.emitULEB128IntValue(Offset);
  1274. } else {
  1275. Streamer.emitInt8(dwarf::DW_CFA_offset_extended);
  1276. Streamer.emitULEB128IntValue(Reg);
  1277. Streamer.emitULEB128IntValue(Offset);
  1278. }
  1279. return;
  1280. }
  1281. case MCCFIInstruction::OpRememberState:
  1282. Streamer.emitInt8(dwarf::DW_CFA_remember_state);
  1283. return;
  1284. case MCCFIInstruction::OpRestoreState:
  1285. Streamer.emitInt8(dwarf::DW_CFA_restore_state);
  1286. return;
  1287. case MCCFIInstruction::OpSameValue: {
  1288. unsigned Reg = Instr.getRegister();
  1289. Streamer.emitInt8(dwarf::DW_CFA_same_value);
  1290. Streamer.emitULEB128IntValue(Reg);
  1291. return;
  1292. }
  1293. case MCCFIInstruction::OpRestore: {
  1294. unsigned Reg = Instr.getRegister();
  1295. if (!IsEH)
  1296. Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
  1297. if (Reg < 64) {
  1298. Streamer.emitInt8(dwarf::DW_CFA_restore | Reg);
  1299. } else {
  1300. Streamer.emitInt8(dwarf::DW_CFA_restore_extended);
  1301. Streamer.emitULEB128IntValue(Reg);
  1302. }
  1303. return;
  1304. }
  1305. case MCCFIInstruction::OpGnuArgsSize:
  1306. Streamer.emitInt8(dwarf::DW_CFA_GNU_args_size);
  1307. Streamer.emitULEB128IntValue(Instr.getOffset());
  1308. return;
  1309. case MCCFIInstruction::OpEscape:
  1310. Streamer.emitBytes(Instr.getValues());
  1311. return;
  1312. }
  1313. llvm_unreachable("Unhandled case in switch");
  1314. }
  1315. /// Emit frame instructions to describe the layout of the frame.
  1316. void FrameEmitterImpl::emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
  1317. MCSymbol *BaseLabel) {
  1318. for (const MCCFIInstruction &Instr : Instrs) {
  1319. MCSymbol *Label = Instr.getLabel();
  1320. // Throw out move if the label is invalid.
  1321. if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
  1322. // Advance row if new location.
  1323. if (BaseLabel && Label) {
  1324. MCSymbol *ThisSym = Label;
  1325. if (ThisSym != BaseLabel) {
  1326. Streamer.emitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
  1327. BaseLabel = ThisSym;
  1328. }
  1329. }
  1330. emitCFIInstruction(Instr);
  1331. }
  1332. }
  1333. /// Emit the unwind information in a compact way.
  1334. void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) {
  1335. MCContext &Context = Streamer.getContext();
  1336. const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
  1337. // range-start range-length compact-unwind-enc personality-func lsda
  1338. // _foo LfooEnd-_foo 0x00000023 0 0
  1339. // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
  1340. //
  1341. // .section __LD,__compact_unwind,regular,debug
  1342. //
  1343. // # compact unwind for _foo
  1344. // .quad _foo
  1345. // .set L1,LfooEnd-_foo
  1346. // .long L1
  1347. // .long 0x01010001
  1348. // .quad 0
  1349. // .quad 0
  1350. //
  1351. // # compact unwind for _bar
  1352. // .quad _bar
  1353. // .set L2,LbarEnd-_bar
  1354. // .long L2
  1355. // .long 0x01020011
  1356. // .quad __gxx_personality
  1357. // .quad except_tab1
  1358. uint32_t Encoding = Frame.CompactUnwindEncoding;
  1359. if (!Encoding) return;
  1360. bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
  1361. // The encoding needs to know we have an LSDA.
  1362. if (!DwarfEHFrameOnly && Frame.Lsda)
  1363. Encoding |= 0x40000000;
  1364. // Range Start
  1365. unsigned FDEEncoding = MOFI->getFDEEncoding();
  1366. unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
  1367. Streamer.emitSymbolValue(Frame.Begin, Size);
  1368. // Range Length
  1369. const MCExpr *Range =
  1370. makeEndMinusStartExpr(Context, *Frame.Begin, *Frame.End, 0);
  1371. emitAbsValue(Streamer, Range, 4);
  1372. // Compact Encoding
  1373. Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
  1374. Streamer.emitIntValue(Encoding, Size);
  1375. // Personality Function
  1376. Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
  1377. if (!DwarfEHFrameOnly && Frame.Personality)
  1378. Streamer.emitSymbolValue(Frame.Personality, Size);
  1379. else
  1380. Streamer.emitIntValue(0, Size); // No personality fn
  1381. // LSDA
  1382. Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
  1383. if (!DwarfEHFrameOnly && Frame.Lsda)
  1384. Streamer.emitSymbolValue(Frame.Lsda, Size);
  1385. else
  1386. Streamer.emitIntValue(0, Size); // No LSDA
  1387. }
  1388. static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
  1389. if (IsEH)
  1390. return 1;
  1391. switch (DwarfVersion) {
  1392. case 2:
  1393. return 1;
  1394. case 3:
  1395. return 3;
  1396. case 4:
  1397. case 5:
  1398. return 4;
  1399. }
  1400. llvm_unreachable("Unknown version");
  1401. }
  1402. const MCSymbol &FrameEmitterImpl::EmitCIE(const MCDwarfFrameInfo &Frame) {
  1403. MCContext &context = Streamer.getContext();
  1404. const MCRegisterInfo *MRI = context.getRegisterInfo();
  1405. const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
  1406. MCSymbol *sectionStart = context.createTempSymbol();
  1407. Streamer.emitLabel(sectionStart);
  1408. MCSymbol *sectionEnd = context.createTempSymbol();
  1409. dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
  1410. unsigned UnitLengthBytes = dwarf::getUnitLengthFieldByteSize(Format);
  1411. unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
  1412. bool IsDwarf64 = Format == dwarf::DWARF64;
  1413. if (IsDwarf64)
  1414. // DWARF64 mark
  1415. Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
  1416. // Length
  1417. const MCExpr *Length = makeEndMinusStartExpr(context, *sectionStart,
  1418. *sectionEnd, UnitLengthBytes);
  1419. emitAbsValue(Streamer, Length, OffsetSize);
  1420. // CIE ID
  1421. uint64_t CIE_ID =
  1422. IsEH ? 0 : (IsDwarf64 ? dwarf::DW64_CIE_ID : dwarf::DW_CIE_ID);
  1423. Streamer.emitIntValue(CIE_ID, OffsetSize);
  1424. // Version
  1425. uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
  1426. Streamer.emitInt8(CIEVersion);
  1427. if (IsEH) {
  1428. SmallString<8> Augmentation;
  1429. Augmentation += "z";
  1430. if (Frame.Personality)
  1431. Augmentation += "P";
  1432. if (Frame.Lsda)
  1433. Augmentation += "L";
  1434. Augmentation += "R";
  1435. if (Frame.IsSignalFrame)
  1436. Augmentation += "S";
  1437. if (Frame.IsBKeyFrame)
  1438. Augmentation += "B";
  1439. Streamer.emitBytes(Augmentation);
  1440. }
  1441. Streamer.emitInt8(0);
  1442. if (CIEVersion >= 4) {
  1443. // Address Size
  1444. Streamer.emitInt8(context.getAsmInfo()->getCodePointerSize());
  1445. // Segment Descriptor Size
  1446. Streamer.emitInt8(0);
  1447. }
  1448. // Code Alignment Factor
  1449. Streamer.emitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
  1450. // Data Alignment Factor
  1451. Streamer.emitSLEB128IntValue(getDataAlignmentFactor(Streamer));
  1452. // Return Address Register
  1453. unsigned RAReg = Frame.RAReg;
  1454. if (RAReg == static_cast<unsigned>(INT_MAX))
  1455. RAReg = MRI->getDwarfRegNum(MRI->getRARegister(), IsEH);
  1456. if (CIEVersion == 1) {
  1457. assert(RAReg <= 255 &&
  1458. "DWARF 2 encodes return_address_register in one byte");
  1459. Streamer.emitInt8(RAReg);
  1460. } else {
  1461. Streamer.emitULEB128IntValue(RAReg);
  1462. }
  1463. // Augmentation Data Length (optional)
  1464. unsigned augmentationLength = 0;
  1465. if (IsEH) {
  1466. if (Frame.Personality) {
  1467. // Personality Encoding
  1468. augmentationLength += 1;
  1469. // Personality
  1470. augmentationLength +=
  1471. getSizeForEncoding(Streamer, Frame.PersonalityEncoding);
  1472. }
  1473. if (Frame.Lsda)
  1474. augmentationLength += 1;
  1475. // Encoding of the FDE pointers
  1476. augmentationLength += 1;
  1477. Streamer.emitULEB128IntValue(augmentationLength);
  1478. // Augmentation Data (optional)
  1479. if (Frame.Personality) {
  1480. // Personality Encoding
  1481. emitEncodingByte(Streamer, Frame.PersonalityEncoding);
  1482. // Personality
  1483. EmitPersonality(Streamer, *Frame.Personality, Frame.PersonalityEncoding);
  1484. }
  1485. if (Frame.Lsda)
  1486. emitEncodingByte(Streamer, Frame.LsdaEncoding);
  1487. // Encoding of the FDE pointers
  1488. emitEncodingByte(Streamer, MOFI->getFDEEncoding());
  1489. }
  1490. // Initial Instructions
  1491. const MCAsmInfo *MAI = context.getAsmInfo();
  1492. if (!Frame.IsSimple) {
  1493. const std::vector<MCCFIInstruction> &Instructions =
  1494. MAI->getInitialFrameState();
  1495. emitCFIInstructions(Instructions, nullptr);
  1496. }
  1497. InitialCFAOffset = CFAOffset;
  1498. // Padding
  1499. Streamer.emitValueToAlignment(IsEH ? 4 : MAI->getCodePointerSize());
  1500. Streamer.emitLabel(sectionEnd);
  1501. return *sectionStart;
  1502. }
  1503. void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart,
  1504. const MCDwarfFrameInfo &frame,
  1505. bool LastInSection,
  1506. const MCSymbol &SectionStart) {
  1507. MCContext &context = Streamer.getContext();
  1508. MCSymbol *fdeStart = context.createTempSymbol();
  1509. MCSymbol *fdeEnd = context.createTempSymbol();
  1510. const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
  1511. CFAOffset = InitialCFAOffset;
  1512. dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
  1513. unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
  1514. if (Format == dwarf::DWARF64)
  1515. // DWARF64 mark
  1516. Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
  1517. // Length
  1518. const MCExpr *Length = makeEndMinusStartExpr(context, *fdeStart, *fdeEnd, 0);
  1519. emitAbsValue(Streamer, Length, OffsetSize);
  1520. Streamer.emitLabel(fdeStart);
  1521. // CIE Pointer
  1522. const MCAsmInfo *asmInfo = context.getAsmInfo();
  1523. if (IsEH) {
  1524. const MCExpr *offset =
  1525. makeEndMinusStartExpr(context, cieStart, *fdeStart, 0);
  1526. emitAbsValue(Streamer, offset, OffsetSize);
  1527. } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
  1528. const MCExpr *offset =
  1529. makeEndMinusStartExpr(context, SectionStart, cieStart, 0);
  1530. emitAbsValue(Streamer, offset, OffsetSize);
  1531. } else {
  1532. Streamer.emitSymbolValue(&cieStart, OffsetSize,
  1533. asmInfo->needsDwarfSectionOffsetDirective());
  1534. }
  1535. // PC Begin
  1536. unsigned PCEncoding =
  1537. IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
  1538. unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding);
  1539. emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH);
  1540. // PC Range
  1541. const MCExpr *Range =
  1542. makeEndMinusStartExpr(context, *frame.Begin, *frame.End, 0);
  1543. emitAbsValue(Streamer, Range, PCSize);
  1544. if (IsEH) {
  1545. // Augmentation Data Length
  1546. unsigned augmentationLength = 0;
  1547. if (frame.Lsda)
  1548. augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding);
  1549. Streamer.emitULEB128IntValue(augmentationLength);
  1550. // Augmentation Data
  1551. if (frame.Lsda)
  1552. emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true);
  1553. }
  1554. // Call Frame Instructions
  1555. emitCFIInstructions(frame.Instructions, frame.Begin);
  1556. // Padding
  1557. // The size of a .eh_frame section has to be a multiple of the alignment
  1558. // since a null CIE is interpreted as the end. Old systems overaligned
  1559. // .eh_frame, so we do too and account for it in the last FDE.
  1560. unsigned Align = LastInSection ? asmInfo->getCodePointerSize() : PCSize;
  1561. Streamer.emitValueToAlignment(Align);
  1562. Streamer.emitLabel(fdeEnd);
  1563. }
  1564. namespace {
  1565. struct CIEKey {
  1566. static const CIEKey getEmptyKey() {
  1567. return CIEKey(nullptr, 0, -1, false, false, static_cast<unsigned>(INT_MAX),
  1568. false);
  1569. }
  1570. static const CIEKey getTombstoneKey() {
  1571. return CIEKey(nullptr, -1, 0, false, false, static_cast<unsigned>(INT_MAX),
  1572. false);
  1573. }
  1574. CIEKey(const MCSymbol *Personality, unsigned PersonalityEncoding,
  1575. unsigned LSDAEncoding, bool IsSignalFrame, bool IsSimple,
  1576. unsigned RAReg, bool IsBKeyFrame)
  1577. : Personality(Personality), PersonalityEncoding(PersonalityEncoding),
  1578. LsdaEncoding(LSDAEncoding), IsSignalFrame(IsSignalFrame),
  1579. IsSimple(IsSimple), RAReg(RAReg), IsBKeyFrame(IsBKeyFrame) {}
  1580. explicit CIEKey(const MCDwarfFrameInfo &Frame)
  1581. : Personality(Frame.Personality),
  1582. PersonalityEncoding(Frame.PersonalityEncoding),
  1583. LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame),
  1584. IsSimple(Frame.IsSimple), RAReg(Frame.RAReg),
  1585. IsBKeyFrame(Frame.IsBKeyFrame) {}
  1586. StringRef PersonalityName() const {
  1587. if (!Personality)
  1588. return StringRef();
  1589. return Personality->getName();
  1590. }
  1591. bool operator<(const CIEKey &Other) const {
  1592. return std::make_tuple(PersonalityName(), PersonalityEncoding, LsdaEncoding,
  1593. IsSignalFrame, IsSimple, RAReg) <
  1594. std::make_tuple(Other.PersonalityName(), Other.PersonalityEncoding,
  1595. Other.LsdaEncoding, Other.IsSignalFrame,
  1596. Other.IsSimple, Other.RAReg);
  1597. }
  1598. const MCSymbol *Personality;
  1599. unsigned PersonalityEncoding;
  1600. unsigned LsdaEncoding;
  1601. bool IsSignalFrame;
  1602. bool IsSimple;
  1603. unsigned RAReg;
  1604. bool IsBKeyFrame;
  1605. };
  1606. } // end anonymous namespace
  1607. namespace llvm {
  1608. template <> struct DenseMapInfo<CIEKey> {
  1609. static CIEKey getEmptyKey() { return CIEKey::getEmptyKey(); }
  1610. static CIEKey getTombstoneKey() { return CIEKey::getTombstoneKey(); }
  1611. static unsigned getHashValue(const CIEKey &Key) {
  1612. return static_cast<unsigned>(hash_combine(
  1613. Key.Personality, Key.PersonalityEncoding, Key.LsdaEncoding,
  1614. Key.IsSignalFrame, Key.IsSimple, Key.RAReg, Key.IsBKeyFrame));
  1615. }
  1616. static bool isEqual(const CIEKey &LHS, const CIEKey &RHS) {
  1617. return LHS.Personality == RHS.Personality &&
  1618. LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
  1619. LHS.LsdaEncoding == RHS.LsdaEncoding &&
  1620. LHS.IsSignalFrame == RHS.IsSignalFrame &&
  1621. LHS.IsSimple == RHS.IsSimple && LHS.RAReg == RHS.RAReg &&
  1622. LHS.IsBKeyFrame == RHS.IsBKeyFrame;
  1623. }
  1624. };
  1625. } // end namespace llvm
  1626. void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
  1627. bool IsEH) {
  1628. Streamer.generateCompactUnwindEncodings(MAB);
  1629. MCContext &Context = Streamer.getContext();
  1630. const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
  1631. const MCAsmInfo *AsmInfo = Context.getAsmInfo();
  1632. FrameEmitterImpl Emitter(IsEH, Streamer);
  1633. ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
  1634. // Emit the compact unwind info if available.
  1635. bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
  1636. if (IsEH && MOFI->getCompactUnwindSection()) {
  1637. bool SectionEmitted = false;
  1638. for (const MCDwarfFrameInfo &Frame : FrameArray) {
  1639. if (Frame.CompactUnwindEncoding == 0) continue;
  1640. if (!SectionEmitted) {
  1641. Streamer.SwitchSection(MOFI->getCompactUnwindSection());
  1642. Streamer.emitValueToAlignment(AsmInfo->getCodePointerSize());
  1643. SectionEmitted = true;
  1644. }
  1645. NeedsEHFrameSection |=
  1646. Frame.CompactUnwindEncoding ==
  1647. MOFI->getCompactUnwindDwarfEHFrameOnly();
  1648. Emitter.EmitCompactUnwind(Frame);
  1649. }
  1650. }
  1651. if (!NeedsEHFrameSection) return;
  1652. MCSection &Section =
  1653. IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
  1654. : *MOFI->getDwarfFrameSection();
  1655. Streamer.SwitchSection(&Section);
  1656. MCSymbol *SectionStart = Context.createTempSymbol();
  1657. Streamer.emitLabel(SectionStart);
  1658. DenseMap<CIEKey, const MCSymbol *> CIEStarts;
  1659. const MCSymbol *DummyDebugKey = nullptr;
  1660. bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind();
  1661. // Sort the FDEs by their corresponding CIE before we emit them.
  1662. // This isn't technically necessary according to the DWARF standard,
  1663. // but the Android libunwindstack rejects eh_frame sections where
  1664. // an FDE refers to a CIE other than the closest previous CIE.
  1665. std::vector<MCDwarfFrameInfo> FrameArrayX(FrameArray.begin(), FrameArray.end());
  1666. llvm::stable_sort(FrameArrayX,
  1667. [](const MCDwarfFrameInfo &X, const MCDwarfFrameInfo &Y) {
  1668. return CIEKey(X) < CIEKey(Y);
  1669. });
  1670. for (auto I = FrameArrayX.begin(), E = FrameArrayX.end(); I != E;) {
  1671. const MCDwarfFrameInfo &Frame = *I;
  1672. ++I;
  1673. if (CanOmitDwarf && Frame.CompactUnwindEncoding !=
  1674. MOFI->getCompactUnwindDwarfEHFrameOnly())
  1675. // Don't generate an EH frame if we don't need one. I.e., it's taken care
  1676. // of by the compact unwind encoding.
  1677. continue;
  1678. CIEKey Key(Frame);
  1679. const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
  1680. if (!CIEStart)
  1681. CIEStart = &Emitter.EmitCIE(Frame);
  1682. Emitter.EmitFDE(*CIEStart, Frame, I == E, *SectionStart);
  1683. }
  1684. }
  1685. void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
  1686. uint64_t AddrDelta) {
  1687. MCContext &Context = Streamer.getContext();
  1688. SmallString<256> Tmp;
  1689. raw_svector_ostream OS(Tmp);
  1690. MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
  1691. Streamer.emitBytes(OS.str());
  1692. }
  1693. void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
  1694. uint64_t AddrDelta, raw_ostream &OS,
  1695. uint32_t *Offset, uint32_t *Size) {
  1696. // Scale the address delta by the minimum instruction length.
  1697. AddrDelta = ScaleAddrDelta(Context, AddrDelta);
  1698. bool WithFixups = false;
  1699. if (Offset && Size)
  1700. WithFixups = true;
  1701. support::endianness E =
  1702. Context.getAsmInfo()->isLittleEndian() ? support::little : support::big;
  1703. if (AddrDelta == 0) {
  1704. if (WithFixups) {
  1705. *Offset = 0;
  1706. *Size = 0;
  1707. }
  1708. } else if (isUIntN(6, AddrDelta)) {
  1709. uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
  1710. if (WithFixups) {
  1711. *Offset = OS.tell();
  1712. *Size = 6;
  1713. OS << uint8_t(dwarf::DW_CFA_advance_loc);
  1714. } else
  1715. OS << Opcode;
  1716. } else if (isUInt<8>(AddrDelta)) {
  1717. OS << uint8_t(dwarf::DW_CFA_advance_loc1);
  1718. if (WithFixups) {
  1719. *Offset = OS.tell();
  1720. *Size = 8;
  1721. OS.write_zeros(1);
  1722. } else
  1723. OS << uint8_t(AddrDelta);
  1724. } else if (isUInt<16>(AddrDelta)) {
  1725. OS << uint8_t(dwarf::DW_CFA_advance_loc2);
  1726. if (WithFixups) {
  1727. *Offset = OS.tell();
  1728. *Size = 16;
  1729. OS.write_zeros(2);
  1730. } else
  1731. support::endian::write<uint16_t>(OS, AddrDelta, E);
  1732. } else {
  1733. assert(isUInt<32>(AddrDelta));
  1734. OS << uint8_t(dwarf::DW_CFA_advance_loc4);
  1735. if (WithFixups) {
  1736. *Offset = OS.tell();
  1737. *Size = 32;
  1738. OS.write_zeros(4);
  1739. } else
  1740. support::endian::write<uint32_t>(OS, AddrDelta, E);
  1741. }
  1742. }