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