add symbol attribute support for the ELF .type directive.
[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, uint64_t Size,
126                                 unsigned ByteAlignment);
127   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
128     assert(0 && "macho doesn't support this directive");
129   }
130   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
131     assert(0 && "macho doesn't support this directive");
132   }
133   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
134                             unsigned Size = 0, unsigned ByteAlignment = 0);
135   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
136   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
137   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
138                                     unsigned ValueSize = 1,
139                                     unsigned MaxBytesToEmit = 0);
140   virtual void EmitValueToOffset(const MCExpr *Offset,
141                                  unsigned char Value = 0);
142   virtual void EmitInstruction(const MCInst &Inst);
143   virtual void Finish();
144
145   /// @}
146 };
147
148 } // end anonymous namespace.
149
150 void MCMachOStreamer::SwitchSection(const MCSection *Section) {
151   assert(Section && "Cannot switch to a null section!");
152   
153   // If already in this section, then this is a noop.
154   if (Section == CurSection) return;
155
156   CurSection = Section;
157   CurSectionData = &getSectionData(*Section);
158 }
159
160 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
161   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
162
163   // FIXME: We should also use offsets into Fill fragments.
164   MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
165   if (!F)
166     F = new MCDataFragment(CurSectionData);
167
168   MCSymbolData &SD = getSymbolData(*Symbol);
169   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
170   SD.setFragment(F);
171   SD.setOffset(F->getContents().size());
172
173   // This causes the reference type and weak reference flags to be cleared.
174   SD.setFlags(SD.getFlags() & ~(SF_WeakReference | SF_ReferenceTypeMask));
175   
176   Symbol->setSection(*CurSection);
177 }
178
179 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
180   switch (Flag) {
181   case MCAF_SubsectionsViaSymbols:
182     Assembler.setSubsectionsViaSymbols(true);
183     return;
184   }
185
186   assert(0 && "invalid assembler flag!");
187 }
188
189 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
190   // Only absolute symbols can be redefined.
191   assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
192          "Cannot define a symbol twice!");
193
194   // FIXME: Lift context changes into super class.
195   // FIXME: Set associated section.
196   Symbol->setValue(Value);
197 }
198
199 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
200                                           MCSymbolAttr Attribute) {
201   // Indirect symbols are handled differently, to match how 'as' handles
202   // them. This makes writing matching .o files easier.
203   if (Attribute == MCSA_IndirectSymbol) {
204     // Note that we intentionally cannot use the symbol data here; this is
205     // important for matching the string table that 'as' generates.
206     IndirectSymbolData ISD;
207     ISD.Symbol = Symbol;
208     ISD.SectionData = CurSectionData;
209     Assembler.getIndirectSymbols().push_back(ISD);
210     return;
211   }
212
213   // Adding a symbol attribute always introduces the symbol, note that an
214   // important side effect of calling getSymbolData here is to register the
215   // symbol with the assembler.
216   MCSymbolData &SD = getSymbolData(*Symbol);
217
218   // The implementation of symbol attributes is designed to match 'as', but it
219   // leaves much to desired. It doesn't really make sense to arbitrarily add and
220   // remove flags, but 'as' allows this (in particular, see .desc).
221   //
222   // In the future it might be worth trying to make these operations more well
223   // defined.
224   switch (Attribute) {
225   case MCSA_Invalid:
226   case MCSA_ELF_TypeFunction:
227   case MCSA_ELF_TypeIndFunction:
228   case MCSA_ELF_TypeObject:
229   case MCSA_ELF_TypeTLS:
230   case MCSA_ELF_TypeCommon:
231   case MCSA_ELF_TypeNoType:
232   case MCSA_IndirectSymbol:
233   case MCSA_Hidden:
234   case MCSA_Internal:
235   case MCSA_Protected:
236   case MCSA_Weak:
237   case MCSA_Local:
238     assert(0 && "Invalid symbol attribute for Mach-O!");
239     break;
240
241   case MCSA_Global:
242     SD.setExternal(true);
243     break;
244
245   case MCSA_LazyReference:
246     // FIXME: This requires -dynamic.
247     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
248     if (Symbol->isUndefined())
249       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
250     break;
251
252     // Since .reference sets the no dead strip bit, it is equivalent to
253     // .no_dead_strip in practice.
254   case MCSA_Reference:
255   case MCSA_NoDeadStrip:
256     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
257     break;
258
259   case MCSA_PrivateExtern:
260     SD.setExternal(true);
261     SD.setPrivateExtern(true);
262     break;
263
264   case MCSA_WeakReference:
265     // FIXME: This requires -dynamic.
266     if (Symbol->isUndefined())
267       SD.setFlags(SD.getFlags() | SF_WeakReference);
268     break;
269
270   case MCSA_WeakDefinition:
271     // FIXME: 'as' enforces that this is defined and global. The manual claims
272     // it has to be in a coalesced section, but this isn't enforced.
273     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
274     break;
275   }
276 }
277
278 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
279   // Encode the 'desc' value into the lowest implementation defined bits.
280   assert(DescValue == (DescValue & SF_DescFlagsMask) && 
281          "Invalid .desc value!");
282   getSymbolData(*Symbol).setFlags(DescValue & SF_DescFlagsMask);
283 }
284
285 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
286                                        unsigned ByteAlignment) {
287   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
288   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
289
290   MCSymbolData &SD = getSymbolData(*Symbol);
291   SD.setExternal(true);
292   SD.setCommon(Size, ByteAlignment);
293 }
294
295 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
296                                    unsigned Size, unsigned ByteAlignment) {
297   MCSectionData &SectData = getSectionData(*Section);
298
299   // The symbol may not be present, which only creates the section.
300   if (!Symbol)
301     return;
302
303   // FIXME: Assert that this section has the zerofill type.
304
305   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
306
307   MCSymbolData &SD = getSymbolData(*Symbol);
308
309   MCFragment *F = new MCZeroFillFragment(Size, ByteAlignment, &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 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
320   MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
321   if (!DF)
322     DF = new MCDataFragment(CurSectionData);
323   DF->getContents().append(Data.begin(), Data.end());
324 }
325
326 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
327                                 unsigned AddrSpace) {
328   new MCFillFragment(*AddValueSymbols(Value), Size, 1, CurSectionData);
329 }
330
331 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
332                                            int64_t Value, unsigned ValueSize,
333                                            unsigned MaxBytesToEmit) {
334   if (MaxBytesToEmit == 0)
335     MaxBytesToEmit = ByteAlignment;
336   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
337                       CurSectionData);
338
339   // Update the maximum alignment on the current section if necessary.
340   if (ByteAlignment > CurSectionData->getAlignment())
341     CurSectionData->setAlignment(ByteAlignment);
342 }
343
344 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
345                                         unsigned char Value) {
346   new MCOrgFragment(*Offset, Value, CurSectionData);
347 }
348
349 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
350   // Scan for values.
351   for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
352     if (Inst.getOperand(i).isExpr())
353       AddValueSymbols(Inst.getOperand(i).getExpr());
354
355   if (!Emitter)
356     llvm_unreachable("no code emitter available!");
357
358   // FIXME: Emitting an instruction should cause S_ATTR_SOME_INSTRUCTIONS to
359   //        be set for the current section.
360   // FIXME: Relocations!
361   SmallString<256> Code;
362   raw_svector_ostream VecOS(Code);
363   Emitter->EncodeInstruction(Inst, VecOS);
364   EmitBytes(VecOS.str(), 0);
365 }
366
367 void MCMachOStreamer::Finish() {
368   Assembler.Finish();
369 }
370
371 MCStreamer *llvm::createMachOStreamer(MCContext &Context, raw_ostream &OS,
372                                       MCCodeEmitter *CE) {
373   return new MCMachOStreamer(Context, OS, CE);
374 }