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