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