MCMachOStreamer.cpp revision 226633
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/MC/MCAsmBackend.h"
24#include "llvm/Support/Dwarf.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/raw_ostream.h"
27
28using namespace llvm;
29
30namespace {
31
32class MCMachOStreamer : public MCObjectStreamer {
33private:
34  virtual void EmitInstToData(const MCInst &Inst);
35
36public:
37  MCMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
38                  raw_ostream &OS, MCCodeEmitter *Emitter)
39    : MCObjectStreamer(Context, MAB, OS, Emitter) {}
40
41  /// @name MCStreamer Interface
42  /// @{
43
44  virtual void InitSections();
45  virtual void EmitLabel(MCSymbol *Symbol);
46  virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
47                                   MCSymbol *EHSymbol);
48  virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
49  virtual void EmitThumbFunc(MCSymbol *Func);
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                                     unsigned ByteAlignment) {
72    assert(0 && "macho doesn't support this directive");
73  }
74  virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
75                            unsigned Size = 0, unsigned ByteAlignment = 0);
76  virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
77                              uint64_t Size, unsigned ByteAlignment = 0);
78  virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
79  virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
80                                    unsigned ValueSize = 1,
81                                    unsigned MaxBytesToEmit = 0);
82  virtual void EmitCodeAlignment(unsigned ByteAlignment,
83                                 unsigned MaxBytesToEmit = 0);
84
85  virtual void EmitFileDirective(StringRef Filename) {
86    // FIXME: Just ignore the .file; it isn't important enough to fail the
87    // entire assembly.
88
89    //report_fatal_error("unsupported directive: '.file'");
90  }
91
92  virtual void Finish();
93
94  /// @}
95};
96
97} // end anonymous namespace.
98
99void MCMachOStreamer::InitSections() {
100  SwitchSection(getContext().getMachOSection("__TEXT", "__text",
101                                    MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
102                                    0, SectionKind::getText()));
103
104}
105
106void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
107                                          MCSymbol *EHSymbol) {
108  MCSymbolData &SD =
109    getAssembler().getOrCreateSymbolData(*Symbol);
110  if (SD.isExternal())
111    EmitSymbolAttribute(EHSymbol, MCSA_Global);
112  if (SD.getFlags() & SF_WeakDefinition)
113    EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
114  if (SD.isPrivateExtern())
115    EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
116}
117
118void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
119  assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
120
121  // isSymbolLinkerVisible uses the section.
122  Symbol->setSection(*getCurrentSection());
123  // We have to create a new fragment if this is an atom defining symbol,
124  // fragments cannot span atoms.
125  if (getAssembler().isSymbolLinkerVisible(*Symbol))
126    new MCDataFragment(getCurrentSectionData());
127
128  MCObjectStreamer::EmitLabel(Symbol);
129
130  MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
131  // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
132  // to clear the weak reference and weak definition bits too, but the
133  // implementation was buggy. For now we just try to match 'as', for
134  // diffability.
135  //
136  // FIXME: Cleanup this code, these bits should be emitted based on semantic
137  // properties, not on the order of definition, etc.
138  SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
139}
140
141void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
142  // Let the target do whatever target specific stuff it needs to do.
143  getAssembler().getBackend().HandleAssemblerFlag(Flag);
144  // Do any generic stuff we need to do.
145  switch (Flag) {
146  case MCAF_SyntaxUnified: return; // no-op here.
147  case MCAF_Code16: return; // Change parsing mode; no-op here.
148  case MCAF_Code32: return; // Change parsing mode; no-op here.
149  case MCAF_Code64: return; // Change parsing mode; no-op here.
150  case MCAF_SubsectionsViaSymbols:
151    getAssembler().setSubsectionsViaSymbols(true);
152    return;
153  default:
154    llvm_unreachable("invalid assembler flag!");
155  }
156}
157
158void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
159  // FIXME: Flag the function ISA as thumb with DW_AT_APPLE_isa.
160
161  // Remember that the function is a thumb function. Fixup and relocation
162  // values will need adjusted.
163  getAssembler().setIsThumbFunc(Symbol);
164
165  // Mark the thumb bit on the symbol.
166  MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
167  SD.setFlags(SD.getFlags() | SF_ThumbFunc);
168}
169
170void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
171  // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
172  // MCObjectStreamer.
173  // FIXME: Lift context changes into super class.
174  getAssembler().getOrCreateSymbolData(*Symbol);
175  Symbol->setVariableValue(AddValueSymbols(Value));
176}
177
178void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
179                                          MCSymbolAttr Attribute) {
180  // Indirect symbols are handled differently, to match how 'as' handles
181  // them. This makes writing matching .o files easier.
182  if (Attribute == MCSA_IndirectSymbol) {
183    // Note that we intentionally cannot use the symbol data here; this is
184    // important for matching the string table that 'as' generates.
185    IndirectSymbolData ISD;
186    ISD.Symbol = Symbol;
187    ISD.SectionData = getCurrentSectionData();
188    getAssembler().getIndirectSymbols().push_back(ISD);
189    return;
190  }
191
192  // Adding a symbol attribute always introduces the symbol, note that an
193  // important side effect of calling getOrCreateSymbolData here is to register
194  // the symbol with the assembler.
195  MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
196
197  // The implementation of symbol attributes is designed to match 'as', but it
198  // leaves much to desired. It doesn't really make sense to arbitrarily add and
199  // remove flags, but 'as' allows this (in particular, see .desc).
200  //
201  // In the future it might be worth trying to make these operations more well
202  // defined.
203  switch (Attribute) {
204  case MCSA_Invalid:
205  case MCSA_ELF_TypeFunction:
206  case MCSA_ELF_TypeIndFunction:
207  case MCSA_ELF_TypeObject:
208  case MCSA_ELF_TypeTLS:
209  case MCSA_ELF_TypeCommon:
210  case MCSA_ELF_TypeNoType:
211  case MCSA_ELF_TypeGnuUniqueObject:
212  case MCSA_Hidden:
213  case MCSA_IndirectSymbol:
214  case MCSA_Internal:
215  case MCSA_Protected:
216  case MCSA_Weak:
217  case MCSA_Local:
218    assert(0 && "Invalid symbol attribute for Mach-O!");
219    break;
220
221  case MCSA_Global:
222    SD.setExternal(true);
223    // This effectively clears the undefined lazy bit, in Darwin 'as', although
224    // it isn't very consistent because it implements this as part of symbol
225    // lookup.
226    //
227    // FIXME: Cleanup this code, these bits should be emitted based on semantic
228    // properties, not on the order of definition, etc.
229    SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
230    break;
231
232  case MCSA_LazyReference:
233    // FIXME: This requires -dynamic.
234    SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
235    if (Symbol->isUndefined())
236      SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
237    break;
238
239    // Since .reference sets the no dead strip bit, it is equivalent to
240    // .no_dead_strip in practice.
241  case MCSA_Reference:
242  case MCSA_NoDeadStrip:
243    SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
244    break;
245
246  case MCSA_SymbolResolver:
247    SD.setFlags(SD.getFlags() | SF_SymbolResolver);
248    break;
249
250  case MCSA_PrivateExtern:
251    SD.setExternal(true);
252    SD.setPrivateExtern(true);
253    break;
254
255  case MCSA_WeakReference:
256    // FIXME: This requires -dynamic.
257    if (Symbol->isUndefined())
258      SD.setFlags(SD.getFlags() | SF_WeakReference);
259    break;
260
261  case MCSA_WeakDefinition:
262    // FIXME: 'as' enforces that this is defined and global. The manual claims
263    // it has to be in a coalesced section, but this isn't enforced.
264    SD.setFlags(SD.getFlags() | SF_WeakDefinition);
265    break;
266
267  case MCSA_WeakDefAutoPrivate:
268    SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
269    break;
270  }
271}
272
273void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
274  // Encode the 'desc' value into the lowest implementation defined bits.
275  assert(DescValue == (DescValue & SF_DescFlagsMask) &&
276         "Invalid .desc value!");
277  getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
278    DescValue & SF_DescFlagsMask);
279}
280
281void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
282                                       unsigned ByteAlignment) {
283  // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
284  assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
285
286  MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
287  SD.setExternal(true);
288  SD.setCommon(Size, ByteAlignment);
289}
290
291void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
292                                   unsigned Size, unsigned ByteAlignment) {
293  MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
294
295  // The symbol may not be present, which only creates the section.
296  if (!Symbol)
297    return;
298
299  // FIXME: Assert that this section has the zerofill type.
300
301  assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
302
303  MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
304
305  // Emit an align fragment if necessary.
306  if (ByteAlignment != 1)
307    new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
308
309  MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
310  SD.setFragment(F);
311
312  Symbol->setSection(*Section);
313
314  // Update the maximum alignment on the zero fill section if necessary.
315  if (ByteAlignment > SectData.getAlignment())
316    SectData.setAlignment(ByteAlignment);
317}
318
319// This should always be called with the thread local bss section.  Like the
320// .zerofill directive this doesn't actually switch sections on us.
321void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
322                                     uint64_t Size, unsigned ByteAlignment) {
323  EmitZerofill(Section, Symbol, Size, ByteAlignment);
324  return;
325}
326
327void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
328  // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
329  // MCObjectStreamer.
330  getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
331}
332
333void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
334                                           int64_t Value, unsigned ValueSize,
335                                           unsigned MaxBytesToEmit) {
336  // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
337  // MCObjectStreamer.
338  if (MaxBytesToEmit == 0)
339    MaxBytesToEmit = ByteAlignment;
340  new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
341                      getCurrentSectionData());
342
343  // Update the maximum alignment on the current section if necessary.
344  if (ByteAlignment > getCurrentSectionData()->getAlignment())
345    getCurrentSectionData()->setAlignment(ByteAlignment);
346}
347
348void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
349                                        unsigned MaxBytesToEmit) {
350  // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
351  // MCObjectStreamer.
352  if (MaxBytesToEmit == 0)
353    MaxBytesToEmit = ByteAlignment;
354  MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
355                                           getCurrentSectionData());
356  F->setEmitNops(true);
357
358  // Update the maximum alignment on the current section if necessary.
359  if (ByteAlignment > getCurrentSectionData()->getAlignment())
360    getCurrentSectionData()->setAlignment(ByteAlignment);
361}
362
363void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
364  MCDataFragment *DF = getOrCreateDataFragment();
365
366  SmallVector<MCFixup, 4> Fixups;
367  SmallString<256> Code;
368  raw_svector_ostream VecOS(Code);
369  getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
370  VecOS.flush();
371
372  // Add the fixups and data.
373  for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
374    Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
375    DF->addFixup(Fixups[i]);
376  }
377  DF->getContents().append(Code.begin(), Code.end());
378}
379
380void MCMachOStreamer::Finish() {
381  EmitFrames(true);
382
383  // We have to set the fragment atom associations so we can relax properly for
384  // Mach-O.
385
386  // First, scan the symbol table to build a lookup table from fragments to
387  // defining symbols.
388  DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
389  for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
390         ie = getAssembler().symbol_end(); it != ie; ++it) {
391    if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
392        it->getFragment()) {
393      // An atom defining symbol should never be internal to a fragment.
394      assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
395      DefiningSymbolMap[it->getFragment()] = it;
396    }
397  }
398
399  // Set the fragment atom associations by tracking the last seen atom defining
400  // symbol.
401  for (MCAssembler::iterator it = getAssembler().begin(),
402         ie = getAssembler().end(); it != ie; ++it) {
403    MCSymbolData *CurrentAtom = 0;
404    for (MCSectionData::iterator it2 = it->begin(),
405           ie2 = it->end(); it2 != ie2; ++it2) {
406      if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
407        CurrentAtom = SD;
408      it2->setAtom(CurrentAtom);
409    }
410  }
411
412  this->MCObjectStreamer::Finish();
413}
414
415MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
416                                      raw_ostream &OS, MCCodeEmitter *CE,
417                                      bool RelaxAll) {
418  MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE);
419  if (RelaxAll)
420    S->getAssembler().setRelaxAll(true);
421  return S;
422}
423