1 //===- lib/MC/MCMachOStreamer.cpp - Mach-O Object Output ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCStreamer.h"
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/MCValue.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
26 class MCMachOStreamer : public MCStreamer {
27 /// SymbolFlags - We store the value for the 'desc' symbol field in the lowest
28 /// 16 bits of the implementation defined flags.
29 enum SymbolFlags { // See <mach-o/nlist.h>.
30 SF_DescFlagsMask = 0xFFFF,
32 // Reference type flags.
33 SF_ReferenceTypeMask = 0x0007,
34 SF_ReferenceTypeUndefinedNonLazy = 0x0000,
35 SF_ReferenceTypeUndefinedLazy = 0x0001,
36 SF_ReferenceTypeDefined = 0x0002,
37 SF_ReferenceTypePrivateDefined = 0x0003,
38 SF_ReferenceTypePrivateUndefinedNonLazy = 0x0004,
39 SF_ReferenceTypePrivateUndefinedLazy = 0x0005,
41 // Other 'desc' flags.
42 SF_NoDeadStrip = 0x0020,
43 SF_WeakReference = 0x0040,
44 SF_WeakDefinition = 0x0080
48 MCAssembler Assembler;
49 MCCodeEmitter *Emitter;
50 MCSectionData *CurSectionData;
51 DenseMap<const MCSection*, MCSectionData*> SectionMap;
52 DenseMap<const MCSymbol*, MCSymbolData*> SymbolMap;
55 MCFragment *getCurrentFragment() const {
56 assert(CurSectionData && "No current section!");
58 if (!CurSectionData->empty())
59 return &CurSectionData->getFragmentList().back();
64 MCSectionData &getSectionData(const MCSection &Section) {
65 MCSectionData *&Entry = SectionMap[&Section];
68 Entry = new MCSectionData(Section, &Assembler);
73 MCSymbolData &getSymbolData(const MCSymbol &Symbol) {
74 MCSymbolData *&Entry = SymbolMap[&Symbol];
77 Entry = new MCSymbolData(Symbol, 0, 0, &Assembler);
83 MCMachOStreamer(MCContext &Context, raw_ostream &_OS, MCCodeEmitter *_Emitter)
84 : MCStreamer(Context), Assembler(Context, _OS), Emitter(_Emitter),
88 const MCExpr *AddValueSymbols(const MCExpr *Value) {
89 switch (Value->getKind()) {
90 case MCExpr::Target: assert(0 && "Can't handle target exprs yet!");
91 case MCExpr::Constant:
94 case MCExpr::Binary: {
95 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
96 AddValueSymbols(BE->getLHS());
97 AddValueSymbols(BE->getRHS());
101 case MCExpr::SymbolRef:
102 getSymbolData(cast<MCSymbolRefExpr>(Value)->getSymbol());
106 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
113 /// @name MCStreamer Interface
116 virtual void SwitchSection(const MCSection *Section);
117 virtual void EmitLabel(MCSymbol *Symbol);
118 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
119 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
120 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
121 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
122 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
123 unsigned ByteAlignment);
124 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
125 assert(0 && "macho doesn't support this directive");
127 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
128 assert(0 && "macho doesn't support this directive");
130 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
131 unsigned Size = 0, unsigned ByteAlignment = 0);
132 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
133 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
134 virtual void EmitGPRel32Value(const MCExpr *Value) {
135 assert(0 && "macho doesn't support this directive");
137 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
138 unsigned ValueSize = 1,
139 unsigned MaxBytesToEmit = 0);
140 virtual void EmitValueToOffset(const MCExpr *Offset,
141 unsigned char Value = 0);
143 virtual void EmitFileDirective(StringRef Filename) {
144 errs() << "FIXME: MCMachoStreamer:EmitFileDirective not implemented\n";
146 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
147 errs() << "FIXME: MCMachoStreamer:EmitDwarfFileDirective not implemented\n";
150 virtual void EmitInstruction(const MCInst &Inst);
151 virtual void Finish();
156 } // end anonymous namespace.
158 void MCMachOStreamer::SwitchSection(const MCSection *Section) {
159 assert(Section && "Cannot switch to a null section!");
161 // If already in this section, then this is a noop.
162 if (Section == CurSection) return;
164 CurSection = Section;
165 CurSectionData = &getSectionData(*Section);
168 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
169 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
171 // FIXME: We should also use offsets into Fill fragments.
172 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
174 F = new MCDataFragment(CurSectionData);
176 MCSymbolData &SD = getSymbolData(*Symbol);
177 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
179 SD.setOffset(F->getContents().size());
181 // This causes the reference type and weak reference flags to be cleared.
182 SD.setFlags(SD.getFlags() & ~(SF_WeakReference | SF_ReferenceTypeMask));
184 Symbol->setSection(*CurSection);
187 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
189 case MCAF_SubsectionsViaSymbols:
190 Assembler.setSubsectionsViaSymbols(true);
194 assert(0 && "invalid assembler flag!");
197 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
198 // Only absolute symbols can be redefined.
199 assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
200 "Cannot define a symbol twice!");
202 // FIXME: Lift context changes into super class.
203 // FIXME: Set associated section.
204 Symbol->setValue(Value);
207 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
208 MCSymbolAttr Attribute) {
209 // Indirect symbols are handled differently, to match how 'as' handles
210 // them. This makes writing matching .o files easier.
211 if (Attribute == MCSA_IndirectSymbol) {
212 // Note that we intentionally cannot use the symbol data here; this is
213 // important for matching the string table that 'as' generates.
214 IndirectSymbolData ISD;
216 ISD.SectionData = CurSectionData;
217 Assembler.getIndirectSymbols().push_back(ISD);
221 // Adding a symbol attribute always introduces the symbol, note that an
222 // important side effect of calling getSymbolData here is to register the
223 // symbol with the assembler.
224 MCSymbolData &SD = getSymbolData(*Symbol);
226 // The implementation of symbol attributes is designed to match 'as', but it
227 // leaves much to desired. It doesn't really make sense to arbitrarily add and
228 // remove flags, but 'as' allows this (in particular, see .desc).
230 // In the future it might be worth trying to make these operations more well
234 case MCSA_ELF_TypeFunction:
235 case MCSA_ELF_TypeIndFunction:
236 case MCSA_ELF_TypeObject:
237 case MCSA_ELF_TypeTLS:
238 case MCSA_ELF_TypeCommon:
239 case MCSA_ELF_TypeNoType:
240 case MCSA_IndirectSymbol:
246 assert(0 && "Invalid symbol attribute for Mach-O!");
250 SD.setExternal(true);
253 case MCSA_LazyReference:
254 // FIXME: This requires -dynamic.
255 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
256 if (Symbol->isUndefined())
257 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
260 // Since .reference sets the no dead strip bit, it is equivalent to
261 // .no_dead_strip in practice.
263 case MCSA_NoDeadStrip:
264 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
267 case MCSA_PrivateExtern:
268 SD.setExternal(true);
269 SD.setPrivateExtern(true);
272 case MCSA_WeakReference:
273 // FIXME: This requires -dynamic.
274 if (Symbol->isUndefined())
275 SD.setFlags(SD.getFlags() | SF_WeakReference);
278 case MCSA_WeakDefinition:
279 // FIXME: 'as' enforces that this is defined and global. The manual claims
280 // it has to be in a coalesced section, but this isn't enforced.
281 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
286 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
287 // Encode the 'desc' value into the lowest implementation defined bits.
288 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
289 "Invalid .desc value!");
290 getSymbolData(*Symbol).setFlags(DescValue & SF_DescFlagsMask);
293 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
294 unsigned ByteAlignment) {
295 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
296 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
298 MCSymbolData &SD = getSymbolData(*Symbol);
299 SD.setExternal(true);
300 SD.setCommon(Size, ByteAlignment);
303 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
304 unsigned Size, unsigned ByteAlignment) {
305 MCSectionData &SectData = getSectionData(*Section);
307 // The symbol may not be present, which only creates the section.
311 // FIXME: Assert that this section has the zerofill type.
313 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
315 MCSymbolData &SD = getSymbolData(*Symbol);
317 MCFragment *F = new MCZeroFillFragment(Size, ByteAlignment, &SectData);
320 Symbol->setSection(*Section);
322 // Update the maximum alignment on the zero fill section if necessary.
323 if (ByteAlignment > SectData.getAlignment())
324 SectData.setAlignment(ByteAlignment);
327 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
328 MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
330 DF = new MCDataFragment(CurSectionData);
331 DF->getContents().append(Data.begin(), Data.end());
334 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
335 unsigned AddrSpace) {
336 // Assume the front-end will have evaluate things absolute expressions, so
337 // just create data + fixup.
338 MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
340 DF = new MCDataFragment(CurSectionData);
342 // Avoid fixups when possible.
344 if (Value->EvaluateAsAbsolute(AbsValue)) {
345 // FIXME: Endianness assumption.
346 for (unsigned i = 0; i != Size; ++i)
347 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
349 DF->getFixups().push_back(MCAsmFixup(DF->getContents().size(),
350 *AddValueSymbols(Value), Size));
351 DF->getContents().resize(DF->getContents().size() + Size, 0);
355 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
356 int64_t Value, unsigned ValueSize,
357 unsigned MaxBytesToEmit) {
358 if (MaxBytesToEmit == 0)
359 MaxBytesToEmit = ByteAlignment;
360 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
363 // Update the maximum alignment on the current section if necessary.
364 if (ByteAlignment > CurSectionData->getAlignment())
365 CurSectionData->setAlignment(ByteAlignment);
368 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
369 unsigned char Value) {
370 new MCOrgFragment(*Offset, Value, CurSectionData);
373 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
375 for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
376 if (Inst.getOperand(i).isExpr())
377 AddValueSymbols(Inst.getOperand(i).getExpr());
380 llvm_unreachable("no code emitter available!");
382 CurSectionData->setHasInstructions(true);
384 // FIXME: Relocations!
385 SmallVector<MCFixup, 4> Fixups;
386 SmallString<256> Code;
387 raw_svector_ostream VecOS(Code);
388 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
389 EmitBytes(VecOS.str(), 0);
392 void MCMachOStreamer::Finish() {
396 MCStreamer *llvm::createMachOStreamer(MCContext &Context, raw_ostream &OS,
398 return new MCMachOStreamer(Context, OS, CE);