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/Support/ErrorHandling.h"
20 #include "llvm/Support/raw_ostream.h"
25 class MCMachOStreamer : public MCStreamer {
26 /// SymbolFlags - We store the value for the 'desc' symbol field in the lowest
27 /// 16 bits of the implementation defined flags.
28 enum SymbolFlags { // See <mach-o/nlist.h>.
29 SF_DescFlagsMask = 0xFFFF,
31 // Reference type flags.
32 SF_ReferenceTypeMask = 0x0007,
33 SF_ReferenceTypeUndefinedNonLazy = 0x0000,
34 SF_ReferenceTypeUndefinedLazy = 0x0001,
35 SF_ReferenceTypeDefined = 0x0002,
36 SF_ReferenceTypePrivateDefined = 0x0003,
37 SF_ReferenceTypePrivateUndefinedNonLazy = 0x0004,
38 SF_ReferenceTypePrivateUndefinedLazy = 0x0005,
40 // Other 'desc' flags.
41 SF_NoDeadStrip = 0x0020,
42 SF_WeakReference = 0x0040,
43 SF_WeakDefinition = 0x0080
47 MCAssembler Assembler;
48 MCCodeEmitter *Emitter;
49 MCSectionData *CurSectionData;
52 MCFragment *getCurrentFragment() const {
53 assert(CurSectionData && "No current section!");
55 if (!CurSectionData->empty())
56 return &CurSectionData->getFragmentList().back();
62 MCMachOStreamer(MCContext &Context, raw_ostream &_OS, MCCodeEmitter *_Emitter)
63 : MCStreamer(Context), Assembler(Context, _OS), Emitter(_Emitter),
67 const MCExpr *AddValueSymbols(const MCExpr *Value) {
68 switch (Value->getKind()) {
69 case MCExpr::Target: assert(0 && "Can't handle target exprs yet!");
70 case MCExpr::Constant:
73 case MCExpr::Binary: {
74 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
75 AddValueSymbols(BE->getLHS());
76 AddValueSymbols(BE->getRHS());
80 case MCExpr::SymbolRef:
81 Assembler.getOrCreateSymbolData(
82 cast<MCSymbolRefExpr>(Value)->getSymbol());
86 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
93 /// @name MCStreamer Interface
96 virtual void SwitchSection(const MCSection *Section);
97 virtual void EmitLabel(MCSymbol *Symbol);
98 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
99 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
100 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
101 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
102 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
103 unsigned ByteAlignment);
104 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
105 assert(0 && "macho doesn't support this directive");
107 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
108 assert(0 && "macho doesn't support this directive");
110 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
111 unsigned Size = 0, unsigned ByteAlignment = 0);
112 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
113 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
114 virtual void EmitGPRel32Value(const MCExpr *Value) {
115 assert(0 && "macho doesn't support this directive");
117 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
118 unsigned ValueSize = 1,
119 unsigned MaxBytesToEmit = 0);
120 virtual void EmitCodeAlignment(unsigned ByteAlignment,
121 unsigned MaxBytesToEmit = 0);
122 virtual void EmitValueToOffset(const MCExpr *Offset,
123 unsigned char Value = 0);
125 virtual void EmitFileDirective(StringRef Filename) {
126 errs() << "FIXME: MCMachoStreamer:EmitFileDirective not implemented\n";
128 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
129 errs() << "FIXME: MCMachoStreamer:EmitDwarfFileDirective not implemented\n";
132 virtual void EmitInstruction(const MCInst &Inst);
133 virtual void Finish();
138 } // end anonymous namespace.
140 void MCMachOStreamer::SwitchSection(const MCSection *Section) {
141 assert(Section && "Cannot switch to a null section!");
143 // If already in this section, then this is a noop.
144 if (Section == CurSection) return;
146 CurSection = Section;
147 CurSectionData = &Assembler.getOrCreateSectionData(*Section);
150 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
151 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
153 // FIXME: We should also use offsets into Fill fragments.
154 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
156 F = new MCDataFragment(CurSectionData);
158 MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
159 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
161 SD.setOffset(F->getContents().size());
163 // This causes the reference type and weak reference flags to be cleared.
164 SD.setFlags(SD.getFlags() & ~(SF_WeakReference | SF_ReferenceTypeMask));
166 Symbol->setSection(*CurSection);
169 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
171 case MCAF_SubsectionsViaSymbols:
172 Assembler.setSubsectionsViaSymbols(true);
176 assert(0 && "invalid assembler flag!");
179 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
180 // Only absolute symbols can be redefined.
181 assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
182 "Cannot define a symbol twice!");
184 // FIXME: Lift context changes into super class.
185 // FIXME: Set associated section.
186 Symbol->setValue(Value);
189 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
190 MCSymbolAttr Attribute) {
191 // Indirect symbols are handled differently, to match how 'as' handles
192 // them. This makes writing matching .o files easier.
193 if (Attribute == MCSA_IndirectSymbol) {
194 // Note that we intentionally cannot use the symbol data here; this is
195 // important for matching the string table that 'as' generates.
196 IndirectSymbolData ISD;
198 ISD.SectionData = CurSectionData;
199 Assembler.getIndirectSymbols().push_back(ISD);
203 // Adding a symbol attribute always introduces the symbol, note that an
204 // important side effect of calling getOrCreateSymbolData here is to register
205 // the symbol with the assembler.
206 MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
208 // The implementation of symbol attributes is designed to match 'as', but it
209 // leaves much to desired. It doesn't really make sense to arbitrarily add and
210 // remove flags, but 'as' allows this (in particular, see .desc).
212 // In the future it might be worth trying to make these operations more well
216 case MCSA_ELF_TypeFunction:
217 case MCSA_ELF_TypeIndFunction:
218 case MCSA_ELF_TypeObject:
219 case MCSA_ELF_TypeTLS:
220 case MCSA_ELF_TypeCommon:
221 case MCSA_ELF_TypeNoType:
222 case MCSA_IndirectSymbol:
228 assert(0 && "Invalid symbol attribute for Mach-O!");
232 SD.setExternal(true);
235 case MCSA_LazyReference:
236 // FIXME: This requires -dynamic.
237 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
238 if (Symbol->isUndefined())
239 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
242 // Since .reference sets the no dead strip bit, it is equivalent to
243 // .no_dead_strip in practice.
245 case MCSA_NoDeadStrip:
246 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
249 case MCSA_PrivateExtern:
250 SD.setExternal(true);
251 SD.setPrivateExtern(true);
254 case MCSA_WeakReference:
255 // FIXME: This requires -dynamic.
256 if (Symbol->isUndefined())
257 SD.setFlags(SD.getFlags() | SF_WeakReference);
260 case MCSA_WeakDefinition:
261 // FIXME: 'as' enforces that this is defined and global. The manual claims
262 // it has to be in a coalesced section, but this isn't enforced.
263 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
268 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
269 // Encode the 'desc' value into the lowest implementation defined bits.
270 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
271 "Invalid .desc value!");
272 Assembler.getOrCreateSymbolData(*Symbol).setFlags(DescValue&SF_DescFlagsMask);
275 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
276 unsigned ByteAlignment) {
277 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
278 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
280 MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
281 SD.setExternal(true);
282 SD.setCommon(Size, ByteAlignment);
285 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
286 unsigned Size, unsigned ByteAlignment) {
287 MCSectionData &SectData = Assembler.getOrCreateSectionData(*Section);
289 // The symbol may not be present, which only creates the section.
293 // FIXME: Assert that this section has the zerofill type.
295 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
297 MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
299 MCFragment *F = new MCZeroFillFragment(Size, ByteAlignment, &SectData);
302 Symbol->setSection(*Section);
304 // Update the maximum alignment on the zero fill section if necessary.
305 if (ByteAlignment > SectData.getAlignment())
306 SectData.setAlignment(ByteAlignment);
309 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
310 MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
312 DF = new MCDataFragment(CurSectionData);
313 DF->getContents().append(Data.begin(), Data.end());
316 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
317 unsigned AddrSpace) {
318 MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
320 DF = new MCDataFragment(CurSectionData);
322 // Avoid fixups when possible.
324 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
325 // FIXME: Endianness assumption.
326 for (unsigned i = 0; i != Size; ++i)
327 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
329 DF->getFixups().push_back(MCAsmFixup(DF->getContents().size(),
330 *AddValueSymbols(Value),
331 MCFixup::getKindForSize(Size)));
332 DF->getContents().resize(DF->getContents().size() + Size, 0);
336 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
337 int64_t Value, unsigned ValueSize,
338 unsigned MaxBytesToEmit) {
339 if (MaxBytesToEmit == 0)
340 MaxBytesToEmit = ByteAlignment;
341 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
342 false /* EmitNops */, CurSectionData);
344 // Update the maximum alignment on the current section if necessary.
345 if (ByteAlignment > CurSectionData->getAlignment())
346 CurSectionData->setAlignment(ByteAlignment);
349 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
350 unsigned MaxBytesToEmit) {
351 if (MaxBytesToEmit == 0)
352 MaxBytesToEmit = ByteAlignment;
353 // FIXME the 0x90 is the default x86 1 byte nop opcode.
354 new MCAlignFragment(ByteAlignment, 0x90, 1, MaxBytesToEmit,
355 true /* EmitNops */, CurSectionData);
357 // Update the maximum alignment on the current section if necessary.
358 if (ByteAlignment > CurSectionData->getAlignment())
359 CurSectionData->setAlignment(ByteAlignment);
362 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
363 unsigned char Value) {
364 new MCOrgFragment(*Offset, Value, CurSectionData);
367 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
369 for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
370 if (Inst.getOperand(i).isExpr())
371 AddValueSymbols(Inst.getOperand(i).getExpr());
374 llvm_unreachable("no code emitter available!");
376 CurSectionData->setHasInstructions(true);
378 SmallVector<MCFixup, 4> Fixups;
379 SmallString<256> Code;
380 raw_svector_ostream VecOS(Code);
381 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
384 // Add the fixups and data.
385 MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
387 DF = new MCDataFragment(CurSectionData);
388 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
389 MCFixup &F = Fixups[i];
390 DF->getFixups().push_back(MCAsmFixup(DF->getContents().size()+F.getOffset(),
394 DF->getContents().append(Code.begin(), Code.end());
397 void MCMachOStreamer::Finish() {
401 MCStreamer *llvm::createMachOStreamer(MCContext &Context, raw_ostream &OS,
403 return new MCMachOStreamer(Context, OS, CE);