Fix pr24486.
[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/MCObjectFileInfo.h"
22 #include "llvm/MC/MCObjectStreamer.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCSectionMachO.h"
25 #include "llvm/MC/MCSymbolMachO.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Support/raw_ostream.h"
30
31 using namespace llvm;
32
33 namespace {
34
35 class MCMachOStreamer : public MCObjectStreamer {
36 private:
37   /// LabelSections - true if each section change should emit a linker local
38   /// label for use in relocations for assembler local references. Obviates the
39   /// need for local relocations. False by default.
40   bool LabelSections;
41
42   bool DWARFMustBeAtTheEnd;
43   bool CreatedADWARFSection;
44
45   /// HasSectionLabel - map of which sections have already had a non-local
46   /// label emitted to them. Used so we don't emit extraneous linker local
47   /// labels in the middle of the section.
48   DenseMap<const MCSection*, bool> HasSectionLabel;
49
50   void EmitInstToData(const MCInst &Inst, const MCSubtargetInfo &STI) override;
51
52   void EmitDataRegion(DataRegionData::KindTy Kind);
53   void EmitDataRegionEnd();
54
55 public:
56   MCMachOStreamer(MCContext &Context, MCAsmBackend &MAB, raw_pwrite_stream &OS,
57                   MCCodeEmitter *Emitter, bool DWARFMustBeAtTheEnd, bool label)
58       : MCObjectStreamer(Context, MAB, OS, Emitter), LabelSections(label),
59         DWARFMustBeAtTheEnd(DWARFMustBeAtTheEnd), CreatedADWARFSection(false) {}
60
61   /// state management
62   void reset() override {
63     HasSectionLabel.clear();
64     MCObjectStreamer::reset();
65   }
66
67   /// @name MCStreamer Interface
68   /// @{
69
70   void ChangeSection(MCSection *Sect, const MCExpr *Subsect) override;
71   void EmitLabel(MCSymbol *Symbol) override;
72   void EmitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol) override;
73   void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
74   void EmitLinkerOptions(ArrayRef<std::string> Options) override;
75   void EmitDataRegion(MCDataRegionType Kind) override;
76   void EmitVersionMin(MCVersionMinType Kind, unsigned Major,
77                       unsigned Minor, unsigned Update) override;
78   void EmitThumbFunc(MCSymbol *Func) override;
79   bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
80   void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
81   void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
82                         unsigned ByteAlignment) override;
83   void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {
84     llvm_unreachable("macho doesn't support this directive");
85   }
86   void EmitCOFFSymbolStorageClass(int StorageClass) override {
87     llvm_unreachable("macho doesn't support this directive");
88   }
89   void EmitCOFFSymbolType(int Type) override {
90     llvm_unreachable("macho doesn't support this directive");
91   }
92   void EndCOFFSymbolDef() override {
93     llvm_unreachable("macho doesn't support this directive");
94   }
95   void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
96                              unsigned ByteAlignment) override;
97   void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
98                     uint64_t Size = 0, unsigned ByteAlignment = 0) override;
99   void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
100                       unsigned ByteAlignment = 0) override;
101
102   void EmitFileDirective(StringRef Filename) override {
103     // FIXME: Just ignore the .file; it isn't important enough to fail the
104     // entire assembly.
105
106     // report_fatal_error("unsupported directive: '.file'");
107   }
108
109   void EmitIdent(StringRef IdentString) override {
110     llvm_unreachable("macho doesn't support this directive");
111   }
112
113   void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override {
114     getAssembler().getLOHContainer().addDirective(Kind, Args);
115   }
116
117   void FinishImpl() override;
118 };
119
120 } // end anonymous namespace.
121
122 static bool canGoAfterDWARF(const MCSectionMachO &MSec) {
123   // These sections are created by the assembler itself after the end of
124   // the .s file.
125   StringRef SegName = MSec.getSegmentName();
126   StringRef SecName = MSec.getSectionName();
127
128   if (SegName == "__LD" && SecName == "__compact_unwind")
129     return true;
130
131   if (SegName == "__IMPORT") {
132     if (SecName == "__jump_table")
133       return true;
134
135     if (SecName == "__pointers")
136       return true;
137   }
138
139   if (SegName == "__TEXT" && SecName == "__eh_frame")
140     return true;
141
142   if (SegName == "__DATA" && SecName == "__nl_symbol_ptr")
143     return true;
144
145   return false;
146 }
147
148 void MCMachOStreamer::ChangeSection(MCSection *Section,
149                                     const MCExpr *Subsection) {
150   // Change the section normally.
151   bool Created = MCObjectStreamer::changeSectionImpl(Section, Subsection);
152   const MCSectionMachO &MSec = *cast<MCSectionMachO>(Section);
153   StringRef SegName = MSec.getSegmentName();
154   if (SegName == "__DWARF")
155     CreatedADWARFSection = true;
156   else if (Created && DWARFMustBeAtTheEnd && !canGoAfterDWARF(MSec))
157     assert(!CreatedADWARFSection && "Creating regular section after DWARF");
158
159   // Output a linker-local symbol so we don't need section-relative local
160   // relocations. The linker hates us when we do that.
161   if (LabelSections && !HasSectionLabel[Section] &&
162       !Section->getBeginSymbol()) {
163     MCSymbol *Label = getContext().createLinkerPrivateTempSymbol();
164     Section->setBeginSymbol(Label);
165     HasSectionLabel[Section] = true;
166   }
167 }
168
169 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
170                                           MCSymbol *EHSymbol) {
171   getAssembler().registerSymbol(*Symbol);
172   if (Symbol->isExternal())
173     EmitSymbolAttribute(EHSymbol, MCSA_Global);
174   if (cast<MCSymbolMachO>(Symbol)->isWeakDefinition())
175     EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
176   if (Symbol->isPrivateExtern())
177     EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
178 }
179
180 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
181   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
182
183   // We have to create a new fragment if this is an atom defining symbol,
184   // fragments cannot span atoms.
185   if (getAssembler().isSymbolLinkerVisible(*Symbol))
186     insert(new MCDataFragment());
187
188   MCObjectStreamer::EmitLabel(Symbol);
189
190   // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
191   // to clear the weak reference and weak definition bits too, but the
192   // implementation was buggy. For now we just try to match 'as', for
193   // diffability.
194   //
195   // FIXME: Cleanup this code, these bits should be emitted based on semantic
196   // properties, not on the order of definition, etc.
197   cast<MCSymbolMachO>(Symbol)->clearReferenceType();
198 }
199
200 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
201   if (!getAssembler().getBackend().hasDataInCodeSupport())
202     return;
203   // Create a temporary label to mark the start of the data region.
204   MCSymbol *Start = getContext().createTempSymbol();
205   EmitLabel(Start);
206   // Record the region for the object writer to use.
207   DataRegionData Data = { Kind, Start, nullptr };
208   std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
209   Regions.push_back(Data);
210 }
211
212 void MCMachOStreamer::EmitDataRegionEnd() {
213   if (!getAssembler().getBackend().hasDataInCodeSupport())
214     return;
215   std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
216   assert(!Regions.empty() && "Mismatched .end_data_region!");
217   DataRegionData &Data = Regions.back();
218   assert(!Data.End && "Mismatched .end_data_region!");
219   // Create a temporary label to mark the end of the data region.
220   Data.End = getContext().createTempSymbol();
221   EmitLabel(Data.End);
222 }
223
224 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
225   // Let the target do whatever target specific stuff it needs to do.
226   getAssembler().getBackend().handleAssemblerFlag(Flag);
227   // Do any generic stuff we need to do.
228   switch (Flag) {
229   case MCAF_SyntaxUnified: return; // no-op here.
230   case MCAF_Code16: return; // Change parsing mode; no-op here.
231   case MCAF_Code32: return; // Change parsing mode; no-op here.
232   case MCAF_Code64: return; // Change parsing mode; no-op here.
233   case MCAF_SubsectionsViaSymbols:
234     getAssembler().setSubsectionsViaSymbols(true);
235     return;
236   }
237 }
238
239 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
240   getAssembler().getLinkerOptions().push_back(Options);
241 }
242
243 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
244   switch (Kind) {
245   case MCDR_DataRegion:
246     EmitDataRegion(DataRegionData::Data);
247     return;
248   case MCDR_DataRegionJT8:
249     EmitDataRegion(DataRegionData::JumpTable8);
250     return;
251   case MCDR_DataRegionJT16:
252     EmitDataRegion(DataRegionData::JumpTable16);
253     return;
254   case MCDR_DataRegionJT32:
255     EmitDataRegion(DataRegionData::JumpTable32);
256     return;
257   case MCDR_DataRegionEnd:
258     EmitDataRegionEnd();
259     return;
260   }
261 }
262
263 void MCMachOStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
264                                      unsigned Minor, unsigned Update) {
265   getAssembler().setVersionMinInfo(Kind, Major, Minor, Update);
266 }
267
268 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
269   // Remember that the function is a thumb function. Fixup and relocation
270   // values will need adjusted.
271   getAssembler().setIsThumbFunc(Symbol);
272   cast<MCSymbolMachO>(Symbol)->setThumbFunc();
273 }
274
275 bool MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Sym,
276                                           MCSymbolAttr Attribute) {
277   MCSymbolMachO *Symbol = cast<MCSymbolMachO>(Sym);
278
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->setReferenceTypeUndefinedLazy(false);
328     break;
329
330   case MCSA_LazyReference:
331     // FIXME: This requires -dynamic.
332     Symbol->setNoDeadStrip();
333     if (Symbol->isUndefined())
334       Symbol->setReferenceTypeUndefinedLazy(true);
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->setNoDeadStrip();
342     break;
343
344   case MCSA_SymbolResolver:
345     Symbol->setSymbolResolver();
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->setWeakReference();
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->setWeakDefinition();
363     break;
364
365   case MCSA_WeakDefAutoPrivate:
366     Symbol->setWeakDefinition();
367     Symbol->setWeakReference();
368     break;
369   }
370
371   return true;
372 }
373
374 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
375   // Encode the 'desc' value into the lowest implementation defined bits.
376   getAssembler().registerSymbol(*Symbol);
377   cast<MCSymbolMachO>(Symbol)->setDesc(DescValue);
378 }
379
380 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
381                                        unsigned ByteAlignment) {
382   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
383   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
384
385   getAssembler().registerSymbol(*Symbol);
386   Symbol->setExternal(true);
387   Symbol->setCommon(Size, ByteAlignment);
388 }
389
390 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
391                                             unsigned ByteAlignment) {
392   // '.lcomm' is equivalent to '.zerofill'.
393   return EmitZerofill(getContext().getObjectFileInfo()->getDataBSSSection(),
394                       Symbol, Size, ByteAlignment);
395 }
396
397 void MCMachOStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
398                                    uint64_t Size, unsigned ByteAlignment) {
399   getAssembler().registerSection(*Section);
400
401   // The symbol may not be present, which only creates the section.
402   if (!Symbol)
403     return;
404
405   // On darwin all virtual sections have zerofill type.
406   assert(Section->isVirtualSection() && "Section does not have zerofill type!");
407
408   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
409
410   getAssembler().registerSymbol(*Symbol);
411
412   // Emit an align fragment if necessary.
413   if (ByteAlignment != 1)
414     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, Section);
415
416   MCFragment *F = new MCFillFragment(0, 0, Size, Section);
417   Symbol->setFragment(F);
418
419   // Update the maximum alignment on the zero fill section if necessary.
420   if (ByteAlignment > Section->getAlignment())
421     Section->setAlignment(ByteAlignment);
422 }
423
424 // This should always be called with the thread local bss section.  Like the
425 // .zerofill directive this doesn't actually switch sections on us.
426 void MCMachOStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
427                                      uint64_t Size, unsigned ByteAlignment) {
428   EmitZerofill(Section, Symbol, Size, ByteAlignment);
429   return;
430 }
431
432 void MCMachOStreamer::EmitInstToData(const MCInst &Inst,
433                                      const MCSubtargetInfo &STI) {
434   MCDataFragment *DF = getOrCreateDataFragment();
435
436   SmallVector<MCFixup, 4> Fixups;
437   SmallString<256> Code;
438   raw_svector_ostream VecOS(Code);
439   getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
440
441   // Add the fixups and data.
442   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
443     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
444     DF->getFixups().push_back(Fixups[i]);
445   }
446   DF->getContents().append(Code.begin(), Code.end());
447 }
448
449 void MCMachOStreamer::FinishImpl() {
450   EmitFrames(&getAssembler().getBackend());
451
452   // We have to set the fragment atom associations so we can relax properly for
453   // Mach-O.
454
455   // First, scan the symbol table to build a lookup table from fragments to
456   // defining symbols.
457   DenseMap<const MCFragment *, const MCSymbol *> DefiningSymbolMap;
458   for (const MCSymbol &Symbol : getAssembler().symbols()) {
459     if (getAssembler().isSymbolLinkerVisible(Symbol) && Symbol.isInSection() &&
460         !Symbol.isVariable()) {
461       // An atom defining symbol should never be internal to a fragment.
462       assert(Symbol.getOffset() == 0 &&
463              "Invalid offset in atom defining symbol!");
464       DefiningSymbolMap[Symbol.getFragment()] = &Symbol;
465     }
466   }
467
468   // Set the fragment atom associations by tracking the last seen atom defining
469   // symbol.
470   for (MCAssembler::iterator it = getAssembler().begin(),
471          ie = getAssembler().end(); it != ie; ++it) {
472     const MCSymbol *CurrentAtom = nullptr;
473     for (MCSection::iterator it2 = it->begin(), ie2 = it->end(); it2 != ie2;
474          ++it2) {
475       if (const MCSymbol *Symbol = DefiningSymbolMap.lookup(it2))
476         CurrentAtom = Symbol;
477       it2->setAtom(CurrentAtom);
478     }
479   }
480
481   this->MCObjectStreamer::FinishImpl();
482 }
483
484 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
485                                       raw_pwrite_stream &OS, MCCodeEmitter *CE,
486                                       bool RelaxAll, bool DWARFMustBeAtTheEnd,
487                                       bool LabelSections) {
488   MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE,
489                                            DWARFMustBeAtTheEnd, LabelSections);
490   const Triple &TT = Context.getObjectFileInfo()->getTargetTriple();
491   if (TT.isOSDarwin()) {
492     unsigned Major, Minor, Update;
493     TT.getOSVersion(Major, Minor, Update);
494     // If there is a version specified, Major will be non-zero.
495     if (Major)
496       S->EmitVersionMin((TT.isMacOSX() ?
497                         MCVM_OSXVersionMin : MCVM_IOSVersionMin),
498                         Major, Minor, Update);
499   }
500   if (RelaxAll)
501     S->getAssembler().setRelaxAll(true);
502   return S;
503 }