Next bit of support for the dwarf .file directive. This patch takes the
[oota-llvm.git] / lib / MC / MCMachOStreamer.cpp
1 //===- lib/MC/MCMachOStreamer.cpp - Mach-O Object Output ------------===//
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/MCStreamer.h"
11
12 #include "llvm/MC/MCAssembler.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCCodeEmitter.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCObjectStreamer.h"
18 #include "llvm/MC/MCSection.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/MC/MCMachOSymbolFlags.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCDwarf.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Target/TargetAsmBackend.h"
26
27 using namespace llvm;
28
29 namespace {
30
31 class MCMachOStreamer : public MCObjectStreamer {
32 private:
33   void EmitInstToFragment(const MCInst &Inst);
34   void EmitInstToData(const MCInst &Inst);
35   // FIXME: These will likely moved to a better place.
36   const MCExpr * MakeStartMinusEndExpr(MCSymbol *Start, MCSymbol *End,
37                                                         int IntVal);
38   void EmitDwarfFileTable(void);
39
40 public:
41   MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
42                   raw_ostream &OS, MCCodeEmitter *Emitter)
43     : MCObjectStreamer(Context, TAB, OS, Emitter) {}
44
45   /// @name MCStreamer Interface
46   /// @{
47
48   virtual void EmitLabel(MCSymbol *Symbol);
49   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
50   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
51   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
52   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
53   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
54                                 unsigned ByteAlignment);
55   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
56     assert(0 && "macho doesn't support this directive");
57   }
58   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
59     assert(0 && "macho doesn't support this directive");
60   }
61   virtual void EmitCOFFSymbolType(int Type) {
62     assert(0 && "macho doesn't support this directive");
63   }
64   virtual void EndCOFFSymbolDef() {
65     assert(0 && "macho doesn't support this directive");
66   }
67   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
68     assert(0 && "macho doesn't support this directive");
69   }
70   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
71     assert(0 && "macho doesn't support this directive");
72   }
73   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
74                             unsigned Size = 0, unsigned ByteAlignment = 0);
75   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
76                               uint64_t Size, unsigned ByteAlignment = 0);
77   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
78   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
79   virtual void EmitGPRel32Value(const MCExpr *Value) {
80     assert(0 && "macho doesn't support this directive");
81   }
82   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
83                                     unsigned ValueSize = 1,
84                                     unsigned MaxBytesToEmit = 0);
85   virtual void EmitCodeAlignment(unsigned ByteAlignment,
86                                  unsigned MaxBytesToEmit = 0);
87   virtual void EmitValueToOffset(const MCExpr *Offset,
88                                  unsigned char Value = 0);
89
90   virtual void EmitFileDirective(StringRef Filename) {
91     // FIXME: Just ignore the .file; it isn't important enough to fail the
92     // entire assembly.
93
94     //report_fatal_error("unsupported directive: '.file'");
95   }
96   virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
97     // FIXME: Just ignore the .file; it isn't important enough to fail the
98     // entire assembly.
99
100     //report_fatal_error("unsupported directive: '.file'");
101   }
102
103   virtual void EmitInstruction(const MCInst &Inst);
104
105   virtual void Finish();
106
107   /// @}
108 };
109
110 } // end anonymous namespace.
111
112 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
113   // TODO: This is almost exactly the same as WinCOFFStreamer. Consider merging
114   // into MCObjectStreamer.
115   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
116   assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
117   assert(CurSection && "Cannot emit before setting section!");
118
119   Symbol->setSection(*CurSection);
120
121   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
122
123   // We have to create a new fragment if this is an atom defining symbol,
124   // fragments cannot span atoms.
125   if (getAssembler().isSymbolLinkerVisible(SD.getSymbol()))
126     new MCDataFragment(getCurrentSectionData());
127
128   // FIXME: This is wasteful, we don't necessarily need to create a data
129   // fragment. Instead, we should mark the symbol as pointing into the data
130   // fragment if it exists, otherwise we should just queue the label and set its
131   // fragment pointer when we emit the next fragment.
132   MCDataFragment *F = getOrCreateDataFragment();
133   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
134   SD.setFragment(F);
135   SD.setOffset(F->getContents().size());
136
137   // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
138   // to clear the weak reference and weak definition bits too, but the
139   // implementation was buggy. For now we just try to match 'as', for
140   // diffability.
141   //
142   // FIXME: Cleanup this code, these bits should be emitted based on semantic
143   // properties, not on the order of definition, etc.
144   SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
145 }
146
147 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
148   switch (Flag) {
149   case MCAF_SubsectionsViaSymbols:
150     getAssembler().setSubsectionsViaSymbols(true);
151     return;
152   }
153
154   assert(0 && "invalid assembler flag!");
155 }
156
157 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
158   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
159   // MCObjectStreamer.
160   // FIXME: Lift context changes into super class.
161   getAssembler().getOrCreateSymbolData(*Symbol);
162   Symbol->setVariableValue(AddValueSymbols(Value));
163 }
164
165 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
166                                           MCSymbolAttr Attribute) {
167   // Indirect symbols are handled differently, to match how 'as' handles
168   // them. This makes writing matching .o files easier.
169   if (Attribute == MCSA_IndirectSymbol) {
170     // Note that we intentionally cannot use the symbol data here; this is
171     // important for matching the string table that 'as' generates.
172     IndirectSymbolData ISD;
173     ISD.Symbol = Symbol;
174     ISD.SectionData = getCurrentSectionData();
175     getAssembler().getIndirectSymbols().push_back(ISD);
176     return;
177   }
178
179   // Adding a symbol attribute always introduces the symbol, note that an
180   // important side effect of calling getOrCreateSymbolData here is to register
181   // the symbol with the assembler.
182   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
183
184   // The implementation of symbol attributes is designed to match 'as', but it
185   // leaves much to desired. It doesn't really make sense to arbitrarily add and
186   // remove flags, but 'as' allows this (in particular, see .desc).
187   //
188   // In the future it might be worth trying to make these operations more well
189   // defined.
190   switch (Attribute) {
191   case MCSA_Invalid:
192   case MCSA_ELF_TypeFunction:
193   case MCSA_ELF_TypeIndFunction:
194   case MCSA_ELF_TypeObject:
195   case MCSA_ELF_TypeTLS:
196   case MCSA_ELF_TypeCommon:
197   case MCSA_ELF_TypeNoType:
198   case MCSA_IndirectSymbol:
199   case MCSA_Hidden:
200   case MCSA_Internal:
201   case MCSA_Protected:
202   case MCSA_Weak:
203   case MCSA_Local:
204     assert(0 && "Invalid symbol attribute for Mach-O!");
205     break;
206
207   case MCSA_Global:
208     SD.setExternal(true);
209     // This effectively clears the undefined lazy bit, in Darwin 'as', although
210     // it isn't very consistent because it implements this as part of symbol
211     // lookup.
212     //
213     // FIXME: Cleanup this code, these bits should be emitted based on semantic
214     // properties, not on the order of definition, etc.
215     SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
216     break;
217
218   case MCSA_LazyReference:
219     // FIXME: This requires -dynamic.
220     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
221     if (Symbol->isUndefined())
222       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
223     break;
224
225     // Since .reference sets the no dead strip bit, it is equivalent to
226     // .no_dead_strip in practice.
227   case MCSA_Reference:
228   case MCSA_NoDeadStrip:
229     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
230     break;
231
232   case MCSA_PrivateExtern:
233     SD.setExternal(true);
234     SD.setPrivateExtern(true);
235     break;
236
237   case MCSA_WeakReference:
238     // FIXME: This requires -dynamic.
239     if (Symbol->isUndefined())
240       SD.setFlags(SD.getFlags() | SF_WeakReference);
241     break;
242
243   case MCSA_WeakDefinition:
244     // FIXME: 'as' enforces that this is defined and global. The manual claims
245     // it has to be in a coalesced section, but this isn't enforced.
246     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
247     break;
248
249   case MCSA_WeakDefAutoPrivate:
250     SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
251     break;
252   }
253 }
254
255 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
256   // Encode the 'desc' value into the lowest implementation defined bits.
257   assert(DescValue == (DescValue & SF_DescFlagsMask) &&
258          "Invalid .desc value!");
259   getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
260     DescValue & SF_DescFlagsMask);
261 }
262
263 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
264                                        unsigned ByteAlignment) {
265   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
266   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
267
268   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
269   SD.setExternal(true);
270   SD.setCommon(Size, ByteAlignment);
271 }
272
273 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
274                                    unsigned Size, unsigned ByteAlignment) {
275   MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
276
277   // The symbol may not be present, which only creates the section.
278   if (!Symbol)
279     return;
280
281   // FIXME: Assert that this section has the zerofill type.
282
283   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
284
285   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
286
287   // Emit an align fragment if necessary.
288   if (ByteAlignment != 1)
289     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
290
291   MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
292   SD.setFragment(F);
293
294   Symbol->setSection(*Section);
295
296   // Update the maximum alignment on the zero fill section if necessary.
297   if (ByteAlignment > SectData.getAlignment())
298     SectData.setAlignment(ByteAlignment);
299 }
300
301 // This should always be called with the thread local bss section.  Like the
302 // .zerofill directive this doesn't actually switch sections on us.
303 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
304                                      uint64_t Size, unsigned ByteAlignment) {
305   EmitZerofill(Section, Symbol, Size, ByteAlignment);
306   return;
307 }
308
309 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
310   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
311   // MCObjectStreamer.
312   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
313 }
314
315 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
316                                 unsigned AddrSpace) {
317   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
318   // MCObjectStreamer.
319   MCDataFragment *DF = getOrCreateDataFragment();
320
321   // Avoid fixups when possible.
322   int64_t AbsValue;
323   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
324     // FIXME: Endianness assumption.
325     for (unsigned i = 0; i != Size; ++i)
326       DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
327   } else {
328     DF->addFixup(MCFixup::Create(DF->getContents().size(),
329                                  AddValueSymbols(Value),
330                                  MCFixup::getKindForSize(Size)));
331     DF->getContents().resize(DF->getContents().size() + Size, 0);
332   }
333 }
334
335 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
336                                            int64_t Value, unsigned ValueSize,
337                                            unsigned MaxBytesToEmit) {
338   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
339   // MCObjectStreamer.
340   if (MaxBytesToEmit == 0)
341     MaxBytesToEmit = ByteAlignment;
342   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
343                       getCurrentSectionData());
344
345   // Update the maximum alignment on the current section if necessary.
346   if (ByteAlignment > getCurrentSectionData()->getAlignment())
347     getCurrentSectionData()->setAlignment(ByteAlignment);
348 }
349
350 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
351                                         unsigned MaxBytesToEmit) {
352   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
353   // MCObjectStreamer.
354   if (MaxBytesToEmit == 0)
355     MaxBytesToEmit = ByteAlignment;
356   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
357                                            getCurrentSectionData());
358   F->setEmitNops(true);
359
360   // Update the maximum alignment on the current section if necessary.
361   if (ByteAlignment > getCurrentSectionData()->getAlignment())
362     getCurrentSectionData()->setAlignment(ByteAlignment);
363 }
364
365 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
366                                         unsigned char Value) {
367   new MCOrgFragment(*Offset, Value, getCurrentSectionData());
368 }
369
370 void MCMachOStreamer::EmitInstToFragment(const MCInst &Inst) {
371   MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
372
373   // Add the fixups and data.
374   //
375   // FIXME: Revisit this design decision when relaxation is done, we may be
376   // able to get away with not storing any extra data in the MCInst.
377   SmallVector<MCFixup, 4> Fixups;
378   SmallString<256> Code;
379   raw_svector_ostream VecOS(Code);
380   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
381   VecOS.flush();
382
383   IF->getCode() = Code;
384   IF->getFixups() = Fixups;
385 }
386
387 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
388   MCDataFragment *DF = getOrCreateDataFragment();
389
390   SmallVector<MCFixup, 4> Fixups;
391   SmallString<256> Code;
392   raw_svector_ostream VecOS(Code);
393   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
394   VecOS.flush();
395
396   // Add the fixups and data.
397   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
398     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
399     DF->addFixup(Fixups[i]);
400   }
401   DF->getContents().append(Code.begin(), Code.end());
402 }
403
404 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
405   // Scan for values.
406   for (unsigned i = Inst.getNumOperands(); i--; )
407     if (Inst.getOperand(i).isExpr())
408       AddValueSymbols(Inst.getOperand(i).getExpr());
409
410   getCurrentSectionData()->setHasInstructions(true);
411
412   // If this instruction doesn't need relaxation, just emit it as data.
413   if (!getAssembler().getBackend().MayNeedRelaxation(Inst)) {
414     EmitInstToData(Inst);
415     return;
416   }
417
418   // Otherwise, if we are relaxing everything, relax the instruction as much as
419   // possible and emit it as data.
420   if (getAssembler().getRelaxAll()) {
421     MCInst Relaxed;
422     getAssembler().getBackend().RelaxInstruction(Inst, Relaxed);
423     while (getAssembler().getBackend().MayNeedRelaxation(Relaxed))
424       getAssembler().getBackend().RelaxInstruction(Relaxed, Relaxed);
425     EmitInstToData(Relaxed);
426     return;
427   }
428
429   // Otherwise emit to a separate fragment.
430   EmitInstToFragment(Inst);
431 }
432
433 //
434 // This helper routine returns an expression of End - Start + IntVal for use
435 // by EmitDwarfFileTable() below.
436 // 
437 const MCExpr * MCMachOStreamer::MakeStartMinusEndExpr(MCSymbol *Start,
438                                                       MCSymbol *End,
439                                                       int IntVal) {
440   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
441   const MCExpr *Res =
442     MCSymbolRefExpr::Create(End, Variant, getContext());
443   const MCExpr *RHS =
444     MCSymbolRefExpr::Create(Start, Variant, getContext());
445   const MCExpr *Res1 =
446     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS,getContext());
447   const MCExpr *Res2 =
448     MCConstantExpr::Create(IntVal, getContext());
449   const MCExpr *Res3 =
450     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, getContext());
451   return Res3;
452 }
453
454 //
455 // This emits the Dwarf file (and eventually the line) table.
456 //
457 void MCMachOStreamer::EmitDwarfFileTable(void) {
458   // For now make sure we don't put out the Dwarf file table if no .file
459   // directives were seen.
460   const std::vector<MCDwarfFile *> &MCDwarfFiles =
461     getContext().getMCDwarfFiles();
462   if (MCDwarfFiles.size() == 0)
463     return;
464
465   // This is the Mach-O section, for ELF it is the .debug_line section.
466   SwitchSection(getContext().getMachOSection("__DWARF", "__debug_line",
467                                          MCSectionMachO::S_ATTR_DEBUG,
468                                          0, SectionKind::getDataRelLocal()));
469
470   // Create a symbol at the beginning of this section.
471   MCSymbol *LineStartSym = getContext().CreateTempSymbol();
472   // Set the value of the symbol, as we are at the start of the section.
473   EmitLabel(LineStartSym);
474
475   // Create a symbol for the end of the section (to be set when we get there).
476   MCSymbol *LineEndSym = getContext().CreateTempSymbol();
477
478   // The first 4 bytes is the total length of the information for this
479   // compilation unit (not including these 4 bytes for the length).
480   EmitValue(MakeStartMinusEndExpr(LineStartSym, LineEndSym, 4), 4, 0);
481
482   // Next 2 bytes is the Version, which is Dwarf 2.
483   EmitIntValue(2, 2);
484
485   // Create a symbol for the end of the prologue (to be set when we get there).
486   MCSymbol *ProEndSym = getContext().CreateTempSymbol(); // Lprologue_end
487
488   // Length of the prologue, is the next 4 bytes.  Which is the start of the
489   // section to the end of the prologue.  Not including the 4 bytes for the
490   // total length, the 2 bytes for the version, and these 4 bytes for the
491   // length of the prologue.
492   EmitValue(MakeStartMinusEndExpr(LineStartSym, ProEndSym, (4 + 2 + 4)), 4, 0);
493
494   // Parameters of the state machine, are next.
495   //  Define the architecture-dependent minimum instruction length (in
496   //  bytes).  This value should be rather too small than too big.  */
497   //  DWARF2_LINE_MIN_INSN_LENGTH
498   EmitIntValue(1, 1);
499   //  Flag that indicates the initial value of the is_stmt_start flag.
500   //  DWARF2_LINE_DEFAULT_IS_STMT
501   EmitIntValue(1, 1);
502   //  Minimum line offset in a special line info. opcode.  This value
503   //  was chosen to give a reasonable range of values.  */
504   //  DWARF2_LINE_BASE
505   EmitIntValue(-5, 1);
506   //  Range of line offsets in a special line info. opcode.
507   //  DWARF2_LINE_RANGE
508   EmitIntValue(14, 1);
509   //  First special line opcode - leave room for the standard opcodes.
510   //  DWARF2_LINE_OPCODE_BASE
511   EmitIntValue(13, 1);
512
513   // Standard opcode lengths
514   EmitIntValue(0, 1); // length of DW_LNS_copy
515   EmitIntValue(1, 1); // length of DW_LNS_advance_pc
516   EmitIntValue(1, 1); // length of DW_LNS_advance_line
517   EmitIntValue(1, 1); // length of DW_LNS_set_file
518   EmitIntValue(1, 1); // length of DW_LNS_set_column
519   EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
520   EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
521   EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
522   EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
523   EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
524   EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
525   EmitIntValue(1, 1); // DW_LNS_set_isa
526
527   // Put out the directory and file tables.
528
529   // First the directory table.
530   const std::vector<StringRef> &MCDwarfDirs =
531     getContext().getMCDwarfDirs();
532   for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
533     EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
534     EmitBytes(StringRef("\0", 1), 0); // the null termination of the string
535   }
536   EmitIntValue(0, 1); // Terminate the directory list
537
538   // Second the file table.
539   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
540     EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
541     EmitBytes(StringRef("\0", 1), 0); // the null termination of the string
542     // FIXME the Directory number should be a .uleb128 not a .byte
543     EmitIntValue(MCDwarfFiles[i]->getDirIndex(), 1);
544     EmitIntValue(0, 1); // last modification timestamp (always 0)
545     EmitIntValue(0, 1); // filesize (always 0)
546   }
547   EmitIntValue(0, 1); // Terminate the file list
548
549   // This is the end of the prologue, so set the value of the symbol at the
550   // end of the prologue (that was used in a previous expression).
551   EmitLabel(ProEndSym);
552
553   // TODO: This is the point where the line tables would be emitted.
554
555   // If there are no line tables emited then we emit:
556   // The following DW_LNE_set_address sequence to set the address to zero
557   //   TODO test for 32-bit or 64-bit output
558   //     This is the sequence for 32-bit code
559   EmitIntValue(0, 1);
560   EmitIntValue(5, 1);
561   EmitIntValue(2, 1);
562   EmitIntValue(0, 1);
563   EmitIntValue(0, 1);
564   EmitIntValue(0, 1);
565   EmitIntValue(0, 1);
566
567   // Lastly emit the DW_LNE_end_sequence which consists of 3 bytes '00 01 01'
568   // (00 is the code for extended opcodes, followed by a ULEB128 length of the
569   // extended opcode (01), and the DW_LNE_end_sequence (01).
570   EmitIntValue(0, 1); // DW_LNS_extended_op
571   EmitIntValue(1, 1); // ULEB128 length of the extended opcode
572   EmitIntValue(1, 1); // DW_LNE_end_sequence
573
574   // This is the end of the section, so set the value of the symbol at the end
575   // of this section (that was used in a previous expression).
576   EmitLabel(LineEndSym);
577 }
578
579 void MCMachOStreamer::Finish() {
580   // Dump out the dwarf file and directory tables (soon to include line table)
581   EmitDwarfFileTable();
582
583   // We have to set the fragment atom associations so we can relax properly for
584   // Mach-O.
585
586   // First, scan the symbol table to build a lookup table from fragments to
587   // defining symbols.
588   DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
589   for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
590          ie = getAssembler().symbol_end(); it != ie; ++it) {
591     if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
592         it->getFragment()) {
593       // An atom defining symbol should never be internal to a fragment.
594       assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
595       DefiningSymbolMap[it->getFragment()] = it;
596     }
597   }
598
599   // Set the fragment atom associations by tracking the last seen atom defining
600   // symbol.
601   for (MCAssembler::iterator it = getAssembler().begin(),
602          ie = getAssembler().end(); it != ie; ++it) {
603     MCSymbolData *CurrentAtom = 0;
604     for (MCSectionData::iterator it2 = it->begin(),
605            ie2 = it->end(); it2 != ie2; ++it2) {
606       if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
607         CurrentAtom = SD;
608       it2->setAtom(CurrentAtom);
609     }
610   }
611
612   this->MCObjectStreamer::Finish();
613 }
614
615 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
616                                       raw_ostream &OS, MCCodeEmitter *CE,
617                                       bool RelaxAll) {
618   MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
619   if (RelaxAll)
620     S->getAssembler().setRelaxAll(true);
621   return S;
622 }