edeee20ab47bad34520c2e8a5129cfe3935f0a5b
[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 (FileName.empty()) {
344     FileName = "<stdin>";
345     Directory = "";
346   }
347   assert(!FileName.empty());
348   if (FileNumber == 0) {
349     FileNumber = SourceIdMap.size() + 1;
350     assert((MCDwarfFiles.empty() || FileNumber == MCDwarfFiles.size()) &&
351            "Don't mix autonumbered and explicit numbered line table usage");
352     StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(
353         (Directory + Twine('\0') + FileName).str(), FileNumber);
354     if (Ent.getValue() != FileNumber)
355       return Ent.getValue();
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.
406 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
407                            uint64_t AddrDelta) {
408   MCContext &Context = MCOS->getContext();
409   SmallString<256> Tmp;
410   raw_svector_ostream OS(Tmp);
411   MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
412   MCOS->EmitBytes(OS.str());
413 }
414
415 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
416 void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
417                              uint64_t AddrDelta, raw_ostream &OS) {
418   uint64_t Temp, Opcode;
419   bool NeedCopy = false;
420
421   // Scale the address delta by the minimum instruction length.
422   AddrDelta = ScaleAddrDelta(Context, AddrDelta);
423
424   // A LineDelta of INT64_MAX is a signal that this is actually a
425   // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
426   // end_sequence to emit the matrix entry.
427   if (LineDelta == INT64_MAX) {
428     if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
429       OS << char(dwarf::DW_LNS_const_add_pc);
430     else {
431       OS << char(dwarf::DW_LNS_advance_pc);
432       encodeULEB128(AddrDelta, OS);
433     }
434     OS << char(dwarf::DW_LNS_extended_op);
435     OS << char(1);
436     OS << char(dwarf::DW_LNE_end_sequence);
437     return;
438   }
439
440   // Bias the line delta by the base.
441   Temp = LineDelta - DWARF2_LINE_BASE;
442
443   // If the line increment is out of range of a special opcode, we must encode
444   // it with DW_LNS_advance_line.
445   if (Temp >= DWARF2_LINE_RANGE) {
446     OS << char(dwarf::DW_LNS_advance_line);
447     encodeSLEB128(LineDelta, OS);
448
449     LineDelta = 0;
450     Temp = 0 - DWARF2_LINE_BASE;
451     NeedCopy = true;
452   }
453
454   // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
455   if (LineDelta == 0 && AddrDelta == 0) {
456     OS << char(dwarf::DW_LNS_copy);
457     return;
458   }
459
460   // Bias the opcode by the special opcode base.
461   Temp += DWARF2_LINE_OPCODE_BASE;
462
463   // Avoid overflow when addr_delta is large.
464   if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
465     // Try using a special opcode.
466     Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
467     if (Opcode <= 255) {
468       OS << char(Opcode);
469       return;
470     }
471
472     // Try using DW_LNS_const_add_pc followed by special op.
473     Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
474     if (Opcode <= 255) {
475       OS << char(dwarf::DW_LNS_const_add_pc);
476       OS << char(Opcode);
477       return;
478     }
479   }
480
481   // Otherwise use DW_LNS_advance_pc.
482   OS << char(dwarf::DW_LNS_advance_pc);
483   encodeULEB128(AddrDelta, OS);
484
485   if (NeedCopy)
486     OS << char(dwarf::DW_LNS_copy);
487   else
488     OS << char(Temp);
489 }
490
491 // Utility function to write a tuple for .debug_abbrev.
492 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
493   MCOS->EmitULEB128IntValue(Name);
494   MCOS->EmitULEB128IntValue(Form);
495 }
496
497 // When generating dwarf for assembly source files this emits
498 // the data for .debug_abbrev section which contains three DIEs.
499 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
500   MCContext &context = MCOS->getContext();
501   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
502
503   // DW_TAG_compile_unit DIE abbrev (1).
504   MCOS->EmitULEB128IntValue(1);
505   MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
506   MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
507   EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
508   EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
509   EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
510   EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
511   if (!context.getCompilationDir().empty())
512     EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
513   StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
514   if (!DwarfDebugFlags.empty())
515     EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
516   EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
517   EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
518   EmitAbbrev(MCOS, 0, 0);
519
520   // DW_TAG_label DIE abbrev (2).
521   MCOS->EmitULEB128IntValue(2);
522   MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
523   MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
524   EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
525   EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
526   EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
527   EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
528   EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
529   EmitAbbrev(MCOS, 0, 0);
530
531   // DW_TAG_unspecified_parameters DIE abbrev (3).
532   MCOS->EmitULEB128IntValue(3);
533   MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
534   MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
535   EmitAbbrev(MCOS, 0, 0);
536
537   // Terminate the abbreviations for this compilation unit.
538   MCOS->EmitIntValue(0, 1);
539 }
540
541 // When generating dwarf for assembly source files this emits the data for
542 // .debug_aranges section.  Which contains a header and a table of pairs of
543 // PointerSize'ed values for the address and size of section(s) with line table
544 // entries (just the default .text in our case) and a terminating pair of zeros.
545 static void EmitGenDwarfAranges(MCStreamer *MCOS,
546                                 const MCSymbol *InfoSectionSymbol) {
547   MCContext &context = MCOS->getContext();
548
549   // Create a symbol at the end of the section that we are creating the dwarf
550   // debugging info to use later in here as part of the expression to calculate
551   // the size of the section for the table.
552   MCOS->SwitchSection(context.getGenDwarfSection());
553   MCSymbol *SectionEndSym = context.CreateTempSymbol();
554   MCOS->EmitLabel(SectionEndSym);
555   context.setGenDwarfSectionEndSym(SectionEndSym);
556
557   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
558
559   // This will be the length of the .debug_aranges section, first account for
560   // the size of each item in the header (see below where we emit these items).
561   int Length = 4 + 2 + 4 + 1 + 1;
562
563   // Figure the padding after the header before the table of address and size
564   // pairs who's values are PointerSize'ed.
565   const MCAsmInfo *asmInfo = context.getAsmInfo();
566   int AddrSize = asmInfo->getPointerSize();
567   int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
568   if (Pad == 2 * AddrSize)
569     Pad = 0;
570   Length += Pad;
571
572   // Add the size of the pair of PointerSize'ed values for the address and size
573   // of the one default .text section we have in the table.
574   Length += 2 * AddrSize;
575   // And the pair of terminating zeros.
576   Length += 2 * AddrSize;
577
578
579   // Emit the header for this section.
580   // The 4 byte length not including the 4 byte value for the length.
581   MCOS->EmitIntValue(Length - 4, 4);
582   // The 2 byte version, which is 2.
583   MCOS->EmitIntValue(2, 2);
584   // The 4 byte offset to the compile unit in the .debug_info from the start
585   // of the .debug_info.
586   if (InfoSectionSymbol)
587     MCOS->EmitSymbolValue(InfoSectionSymbol, 4);
588   else
589     MCOS->EmitIntValue(0, 4);
590   // The 1 byte size of an address.
591   MCOS->EmitIntValue(AddrSize, 1);
592   // The 1 byte size of a segment descriptor, we use a value of zero.
593   MCOS->EmitIntValue(0, 1);
594   // Align the header with the padding if needed, before we put out the table.
595   for(int i = 0; i < Pad; i++)
596     MCOS->EmitIntValue(0, 1);
597
598   // Now emit the table of pairs of PointerSize'ed values for the section(s)
599   // address and size, in our case just the one default .text section.
600   const MCExpr *Addr = MCSymbolRefExpr::Create(
601     context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
602   const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
603     *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
604   MCOS->EmitAbsValue(Addr, AddrSize);
605   MCOS->EmitAbsValue(Size, AddrSize);
606
607   // And finally the pair of terminating zeros.
608   MCOS->EmitIntValue(0, AddrSize);
609   MCOS->EmitIntValue(0, AddrSize);
610 }
611
612 // When generating dwarf for assembly source files this emits the data for
613 // .debug_info section which contains three parts.  The header, the compile_unit
614 // DIE and a list of label DIEs.
615 static void EmitGenDwarfInfo(MCStreamer *MCOS,
616                              const MCSymbol *AbbrevSectionSymbol,
617                              const MCSymbol *LineSectionSymbol) {
618   MCContext &context = MCOS->getContext();
619
620   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
621
622   // Create a symbol at the start and end of this section used in here for the
623   // expression to calculate the length in the header.
624   MCSymbol *InfoStart = context.CreateTempSymbol();
625   MCOS->EmitLabel(InfoStart);
626   MCSymbol *InfoEnd = context.CreateTempSymbol();
627
628   // First part: the header.
629
630   // The 4 byte total length of the information for this compilation unit, not
631   // including these 4 bytes.
632   const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
633   MCOS->EmitAbsValue(Length, 4);
634
635   // The 2 byte DWARF version, which is 2.
636   MCOS->EmitIntValue(2, 2);
637
638   // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
639   // it is at the start of that section so this is zero.
640   if (AbbrevSectionSymbol) {
641     MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
642   } else {
643     MCOS->EmitIntValue(0, 4);
644   }
645
646   const MCAsmInfo *asmInfo = context.getAsmInfo();
647   int AddrSize = asmInfo->getPointerSize();
648   // The 1 byte size of an address.
649   MCOS->EmitIntValue(AddrSize, 1);
650
651   // Second part: the compile_unit DIE.
652
653   // The DW_TAG_compile_unit DIE abbrev (1).
654   MCOS->EmitULEB128IntValue(1);
655
656   // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
657   // which is at the start of that section so this is zero.
658   if (LineSectionSymbol) {
659     MCOS->EmitSymbolValue(LineSectionSymbol, 4);
660   } else {
661     MCOS->EmitIntValue(0, 4);
662   }
663
664   // AT_low_pc, the first address of the default .text section.
665   const MCExpr *Start = MCSymbolRefExpr::Create(
666     context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
667   MCOS->EmitAbsValue(Start, AddrSize);
668
669   // AT_high_pc, the last address of the default .text section.
670   const MCExpr *End = MCSymbolRefExpr::Create(
671     context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
672   MCOS->EmitAbsValue(End, AddrSize);
673
674   // AT_name, the name of the source file.  Reconstruct from the first directory
675   // and file table entries.
676   const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
677   if (MCDwarfDirs.size() > 0) {
678     MCOS->EmitBytes(MCDwarfDirs[0]);
679     MCOS->EmitBytes("/");
680   }
681   const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
682     MCOS->getContext().getMCDwarfFiles();
683   MCOS->EmitBytes(MCDwarfFiles[1].Name);
684   MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
685
686   // AT_comp_dir, the working directory the assembly was done in.
687   if (!context.getCompilationDir().empty()) {
688     MCOS->EmitBytes(context.getCompilationDir());
689     MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
690   }
691
692   // AT_APPLE_flags, the command line arguments of the assembler tool.
693   StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
694   if (!DwarfDebugFlags.empty()){
695     MCOS->EmitBytes(DwarfDebugFlags);
696     MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
697   }
698
699   // AT_producer, the version of the assembler tool.
700   StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
701   if (!DwarfDebugProducer.empty()){
702     MCOS->EmitBytes(DwarfDebugProducer);
703   }
704   else {
705     MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "));
706     MCOS->EmitBytes(StringRef(PACKAGE_VERSION));
707     MCOS->EmitBytes(StringRef(")"));
708   }
709   MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
710
711   // AT_language, a 4 byte value.  We use DW_LANG_Mips_Assembler as the dwarf2
712   // draft has no standard code for assembler.
713   MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
714
715   // Third part: the list of label DIEs.
716
717   // Loop on saved info for dwarf labels and create the DIEs for them.
718   const std::vector<const MCGenDwarfLabelEntry *> &Entries =
719     MCOS->getContext().getMCGenDwarfLabelEntries();
720   for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
721        Entries.begin(), ie = Entries.end(); it != ie;
722        ++it) {
723     const MCGenDwarfLabelEntry *Entry = *it;
724
725     // The DW_TAG_label DIE abbrev (2).
726     MCOS->EmitULEB128IntValue(2);
727
728     // AT_name, of the label without any leading underbar.
729     MCOS->EmitBytes(Entry->getName());
730     MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
731
732     // AT_decl_file, index into the file table.
733     MCOS->EmitIntValue(Entry->getFileNumber(), 4);
734
735     // AT_decl_line, source line number.
736     MCOS->EmitIntValue(Entry->getLineNumber(), 4);
737
738     // AT_low_pc, start address of the label.
739     const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(),
740                                              MCSymbolRefExpr::VK_None, context);
741     MCOS->EmitAbsValue(AT_low_pc, AddrSize);
742
743     // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
744     MCOS->EmitIntValue(0, 1);
745
746     // The DW_TAG_unspecified_parameters DIE abbrev (3).
747     MCOS->EmitULEB128IntValue(3);
748
749     // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
750     MCOS->EmitIntValue(0, 1);
751   }
752   // Deallocate the MCGenDwarfLabelEntry classes that saved away the info
753   // for the dwarf labels.
754   for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
755        Entries.begin(), ie = Entries.end(); it != ie;
756        ++it) {
757     const MCGenDwarfLabelEntry *Entry = *it;
758     delete Entry;
759   }
760
761   // Add the NULL DIE terminating the Compile Unit DIE's.
762   MCOS->EmitIntValue(0, 1);
763
764   // Now set the value of the symbol at the end of the info section.
765   MCOS->EmitLabel(InfoEnd);
766 }
767
768 //
769 // When generating dwarf for assembly source files this emits the Dwarf
770 // sections.
771 //
772 void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) {
773   // Create the dwarf sections in this order (.debug_line already created).
774   MCContext &context = MCOS->getContext();
775   const MCAsmInfo *AsmInfo = context.getAsmInfo();
776   bool CreateDwarfSectionSymbols =
777       AsmInfo->doesDwarfUseRelocationsAcrossSections();
778   if (!CreateDwarfSectionSymbols)
779     LineSectionSymbol = NULL;
780   MCSymbol *AbbrevSectionSymbol = NULL;
781   MCSymbol *InfoSectionSymbol = NULL;
782   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
783   if (CreateDwarfSectionSymbols) {
784     InfoSectionSymbol = context.CreateTempSymbol();
785     MCOS->EmitLabel(InfoSectionSymbol);
786   }
787   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
788   if (CreateDwarfSectionSymbols) {
789     AbbrevSectionSymbol = context.CreateTempSymbol();
790     MCOS->EmitLabel(AbbrevSectionSymbol);
791   }
792   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
793
794   // If there are no line table entries then do not emit any section contents.
795   if (!context.hasMCLineSections())
796     return;
797
798   // Output the data for .debug_aranges section.
799   EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
800
801   // Output the data for .debug_abbrev section.
802   EmitGenDwarfAbbrev(MCOS);
803
804   // Output the data for .debug_info section.
805   EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol);
806 }
807
808 //
809 // When generating dwarf for assembly source files this is called when symbol
810 // for a label is created.  If this symbol is not a temporary and is in the
811 // section that dwarf is being generated for, save the needed info to create
812 // a dwarf label.
813 //
814 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
815                                      SourceMgr &SrcMgr, SMLoc &Loc) {
816   // We won't create dwarf labels for temporary symbols or symbols not in
817   // the default text.
818   if (Symbol->isTemporary())
819     return;
820   MCContext &context = MCOS->getContext();
821   if (context.getGenDwarfSection() != MCOS->getCurrentSection().first)
822     return;
823
824   // The dwarf label's name does not have the symbol name's leading
825   // underbar if any.
826   StringRef Name = Symbol->getName();
827   if (Name.startswith("_"))
828     Name = Name.substr(1, Name.size()-1);
829
830   // Get the dwarf file number to be used for the dwarf label.
831   unsigned FileNumber = context.getGenDwarfFileNumber();
832
833   // Finding the line number is the expensive part which is why we just don't
834   // pass it in as for some symbols we won't create a dwarf label.
835   int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
836   unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
837
838   // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
839   // values so that they don't have things like an ARM thumb bit from the
840   // original symbol. So when used they won't get a low bit set after
841   // relocation.
842   MCSymbol *Label = context.CreateTempSymbol();
843   MCOS->EmitLabel(Label);
844
845   // Create and entry for the info and add it to the other entries.
846   MCGenDwarfLabelEntry *Entry =
847     new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label);
848   MCOS->getContext().addMCGenDwarfLabelEntry(Entry);
849 }
850
851 static int getDataAlignmentFactor(MCStreamer &streamer) {
852   MCContext &context = streamer.getContext();
853   const MCAsmInfo *asmInfo = context.getAsmInfo();
854   int size = asmInfo->getCalleeSaveStackSlotSize();
855   if (asmInfo->isStackGrowthDirectionUp())
856     return size;
857   else
858     return -size;
859 }
860
861 static unsigned getSizeForEncoding(MCStreamer &streamer,
862                                    unsigned symbolEncoding) {
863   MCContext &context = streamer.getContext();
864   unsigned format = symbolEncoding & 0x0f;
865   switch (format) {
866   default: llvm_unreachable("Unknown Encoding");
867   case dwarf::DW_EH_PE_absptr:
868   case dwarf::DW_EH_PE_signed:
869     return context.getAsmInfo()->getPointerSize();
870   case dwarf::DW_EH_PE_udata2:
871   case dwarf::DW_EH_PE_sdata2:
872     return 2;
873   case dwarf::DW_EH_PE_udata4:
874   case dwarf::DW_EH_PE_sdata4:
875     return 4;
876   case dwarf::DW_EH_PE_udata8:
877   case dwarf::DW_EH_PE_sdata8:
878     return 8;
879   }
880 }
881
882 static void EmitFDESymbol(MCStreamer &streamer, const MCSymbol &symbol,
883                        unsigned symbolEncoding, bool isEH,
884                        const char *comment = 0) {
885   MCContext &context = streamer.getContext();
886   const MCAsmInfo *asmInfo = context.getAsmInfo();
887   const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
888                                                  symbolEncoding,
889                                                  streamer);
890   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
891   if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
892   if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
893     streamer.EmitAbsValue(v, size);
894   else
895     streamer.EmitValue(v, size);
896 }
897
898 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
899                             unsigned symbolEncoding) {
900   MCContext &context = streamer.getContext();
901   const MCAsmInfo *asmInfo = context.getAsmInfo();
902   const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
903                                                          symbolEncoding,
904                                                          streamer);
905   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
906   streamer.EmitValue(v, size);
907 }
908
909 namespace {
910   class FrameEmitterImpl {
911     int CFAOffset;
912     int CIENum;
913     bool UsingCFI;
914     bool IsEH;
915     const MCSymbol *SectionStart;
916   public:
917     FrameEmitterImpl(bool usingCFI, bool isEH)
918       : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
919         SectionStart(0) {}
920
921     void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
922
923     /// EmitCompactUnwind - Emit the unwind information in a compact way.
924     void EmitCompactUnwind(MCStreamer &streamer,
925                            const MCDwarfFrameInfo &frame);
926
927     const MCSymbol &EmitCIE(MCStreamer &streamer,
928                             const MCSymbol *personality,
929                             unsigned personalityEncoding,
930                             const MCSymbol *lsda,
931                             bool IsSignalFrame,
932                             unsigned lsdaEncoding,
933                             bool IsSimple);
934     MCSymbol *EmitFDE(MCStreamer &streamer,
935                       const MCSymbol &cieStart,
936                       const MCDwarfFrameInfo &frame);
937     void EmitCFIInstructions(MCStreamer &streamer,
938                              ArrayRef<MCCFIInstruction> Instrs,
939                              MCSymbol *BaseLabel);
940     void EmitCFIInstruction(MCStreamer &Streamer,
941                             const MCCFIInstruction &Instr);
942   };
943
944 } // end anonymous namespace
945
946 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
947                              StringRef Prefix) {
948   if (Streamer.isVerboseAsm()) {
949     const char *EncStr;
950     switch (Encoding) {
951     default: EncStr = "<unknown encoding>"; break;
952     case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break;
953     case dwarf::DW_EH_PE_omit:   EncStr = "omit"; break;
954     case dwarf::DW_EH_PE_pcrel:  EncStr = "pcrel"; break;
955     case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break;
956     case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break;
957     case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break;
958     case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break;
959     case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
960       EncStr = "pcrel udata4";
961       break;
962     case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
963       EncStr = "pcrel sdata4";
964       break;
965     case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
966       EncStr = "pcrel udata8";
967       break;
968     case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
969       EncStr = "screl sdata8";
970       break;
971     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
972       EncStr = "indirect pcrel udata4";
973       break;
974     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
975       EncStr = "indirect pcrel sdata4";
976       break;
977     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
978       EncStr = "indirect pcrel udata8";
979       break;
980     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
981       EncStr = "indirect pcrel sdata8";
982       break;
983     }
984
985     Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
986   }
987
988   Streamer.EmitIntValue(Encoding, 1);
989 }
990
991 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
992                                           const MCCFIInstruction &Instr) {
993   int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
994   bool VerboseAsm = Streamer.isVerboseAsm();
995
996   switch (Instr.getOperation()) {
997   case MCCFIInstruction::OpRegister: {
998     unsigned Reg1 = Instr.getRegister();
999     unsigned Reg2 = Instr.getRegister2();
1000     if (VerboseAsm) {
1001       Streamer.AddComment("DW_CFA_register");
1002       Streamer.AddComment(Twine("Reg1 ") + Twine(Reg1));
1003       Streamer.AddComment(Twine("Reg2 ") + Twine(Reg2));
1004     }
1005     Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
1006     Streamer.EmitULEB128IntValue(Reg1);
1007     Streamer.EmitULEB128IntValue(Reg2);
1008     return;
1009   }
1010   case MCCFIInstruction::OpWindowSave: {
1011     Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
1012     return;
1013   }
1014   case MCCFIInstruction::OpUndefined: {
1015     unsigned Reg = Instr.getRegister();
1016     if (VerboseAsm) {
1017       Streamer.AddComment("DW_CFA_undefined");
1018       Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1019     }
1020     Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
1021     Streamer.EmitULEB128IntValue(Reg);
1022     return;
1023   }
1024   case MCCFIInstruction::OpAdjustCfaOffset:
1025   case MCCFIInstruction::OpDefCfaOffset: {
1026     const bool IsRelative =
1027       Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1028
1029     if (VerboseAsm)
1030       Streamer.AddComment("DW_CFA_def_cfa_offset");
1031     Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
1032
1033     if (IsRelative)
1034       CFAOffset += Instr.getOffset();
1035     else
1036       CFAOffset = -Instr.getOffset();
1037
1038     if (VerboseAsm)
1039       Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1040     Streamer.EmitULEB128IntValue(CFAOffset);
1041
1042     return;
1043   }
1044   case MCCFIInstruction::OpDefCfa: {
1045     if (VerboseAsm)
1046       Streamer.AddComment("DW_CFA_def_cfa");
1047     Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1048
1049     if (VerboseAsm)
1050       Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1051     Streamer.EmitULEB128IntValue(Instr.getRegister());
1052
1053     CFAOffset = -Instr.getOffset();
1054
1055     if (VerboseAsm)
1056       Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1057     Streamer.EmitULEB128IntValue(CFAOffset);
1058
1059     return;
1060   }
1061
1062   case MCCFIInstruction::OpDefCfaRegister: {
1063     if (VerboseAsm)
1064       Streamer.AddComment("DW_CFA_def_cfa_register");
1065     Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1066
1067     if (VerboseAsm)
1068       Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1069     Streamer.EmitULEB128IntValue(Instr.getRegister());
1070
1071     return;
1072   }
1073
1074   case MCCFIInstruction::OpOffset:
1075   case MCCFIInstruction::OpRelOffset: {
1076     const bool IsRelative =
1077       Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1078
1079     unsigned Reg = Instr.getRegister();
1080     int Offset = Instr.getOffset();
1081     if (IsRelative)
1082       Offset -= CFAOffset;
1083     Offset = Offset / dataAlignmentFactor;
1084
1085     if (Offset < 0) {
1086       if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
1087       Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1088       if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1089       Streamer.EmitULEB128IntValue(Reg);
1090       if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1091       Streamer.EmitSLEB128IntValue(Offset);
1092     } else if (Reg < 64) {
1093       if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
1094                                           Twine(Reg) + ")");
1095       Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1096       if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1097       Streamer.EmitULEB128IntValue(Offset);
1098     } else {
1099       if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
1100       Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1101       if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1102       Streamer.EmitULEB128IntValue(Reg);
1103       if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1104       Streamer.EmitULEB128IntValue(Offset);
1105     }
1106     return;
1107   }
1108   case MCCFIInstruction::OpRememberState:
1109     if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
1110     Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1111     return;
1112   case MCCFIInstruction::OpRestoreState:
1113     if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
1114     Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1115     return;
1116   case MCCFIInstruction::OpSameValue: {
1117     unsigned Reg = Instr.getRegister();
1118     if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
1119     Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1120     if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1121     Streamer.EmitULEB128IntValue(Reg);
1122     return;
1123   }
1124   case MCCFIInstruction::OpRestore: {
1125     unsigned Reg = Instr.getRegister();
1126     if (VerboseAsm) {
1127       Streamer.AddComment("DW_CFA_restore");
1128       Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1129     }
1130     Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1131     return;
1132   }
1133   case MCCFIInstruction::OpEscape:
1134     if (VerboseAsm) Streamer.AddComment("Escape bytes");
1135     Streamer.EmitBytes(Instr.getValues());
1136     return;
1137   }
1138   llvm_unreachable("Unhandled case in switch");
1139 }
1140
1141 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1142 /// frame.
1143 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
1144                                            ArrayRef<MCCFIInstruction> Instrs,
1145                                            MCSymbol *BaseLabel) {
1146   for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1147     const MCCFIInstruction &Instr = Instrs[i];
1148     MCSymbol *Label = Instr.getLabel();
1149     // Throw out move if the label is invalid.
1150     if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1151
1152     // Advance row if new location.
1153     if (BaseLabel && Label) {
1154       MCSymbol *ThisSym = Label;
1155       if (ThisSym != BaseLabel) {
1156         if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
1157         streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1158         BaseLabel = ThisSym;
1159       }
1160     }
1161
1162     EmitCFIInstruction(streamer, Instr);
1163   }
1164 }
1165
1166 /// EmitCompactUnwind - Emit the unwind information in a compact way.
1167 void FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
1168                                          const MCDwarfFrameInfo &Frame) {
1169   MCContext &Context = Streamer.getContext();
1170   const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1171   bool VerboseAsm = Streamer.isVerboseAsm();
1172
1173   // range-start range-length  compact-unwind-enc personality-func   lsda
1174   //  _foo       LfooEnd-_foo  0x00000023          0                 0
1175   //  _bar       LbarEnd-_bar  0x00000025         __gxx_personality  except_tab1
1176   //
1177   //   .section __LD,__compact_unwind,regular,debug
1178   //
1179   //   # compact unwind for _foo
1180   //   .quad _foo
1181   //   .set L1,LfooEnd-_foo
1182   //   .long L1
1183   //   .long 0x01010001
1184   //   .quad 0
1185   //   .quad 0
1186   //
1187   //   # compact unwind for _bar
1188   //   .quad _bar
1189   //   .set L2,LbarEnd-_bar
1190   //   .long L2
1191   //   .long 0x01020011
1192   //   .quad __gxx_personality
1193   //   .quad except_tab1
1194
1195   uint32_t Encoding = Frame.CompactUnwindEncoding;
1196   if (!Encoding) return;
1197   bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1198
1199   // The encoding needs to know we have an LSDA.
1200   if (!DwarfEHFrameOnly && Frame.Lsda)
1201     Encoding |= 0x40000000;
1202
1203   // Range Start
1204   unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
1205   unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1206   if (VerboseAsm) Streamer.AddComment("Range Start");
1207   Streamer.EmitSymbolValue(Frame.Function, Size);
1208
1209   // Range Length
1210   const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1211                                               *Frame.End, 0);
1212   if (VerboseAsm) Streamer.AddComment("Range Length");
1213   Streamer.EmitAbsValue(Range, 4);
1214
1215   // Compact Encoding
1216   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1217   if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
1218                                       Twine::utohexstr(Encoding));
1219   Streamer.EmitIntValue(Encoding, Size);
1220
1221   // Personality Function
1222   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1223   if (VerboseAsm) Streamer.AddComment("Personality Function");
1224   if (!DwarfEHFrameOnly && Frame.Personality)
1225     Streamer.EmitSymbolValue(Frame.Personality, Size);
1226   else
1227     Streamer.EmitIntValue(0, Size); // No personality fn
1228
1229   // LSDA
1230   Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1231   if (VerboseAsm) Streamer.AddComment("LSDA");
1232   if (!DwarfEHFrameOnly && Frame.Lsda)
1233     Streamer.EmitSymbolValue(Frame.Lsda, Size);
1234   else
1235     Streamer.EmitIntValue(0, Size); // No LSDA
1236 }
1237
1238 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
1239                                           const MCSymbol *personality,
1240                                           unsigned personalityEncoding,
1241                                           const MCSymbol *lsda,
1242                                           bool IsSignalFrame,
1243                                           unsigned lsdaEncoding,
1244                                           bool IsSimple) {
1245   MCContext &context = streamer.getContext();
1246   const MCRegisterInfo *MRI = context.getRegisterInfo();
1247   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1248   bool verboseAsm = streamer.isVerboseAsm();
1249
1250   MCSymbol *sectionStart;
1251   if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
1252     sectionStart = context.CreateTempSymbol();
1253   else
1254     sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
1255
1256   streamer.EmitLabel(sectionStart);
1257   CIENum++;
1258
1259   MCSymbol *sectionEnd = context.CreateTempSymbol();
1260
1261   // Length
1262   const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1263                                                *sectionEnd, 4);
1264   if (verboseAsm) streamer.AddComment("CIE Length");
1265   streamer.EmitAbsValue(Length, 4);
1266
1267   // CIE ID
1268   unsigned CIE_ID = IsEH ? 0 : -1;
1269   if (verboseAsm) streamer.AddComment("CIE ID Tag");
1270   streamer.EmitIntValue(CIE_ID, 4);
1271
1272   // Version
1273   if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
1274   streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
1275
1276   // Augmentation String
1277   SmallString<8> Augmentation;
1278   if (IsEH) {
1279     if (verboseAsm) streamer.AddComment("CIE Augmentation");
1280     Augmentation += "z";
1281     if (personality)
1282       Augmentation += "P";
1283     if (lsda)
1284       Augmentation += "L";
1285     Augmentation += "R";
1286     if (IsSignalFrame)
1287       Augmentation += "S";
1288     streamer.EmitBytes(Augmentation.str());
1289   }
1290   streamer.EmitIntValue(0, 1);
1291
1292   // Code Alignment Factor
1293   if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
1294   streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1295
1296   // Data Alignment Factor
1297   if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
1298   streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1299
1300   // Return Address Register
1301   if (verboseAsm) streamer.AddComment("CIE Return Address Column");
1302   streamer.EmitULEB128IntValue(MRI->getDwarfRegNum(MRI->getRARegister(), true));
1303
1304   // Augmentation Data Length (optional)
1305
1306   unsigned augmentationLength = 0;
1307   if (IsEH) {
1308     if (personality) {
1309       // Personality Encoding
1310       augmentationLength += 1;
1311       // Personality
1312       augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1313     }
1314     if (lsda)
1315       augmentationLength += 1;
1316     // Encoding of the FDE pointers
1317     augmentationLength += 1;
1318
1319     if (verboseAsm) streamer.AddComment("Augmentation Size");
1320     streamer.EmitULEB128IntValue(augmentationLength);
1321
1322     // Augmentation Data (optional)
1323     if (personality) {
1324       // Personality Encoding
1325       EmitEncodingByte(streamer, personalityEncoding,
1326                        "Personality Encoding");
1327       // Personality
1328       if (verboseAsm) streamer.AddComment("Personality");
1329       EmitPersonality(streamer, *personality, personalityEncoding);
1330     }
1331
1332     if (lsda)
1333       EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
1334
1335     // Encoding of the FDE pointers
1336     EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
1337                      "FDE Encoding");
1338   }
1339
1340   // Initial Instructions
1341
1342   const MCAsmInfo *MAI = context.getAsmInfo();
1343   if (!IsSimple) {
1344     const std::vector<MCCFIInstruction> &Instructions =
1345         MAI->getInitialFrameState();
1346     EmitCFIInstructions(streamer, Instructions, NULL);
1347   }
1348
1349   // Padding
1350   streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1351
1352   streamer.EmitLabel(sectionEnd);
1353   return *sectionStart;
1354 }
1355
1356 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
1357                                     const MCSymbol &cieStart,
1358                                     const MCDwarfFrameInfo &frame) {
1359   MCContext &context = streamer.getContext();
1360   MCSymbol *fdeStart = context.CreateTempSymbol();
1361   MCSymbol *fdeEnd = context.CreateTempSymbol();
1362   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1363   bool verboseAsm = streamer.isVerboseAsm();
1364
1365   if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
1366     MCSymbol *EHSym =
1367       context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
1368     streamer.EmitEHSymAttributes(frame.Function, EHSym);
1369     streamer.EmitLabel(EHSym);
1370   }
1371
1372   // Length
1373   const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1374   if (verboseAsm) streamer.AddComment("FDE Length");
1375   streamer.EmitAbsValue(Length, 4);
1376
1377   streamer.EmitLabel(fdeStart);
1378
1379   // CIE Pointer
1380   const MCAsmInfo *asmInfo = context.getAsmInfo();
1381   if (IsEH) {
1382     const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1383                                                  0);
1384     if (verboseAsm) streamer.AddComment("FDE CIE Offset");
1385     streamer.EmitAbsValue(offset, 4);
1386   } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1387     const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1388                                                  cieStart, 0);
1389     streamer.EmitAbsValue(offset, 4);
1390   } else {
1391     streamer.EmitSymbolValue(&cieStart, 4);
1392   }
1393
1394   // PC Begin
1395   unsigned PCEncoding = IsEH ? MOFI->getFDEEncoding(UsingCFI)
1396                              : (unsigned)dwarf::DW_EH_PE_absptr;
1397   unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1398   EmitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH, "FDE initial location");
1399
1400   // PC Range
1401   const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1402                                               *frame.End, 0);
1403   if (verboseAsm) streamer.AddComment("FDE address range");
1404   streamer.EmitAbsValue(Range, PCSize);
1405
1406   if (IsEH) {
1407     // Augmentation Data Length
1408     unsigned augmentationLength = 0;
1409
1410     if (frame.Lsda)
1411       augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1412
1413     if (verboseAsm) streamer.AddComment("Augmentation size");
1414     streamer.EmitULEB128IntValue(augmentationLength);
1415
1416     // Augmentation Data
1417     if (frame.Lsda)
1418       EmitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true,
1419                     "Language Specific Data Area");
1420   }
1421
1422   // Call Frame Instructions
1423   EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1424
1425   // Padding
1426   streamer.EmitValueToAlignment(PCSize);
1427
1428   return fdeEnd;
1429 }
1430
1431 namespace {
1432   struct CIEKey {
1433     static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false, false); }
1434     static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false, false); }
1435
1436     CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
1437            unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_) :
1438       Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1439       LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1440       IsSimple(IsSimple_) {
1441     }
1442     const MCSymbol* Personality;
1443     unsigned PersonalityEncoding;
1444     unsigned LsdaEncoding;
1445     bool IsSignalFrame;
1446     bool IsSimple;
1447   };
1448 }
1449
1450 namespace llvm {
1451   template <>
1452   struct DenseMapInfo<CIEKey> {
1453     static CIEKey getEmptyKey() {
1454       return CIEKey::getEmptyKey();
1455     }
1456     static CIEKey getTombstoneKey() {
1457       return CIEKey::getTombstoneKey();
1458     }
1459     static unsigned getHashValue(const CIEKey &Key) {
1460       return static_cast<unsigned>(hash_combine(Key.Personality,
1461                                                 Key.PersonalityEncoding,
1462                                                 Key.LsdaEncoding,
1463                                                 Key.IsSignalFrame,
1464                                                 Key.IsSimple));
1465     }
1466     static bool isEqual(const CIEKey &LHS,
1467                         const CIEKey &RHS) {
1468       return LHS.Personality == RHS.Personality &&
1469         LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1470         LHS.LsdaEncoding == RHS.LsdaEncoding &&
1471         LHS.IsSignalFrame == RHS.IsSignalFrame &&
1472         LHS.IsSimple == RHS.IsSimple;
1473     }
1474   };
1475 }
1476
1477 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer, MCAsmBackend *MAB,
1478                                bool UsingCFI, bool IsEH) {
1479   Streamer.generateCompactUnwindEncodings(MAB);
1480
1481   MCContext &Context = Streamer.getContext();
1482   const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1483   FrameEmitterImpl Emitter(UsingCFI, IsEH);
1484   ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1485
1486   // Emit the compact unwind info if available.
1487   if (IsEH && MOFI->getCompactUnwindSection()) {
1488     bool SectionEmitted = false;
1489     for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1490       const MCDwarfFrameInfo &Frame = FrameArray[i];
1491       if (Frame.CompactUnwindEncoding == 0) continue;
1492       if (!SectionEmitted) {
1493         Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1494         Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1495         SectionEmitted = true;
1496       }
1497       Emitter.EmitCompactUnwind(Streamer, Frame);
1498     }
1499   }
1500
1501   const MCSection &Section =
1502     IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() :
1503            *MOFI->getDwarfFrameSection();
1504   Streamer.SwitchSection(&Section);
1505   MCSymbol *SectionStart = Context.CreateTempSymbol();
1506   Streamer.EmitLabel(SectionStart);
1507   Emitter.setSectionStart(SectionStart);
1508
1509   MCSymbol *FDEEnd = NULL;
1510   DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1511
1512   const MCSymbol *DummyDebugKey = NULL;
1513   for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1514     const MCDwarfFrameInfo &Frame = FrameArray[i];
1515     CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1516                Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1517     const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1518     if (!CIEStart)
1519       CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1520                                   Frame.PersonalityEncoding, Frame.Lsda,
1521                                   Frame.IsSignalFrame,
1522                                   Frame.LsdaEncoding,
1523                                   Frame.IsSimple);
1524
1525     FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1526
1527     if (i != n - 1)
1528       Streamer.EmitLabel(FDEEnd);
1529   }
1530
1531   Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1532   if (FDEEnd)
1533     Streamer.EmitLabel(FDEEnd);
1534 }
1535
1536 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1537                                          uint64_t AddrDelta) {
1538   MCContext &Context = Streamer.getContext();
1539   SmallString<256> Tmp;
1540   raw_svector_ostream OS(Tmp);
1541   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1542   Streamer.EmitBytes(OS.str());
1543 }
1544
1545 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1546                                            uint64_t AddrDelta,
1547                                            raw_ostream &OS) {
1548   // Scale the address delta by the minimum instruction length.
1549   AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1550
1551   if (AddrDelta == 0) {
1552   } else if (isUIntN(6, AddrDelta)) {
1553     uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1554     OS << Opcode;
1555   } else if (isUInt<8>(AddrDelta)) {
1556     OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1557     OS << uint8_t(AddrDelta);
1558   } else if (isUInt<16>(AddrDelta)) {
1559     // FIXME: check what is the correct behavior on a big endian machine.
1560     OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1561     OS << uint8_t( AddrDelta       & 0xff);
1562     OS << uint8_t((AddrDelta >> 8) & 0xff);
1563   } else {
1564     // FIXME: check what is the correct behavior on a big endian machine.
1565     assert(isUInt<32>(AddrDelta));
1566     OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1567     OS << uint8_t( AddrDelta        & 0xff);
1568     OS << uint8_t((AddrDelta >> 8)  & 0xff);
1569     OS << uint8_t((AddrDelta >> 16) & 0xff);
1570     OS << uint8_t((AddrDelta >> 24) & 0xff);
1571
1572   }
1573 }