f1dc34944dda29bf25880105fd25de46c5a0f5ea
[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/MCMachOSymbolFlags.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetAsmBackend.h"
23
24 using namespace llvm;
25
26 namespace {
27
28 class MCMachOStreamer : public MCStreamer {
29
30 private:
31   MCAssembler Assembler;
32   MCSectionData *CurSectionData;
33
34   /// Track the current atom for each section.
35   DenseMap<const MCSectionData*, MCSymbolData*> CurrentAtomMap;
36
37 private:
38   MCFragment *getCurrentFragment() const {
39     assert(CurSectionData && "No current section!");
40
41     if (!CurSectionData->empty())
42       return &CurSectionData->getFragmentList().back();
43
44     return 0;
45   }
46
47   /// Get a data fragment to write into, creating a new one if the current
48   /// fragment is not a data fragment.
49   MCDataFragment *getOrCreateDataFragment() const {
50     MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
51     if (!F)
52       F = createDataFragment();
53     return F;
54   }
55
56   /// Create a new data fragment in the current section.
57   MCDataFragment *createDataFragment() const {
58     MCDataFragment *DF = new MCDataFragment(CurSectionData);
59     DF->setAtom(CurrentAtomMap.lookup(CurSectionData));
60     return DF;
61   }
62
63 public:
64   MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
65                   raw_ostream &_OS, MCCodeEmitter *_Emitter)
66     : MCStreamer(Context), Assembler(Context, TAB, *_Emitter, _OS),
67       CurSectionData(0) {}
68   ~MCMachOStreamer() {}
69
70   MCAssembler &getAssembler() { return Assembler; }
71
72   const MCExpr *AddValueSymbols(const MCExpr *Value) {
73     switch (Value->getKind()) {
74     case MCExpr::Target: assert(0 && "Can't handle target exprs yet!");
75     case MCExpr::Constant:
76       break;
77
78     case MCExpr::Binary: {
79       const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
80       AddValueSymbols(BE->getLHS());
81       AddValueSymbols(BE->getRHS());
82       break;
83     }
84
85     case MCExpr::SymbolRef:
86       Assembler.getOrCreateSymbolData(
87         cast<MCSymbolRefExpr>(Value)->getSymbol());
88       break;
89
90     case MCExpr::Unary:
91       AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
92       break;
93     }
94
95     return Value;
96   }
97
98   /// @name MCStreamer Interface
99   /// @{
100
101   virtual void SwitchSection(const MCSection *Section);
102   virtual void EmitLabel(MCSymbol *Symbol);
103   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
104   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
105   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
106   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
107   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
108                                 unsigned ByteAlignment);
109   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
110     assert(0 && "macho doesn't support this directive");
111   }
112   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
113     assert(0 && "macho doesn't support this directive");
114   }
115   virtual void EmitCOFFSymbolType(int Type) {
116     assert(0 && "macho doesn't support this directive");
117   }
118   virtual void EndCOFFSymbolDef() {
119     assert(0 && "macho doesn't support this directive");
120   }
121   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
122     assert(0 && "macho doesn't support this directive");
123   }
124   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
125     assert(0 && "macho doesn't support this directive");
126   }
127   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
128                             unsigned Size = 0, unsigned ByteAlignment = 0);
129   virtual void EmitTBSSSymbol(MCSymbol *Symbol, uint64_t Size,
130                               unsigned ByteAlignment = 0);
131   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
132   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
133   virtual void EmitGPRel32Value(const MCExpr *Value) {
134     assert(0 && "macho doesn't support this directive");
135   }
136   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
137                                     unsigned ValueSize = 1,
138                                     unsigned MaxBytesToEmit = 0);
139   virtual void EmitCodeAlignment(unsigned ByteAlignment,
140                                  unsigned MaxBytesToEmit = 0);
141   virtual void EmitValueToOffset(const MCExpr *Offset,
142                                  unsigned char Value = 0);
143   
144   virtual void EmitFileDirective(StringRef Filename) {
145     report_fatal_error("unsupported directive: '.file'");
146   }
147   virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
148     report_fatal_error("unsupported directive: '.file'");
149   }
150   
151   virtual void EmitInstruction(const MCInst &Inst);
152   virtual void Finish();
153
154   /// @}
155 };
156
157 } // end anonymous namespace.
158
159 void MCMachOStreamer::SwitchSection(const MCSection *Section) {
160   assert(Section && "Cannot switch to a null section!");
161   
162   // If already in this section, then this is a noop.
163   if (Section == CurSection) return;
164
165   CurSection = Section;
166   CurSectionData = &Assembler.getOrCreateSectionData(*Section);
167 }
168
169 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
170   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
171   assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
172   assert(CurSection && "Cannot emit before setting section!");
173
174   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
175
176   // Update the current atom map, if necessary.
177   bool MustCreateFragment = false;
178   if (Assembler.isSymbolLinkerVisible(&SD)) {
179     CurrentAtomMap[CurSectionData] = &SD;
180
181     // We have to create a new fragment, fragments cannot span atoms.
182     MustCreateFragment = true;
183   }
184
185   // FIXME: This is wasteful, we don't necessarily need to create a data
186   // fragment. Instead, we should mark the symbol as pointing into the data
187   // fragment if it exists, otherwise we should just queue the label and set its
188   // fragment pointer when we emit the next fragment.
189   MCDataFragment *F =
190     MustCreateFragment ? createDataFragment() : getOrCreateDataFragment();
191   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
192   SD.setFragment(F);
193   SD.setOffset(F->getContents().size());
194
195   // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
196   // to clear the weak reference and weak definition bits too, but the
197   // implementation was buggy. For now we just try to match 'as', for
198   // diffability.
199   //
200   // FIXME: Cleanup this code, these bits should be emitted based on semantic
201   // properties, not on the order of definition, etc.
202   SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
203   
204   Symbol->setSection(*CurSection);
205 }
206
207 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
208   switch (Flag) {
209   case MCAF_SubsectionsViaSymbols:
210     Assembler.setSubsectionsViaSymbols(true);
211     return;
212   }
213
214   assert(0 && "invalid assembler flag!");
215 }
216
217 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
218   // FIXME: Lift context changes into super class.
219   Symbol->setVariableValue(AddValueSymbols(Value));
220 }
221
222 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
223                                           MCSymbolAttr Attribute) {
224   // Indirect symbols are handled differently, to match how 'as' handles
225   // them. This makes writing matching .o files easier.
226   if (Attribute == MCSA_IndirectSymbol) {
227     // Note that we intentionally cannot use the symbol data here; this is
228     // important for matching the string table that 'as' generates.
229     IndirectSymbolData ISD;
230     ISD.Symbol = Symbol;
231     ISD.SectionData = CurSectionData;
232     Assembler.getIndirectSymbols().push_back(ISD);
233     return;
234   }
235
236   // Adding a symbol attribute always introduces the symbol, note that an
237   // important side effect of calling getOrCreateSymbolData here is to register
238   // the symbol with the assembler.
239   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
240
241   // The implementation of symbol attributes is designed to match 'as', but it
242   // leaves much to desired. It doesn't really make sense to arbitrarily add and
243   // remove flags, but 'as' allows this (in particular, see .desc).
244   //
245   // In the future it might be worth trying to make these operations more well
246   // defined.
247   switch (Attribute) {
248   case MCSA_Invalid:
249   case MCSA_ELF_TypeFunction:
250   case MCSA_ELF_TypeIndFunction:
251   case MCSA_ELF_TypeObject:
252   case MCSA_ELF_TypeTLS:
253   case MCSA_ELF_TypeCommon:
254   case MCSA_ELF_TypeNoType:
255   case MCSA_IndirectSymbol:
256   case MCSA_Hidden:
257   case MCSA_Internal:
258   case MCSA_Protected:
259   case MCSA_Weak:
260   case MCSA_Local:
261     assert(0 && "Invalid symbol attribute for Mach-O!");
262     break;
263
264   case MCSA_Global:
265     SD.setExternal(true);
266     // This effectively clears the undefined lazy bit, in Darwin 'as', although
267     // it isn't very consistent because it implements this as part of symbol
268     // lookup.
269     //
270     // FIXME: Cleanup this code, these bits should be emitted based on semantic
271     // properties, not on the order of definition, etc.
272     SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
273     break;
274
275   case MCSA_LazyReference:
276     // FIXME: This requires -dynamic.
277     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
278     if (Symbol->isUndefined())
279       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
280     break;
281
282     // Since .reference sets the no dead strip bit, it is equivalent to
283     // .no_dead_strip in practice.
284   case MCSA_Reference:
285   case MCSA_NoDeadStrip:
286     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
287     break;
288
289   case MCSA_PrivateExtern:
290     SD.setExternal(true);
291     SD.setPrivateExtern(true);
292     break;
293
294   case MCSA_WeakReference:
295     // FIXME: This requires -dynamic.
296     if (Symbol->isUndefined())
297       SD.setFlags(SD.getFlags() | SF_WeakReference);
298     break;
299
300   case MCSA_WeakDefinition:
301     // FIXME: 'as' enforces that this is defined and global. The manual claims
302     // it has to be in a coalesced section, but this isn't enforced.
303     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
304     break;
305   }
306 }
307
308 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
309   // Encode the 'desc' value into the lowest implementation defined bits.
310   assert(DescValue == (DescValue & SF_DescFlagsMask) && 
311          "Invalid .desc value!");
312   Assembler.getOrCreateSymbolData(*Symbol).setFlags(DescValue&SF_DescFlagsMask);
313 }
314
315 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
316                                        unsigned ByteAlignment) {
317   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
318   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
319
320   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
321   SD.setExternal(true);
322   SD.setCommon(Size, ByteAlignment);
323 }
324
325 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
326                                    unsigned Size, unsigned ByteAlignment) {
327   MCSectionData &SectData = Assembler.getOrCreateSectionData(*Section);
328
329   // The symbol may not be present, which only creates the section.
330   if (!Symbol)
331     return;
332
333   // FIXME: Assert that this section has the zerofill type.
334
335   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
336
337   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
338
339   // Emit an align fragment if necessary.
340   if (ByteAlignment != 1)
341     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
342
343   MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
344   SD.setFragment(F);
345   if (Assembler.isSymbolLinkerVisible(&SD))
346     F->setAtom(&SD);
347
348   Symbol->setSection(*Section);
349
350   // Update the maximum alignment on the zero fill section if necessary.
351   if (ByteAlignment > SectData.getAlignment())
352     SectData.setAlignment(ByteAlignment);
353 }
354
355 void MCMachOStreamer::EmitTBSSSymbol(MCSymbol *Symbol, uint64_t Size,
356                                      unsigned ByteAlignment) {
357   assert(false && "Implement me!");
358 }
359
360 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
361   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
362 }
363
364 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
365                                 unsigned AddrSpace) {
366   MCDataFragment *DF = getOrCreateDataFragment();
367
368   // Avoid fixups when possible.
369   int64_t AbsValue;
370   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
371     // FIXME: Endianness assumption.
372     for (unsigned i = 0; i != Size; ++i)
373       DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
374   } else {
375     DF->addFixup(MCAsmFixup(DF->getContents().size(), *AddValueSymbols(Value),
376                             MCFixup::getKindForSize(Size)));
377     DF->getContents().resize(DF->getContents().size() + Size, 0);
378   }
379 }
380
381 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
382                                            int64_t Value, unsigned ValueSize,
383                                            unsigned MaxBytesToEmit) {
384   if (MaxBytesToEmit == 0)
385     MaxBytesToEmit = ByteAlignment;
386   MCFragment *F = new MCAlignFragment(ByteAlignment, Value, ValueSize,
387                                       MaxBytesToEmit, CurSectionData);
388   F->setAtom(CurrentAtomMap.lookup(CurSectionData));
389
390   // Update the maximum alignment on the current section if necessary.
391   if (ByteAlignment > CurSectionData->getAlignment())
392     CurSectionData->setAlignment(ByteAlignment);
393 }
394
395 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
396                                         unsigned MaxBytesToEmit) {
397   if (MaxBytesToEmit == 0)
398     MaxBytesToEmit = ByteAlignment;
399   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
400                                            CurSectionData);
401   F->setEmitNops(true);
402   F->setAtom(CurrentAtomMap.lookup(CurSectionData));
403
404   // Update the maximum alignment on the current section if necessary.
405   if (ByteAlignment > CurSectionData->getAlignment())
406     CurSectionData->setAlignment(ByteAlignment);
407 }
408
409 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
410                                         unsigned char Value) {
411   MCFragment *F = new MCOrgFragment(*Offset, Value, CurSectionData);
412   F->setAtom(CurrentAtomMap.lookup(CurSectionData));
413 }
414
415 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
416   // Scan for values.
417   for (unsigned i = Inst.getNumOperands(); i--; )
418     if (Inst.getOperand(i).isExpr())
419       AddValueSymbols(Inst.getOperand(i).getExpr());
420
421   CurSectionData->setHasInstructions(true);
422
423   // FIXME-PERF: Common case is that we don't need to relax, encode directly
424   // onto the data fragments buffers.
425
426   SmallVector<MCFixup, 4> Fixups;
427   SmallString<256> Code;
428   raw_svector_ostream VecOS(Code);
429   Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
430   VecOS.flush();
431
432   // FIXME: Eliminate this copy.
433   SmallVector<MCAsmFixup, 4> AsmFixups;
434   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
435     MCFixup &F = Fixups[i];
436     AsmFixups.push_back(MCAsmFixup(F.getOffset(), *F.getValue(),
437                                    F.getKind()));
438   }
439
440   // See if we might need to relax this instruction, if so it needs its own
441   // fragment.
442   //
443   // FIXME-PERF: Support target hook to do a fast path that avoids the encoder,
444   // when we can immediately tell that we will get something which might need
445   // relaxation (and compute its size).
446   //
447   // FIXME-PERF: We should also be smart about immediately relaxing instructions
448   // which we can already show will never possibly fit (we can also do a very
449   // good job of this before we do the first relaxation pass, because we have
450   // total knowledge about undefined symbols at that point). Even now, though,
451   // we can do a decent job, especially on Darwin where scattering means that we
452   // are going to often know that we can never fully resolve a fixup.
453   if (Assembler.getBackend().MayNeedRelaxation(Inst, AsmFixups)) {
454     MCInstFragment *IF = new MCInstFragment(Inst, CurSectionData);
455     IF->setAtom(CurrentAtomMap.lookup(CurSectionData));
456
457     // Add the fixups and data.
458     //
459     // FIXME: Revisit this design decision when relaxation is done, we may be
460     // able to get away with not storing any extra data in the MCInst.
461     IF->getCode() = Code;
462     IF->getFixups() = AsmFixups;
463
464     return;
465   }
466
467   // Add the fixups and data.
468   MCDataFragment *DF = getOrCreateDataFragment();
469   for (unsigned i = 0, e = AsmFixups.size(); i != e; ++i) {
470     AsmFixups[i].Offset += DF->getContents().size();
471     DF->addFixup(AsmFixups[i]);
472   }
473   DF->getContents().append(Code.begin(), Code.end());
474 }
475
476 void MCMachOStreamer::Finish() {
477   Assembler.Finish();
478 }
479
480 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
481                                       raw_ostream &OS, MCCodeEmitter *CE,
482                                       bool RelaxAll) {
483   MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
484   if (RelaxAll)
485     S->getAssembler().setRelaxAll(true);
486   return S;
487 }