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