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