move the various directive enums out of the MCStreamer class
[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/MCSection.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 using namespace llvm;
23
24 namespace {
25
26 class MCMachOStreamer : public MCStreamer {
27   /// SymbolFlags - We store the value for the 'desc' symbol field in the lowest
28   /// 16 bits of the implementation defined flags.
29   enum SymbolFlags { // See <mach-o/nlist.h>.
30     SF_DescFlagsMask                        = 0xFFFF,
31
32     // Reference type flags.
33     SF_ReferenceTypeMask                    = 0x0007,
34     SF_ReferenceTypeUndefinedNonLazy        = 0x0000,
35     SF_ReferenceTypeUndefinedLazy           = 0x0001,
36     SF_ReferenceTypeDefined                 = 0x0002,
37     SF_ReferenceTypePrivateDefined          = 0x0003,
38     SF_ReferenceTypePrivateUndefinedNonLazy = 0x0004,
39     SF_ReferenceTypePrivateUndefinedLazy    = 0x0005,
40
41     // Other 'desc' flags.
42     SF_NoDeadStrip                          = 0x0020,
43     SF_WeakReference                        = 0x0040,
44     SF_WeakDefinition                       = 0x0080
45   };
46
47 private:
48   MCAssembler Assembler;
49
50   MCCodeEmitter *Emitter;
51
52   MCSectionData *CurSectionData;
53
54   DenseMap<const MCSection*, MCSectionData*> SectionMap;
55   
56   DenseMap<const MCSymbol*, MCSymbolData*> SymbolMap;
57
58 private:
59   MCFragment *getCurrentFragment() const {
60     assert(CurSectionData && "No current section!");
61
62     if (!CurSectionData->empty())
63       return &CurSectionData->getFragmentList().back();
64
65     return 0;
66   }
67
68   MCSectionData &getSectionData(const MCSection &Section) {
69     MCSectionData *&Entry = SectionMap[&Section];
70
71     if (!Entry)
72       Entry = new MCSectionData(Section, &Assembler);
73
74     return *Entry;
75   }
76
77   MCSymbolData &getSymbolData(const MCSymbol &Symbol) {
78     MCSymbolData *&Entry = SymbolMap[&Symbol];
79
80     if (!Entry)
81       Entry = new MCSymbolData(Symbol, 0, 0, &Assembler);
82
83     return *Entry;
84   }
85
86 public:
87   MCMachOStreamer(MCContext &Context, raw_ostream &_OS, MCCodeEmitter *_Emitter)
88     : MCStreamer(Context), Assembler(Context, _OS), Emitter(_Emitter),
89       CurSectionData(0) {}
90   ~MCMachOStreamer() {}
91
92   const MCExpr *AddValueSymbols(const MCExpr *Value) {
93     switch (Value->getKind()) {
94     case MCExpr::Constant:
95       break;
96
97     case MCExpr::Binary: {
98       const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
99       AddValueSymbols(BE->getLHS());
100       AddValueSymbols(BE->getRHS());
101       break;
102     }
103
104     case MCExpr::SymbolRef:
105       getSymbolData(cast<MCSymbolRefExpr>(Value)->getSymbol());
106       break;
107
108     case MCExpr::Unary:
109       AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
110       break;
111     }
112
113     return Value;
114   }
115
116   /// @name MCStreamer Interface
117   /// @{
118
119   virtual void SwitchSection(const MCSection *Section);
120   virtual void EmitLabel(MCSymbol *Symbol);
121   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
122   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
123   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
124   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
125   virtual void EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
126                                 unsigned ByteAlignment);
127   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
128                             unsigned Size = 0, unsigned ByteAlignment = 0);
129   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
130   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
131   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
132                                     unsigned ValueSize = 1,
133                                     unsigned MaxBytesToEmit = 0);
134   virtual void EmitValueToOffset(const MCExpr *Offset,
135                                  unsigned char Value = 0);
136   virtual void EmitInstruction(const MCInst &Inst);
137   virtual void Finish();
138
139   /// @}
140 };
141
142 } // end anonymous namespace.
143
144 void MCMachOStreamer::SwitchSection(const MCSection *Section) {
145   assert(Section && "Cannot switch to a null section!");
146   
147   // If already in this section, then this is a noop.
148   if (Section == CurSection) return;
149
150   CurSection = Section;
151   CurSectionData = &getSectionData(*Section);
152 }
153
154 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
155   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
156
157   // FIXME: We should also use offsets into Fill fragments.
158   MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
159   if (!F)
160     F = new MCDataFragment(CurSectionData);
161
162   MCSymbolData &SD = getSymbolData(*Symbol);
163   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
164   SD.setFragment(F);
165   SD.setOffset(F->getContents().size());
166
167   // This causes the reference type and weak reference flags to be cleared.
168   SD.setFlags(SD.getFlags() & ~(SF_WeakReference | SF_ReferenceTypeMask));
169   
170   Symbol->setSection(*CurSection);
171 }
172
173 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
174   switch (Flag) {
175   case MCAF_SubsectionsViaSymbols:
176     Assembler.setSubsectionsViaSymbols(true);
177     return;
178   }
179
180   assert(0 && "invalid assembler flag!");
181 }
182
183 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
184   // Only absolute symbols can be redefined.
185   assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
186          "Cannot define a symbol twice!");
187
188   // FIXME: Lift context changes into super class.
189   // FIXME: Set associated section.
190   Symbol->setValue(Value);
191 }
192
193 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
194                                           MCSymbolAttr Attribute) {
195   // Indirect symbols are handled differently, to match how 'as' handles
196   // them. This makes writing matching .o files easier.
197   if (Attribute == MCSA_IndirectSymbol) {
198     // Note that we intentionally cannot use the symbol data here; this is
199     // important for matching the string table that 'as' generates.
200     IndirectSymbolData ISD;
201     ISD.Symbol = Symbol;
202     ISD.SectionData = CurSectionData;
203     Assembler.getIndirectSymbols().push_back(ISD);
204     return;
205   }
206
207   // Adding a symbol attribute always introduces the symbol, note that an
208   // important side effect of calling getSymbolData here is to register the
209   // symbol with the assembler.
210   MCSymbolData &SD = getSymbolData(*Symbol);
211
212   // The implementation of symbol attributes is designed to match 'as', but it
213   // leaves much to desired. It doesn't really make sense to arbitrarily add and
214   // remove flags, but 'as' allows this (in particular, see .desc).
215   //
216   // In the future it might be worth trying to make these operations more well
217   // defined.
218   switch (Attribute) {
219   case MCSA_Invalid:
220   case MCSA_IndirectSymbol:
221   case MCSA_Hidden:
222   case MCSA_Internal:
223   case MCSA_Protected:
224   case MCSA_Weak:
225   case MCSA_Local:
226     assert(0 && "Invalid symbol attribute for Mach-O!");
227     break;
228
229   case MCSA_Global:
230     SD.setExternal(true);
231     break;
232
233   case MCSA_LazyReference:
234     // FIXME: This requires -dynamic.
235     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
236     if (Symbol->isUndefined())
237       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
238     break;
239
240     // Since .reference sets the no dead strip bit, it is equivalent to
241     // .no_dead_strip in practice.
242   case MCSA_Reference:
243   case MCSA_NoDeadStrip:
244     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
245     break;
246
247   case MCSA_PrivateExtern:
248     SD.setExternal(true);
249     SD.setPrivateExtern(true);
250     break;
251
252   case MCSA_WeakReference:
253     // FIXME: This requires -dynamic.
254     if (Symbol->isUndefined())
255       SD.setFlags(SD.getFlags() | SF_WeakReference);
256     break;
257
258   case MCSA_WeakDefinition:
259     // FIXME: 'as' enforces that this is defined and global. The manual claims
260     // it has to be in a coalesced section, but this isn't enforced.
261     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
262     break;
263   }
264 }
265
266 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
267   // Encode the 'desc' value into the lowest implementation defined bits.
268   assert(DescValue == (DescValue & SF_DescFlagsMask) && 
269          "Invalid .desc value!");
270   getSymbolData(*Symbol).setFlags(DescValue & SF_DescFlagsMask);
271 }
272
273 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
274                                        unsigned ByteAlignment) {
275   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
276   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
277
278   MCSymbolData &SD = getSymbolData(*Symbol);
279   SD.setExternal(true);
280   SD.setCommon(Size, ByteAlignment);
281 }
282
283 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
284                                    unsigned Size, unsigned ByteAlignment) {
285   MCSectionData &SectData = getSectionData(*Section);
286
287   // The symbol may not be present, which only creates the section.
288   if (!Symbol)
289     return;
290
291   // FIXME: Assert that this section has the zerofill type.
292
293   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
294
295   MCSymbolData &SD = getSymbolData(*Symbol);
296
297   MCFragment *F = new MCZeroFillFragment(Size, ByteAlignment, &SectData);
298   SD.setFragment(F);
299
300   Symbol->setSection(*Section);
301
302   // Update the maximum alignment on the zero fill section if necessary.
303   if (ByteAlignment > SectData.getAlignment())
304     SectData.setAlignment(ByteAlignment);
305 }
306
307 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
308   MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
309   if (!DF)
310     DF = new MCDataFragment(CurSectionData);
311   DF->getContents().append(Data.begin(), Data.end());
312 }
313
314 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
315                                 unsigned AddrSpace) {
316   new MCFillFragment(*AddValueSymbols(Value), Size, 1, CurSectionData);
317 }
318
319 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
320                                            int64_t Value, unsigned ValueSize,
321                                            unsigned MaxBytesToEmit) {
322   if (MaxBytesToEmit == 0)
323     MaxBytesToEmit = ByteAlignment;
324   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
325                       CurSectionData);
326
327   // Update the maximum alignment on the current section if necessary.
328   if (ByteAlignment > CurSectionData->getAlignment())
329     CurSectionData->setAlignment(ByteAlignment);
330 }
331
332 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
333                                         unsigned char Value) {
334   new MCOrgFragment(*Offset, Value, CurSectionData);
335 }
336
337 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
338   // Scan for values.
339   for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
340     if (Inst.getOperand(i).isExpr())
341       AddValueSymbols(Inst.getOperand(i).getExpr());
342
343   if (!Emitter)
344     llvm_unreachable("no code emitter available!");
345
346   // FIXME: Emitting an instruction should cause S_ATTR_SOME_INSTRUCTIONS to
347   //        be set for the current section.
348   // FIXME: Relocations!
349   SmallString<256> Code;
350   raw_svector_ostream VecOS(Code);
351   Emitter->EncodeInstruction(Inst, VecOS);
352   EmitBytes(VecOS.str(), 0);
353 }
354
355 void MCMachOStreamer::Finish() {
356   Assembler.Finish();
357 }
358
359 MCStreamer *llvm::createMachOStreamer(MCContext &Context, raw_ostream &OS,
360                                       MCCodeEmitter *CE) {
361   return new MCMachOStreamer(Context, OS, CE);
362 }