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/MCMachOSymbolFlags.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetAsmBackend.h"
28 class MCMachOStreamer : public MCStreamer {
31 MCAssembler Assembler;
32 MCSectionData *CurSectionData;
34 /// Track the current atom for each section.
35 DenseMap<const MCSectionData*, MCSymbolData*> CurrentAtomMap;
38 MCFragment *getCurrentFragment() const {
39 assert(CurSectionData && "No current section!");
41 if (!CurSectionData->empty())
42 return &CurSectionData->getFragmentList().back();
47 /// Get a data fragment to write into, creating a new one if the current
48 /// fragment is not a data fragment.
49 MCDataFragment *getOrCreateDataFragment() const {
50 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
52 F = createDataFragment();
56 /// Create a new data fragment in the current section.
57 MCDataFragment *createDataFragment() const {
58 MCDataFragment *DF = new MCDataFragment(CurSectionData);
59 DF->setAtom(CurrentAtomMap.lookup(CurSectionData));
64 MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
65 raw_ostream &_OS, MCCodeEmitter *_Emitter)
66 : MCStreamer(Context), Assembler(Context, TAB, *_Emitter, _OS),
70 MCAssembler &getAssembler() { return Assembler; }
72 const MCExpr *AddValueSymbols(const MCExpr *Value) {
73 switch (Value->getKind()) {
74 case MCExpr::Target: assert(0 && "Can't handle target exprs yet!");
75 case MCExpr::Constant:
78 case MCExpr::Binary: {
79 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
80 AddValueSymbols(BE->getLHS());
81 AddValueSymbols(BE->getRHS());
85 case MCExpr::SymbolRef:
86 Assembler.getOrCreateSymbolData(
87 cast<MCSymbolRefExpr>(Value)->getSymbol());
91 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
98 /// @name MCStreamer Interface
101 virtual void SwitchSection(const MCSection *Section);
102 virtual void EmitLabel(MCSymbol *Symbol);
103 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
104 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
105 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
106 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
107 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
108 unsigned ByteAlignment);
109 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
110 assert(0 && "macho doesn't support this directive");
112 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
113 assert(0 && "macho doesn't support this directive");
115 virtual void EmitCOFFSymbolType(int Type) {
116 assert(0 && "macho doesn't support this directive");
118 virtual void EndCOFFSymbolDef() {
119 assert(0 && "macho doesn't support this directive");
121 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
122 assert(0 && "macho doesn't support this directive");
124 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
125 assert(0 && "macho doesn't support this directive");
127 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
128 unsigned Size = 0, unsigned ByteAlignment = 0);
129 virtual void EmitTBSSSymbol(MCSymbol *Symbol, uint64_t Size,
130 unsigned ByteAlignment = 0);
131 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
132 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
133 virtual void EmitGPRel32Value(const MCExpr *Value) {
134 assert(0 && "macho doesn't support this directive");
136 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
137 unsigned ValueSize = 1,
138 unsigned MaxBytesToEmit = 0);
139 virtual void EmitCodeAlignment(unsigned ByteAlignment,
140 unsigned MaxBytesToEmit = 0);
141 virtual void EmitValueToOffset(const MCExpr *Offset,
142 unsigned char Value = 0);
144 virtual void EmitFileDirective(StringRef Filename) {
145 errs() << "FIXME: MCMachoStreamer:EmitFileDirective not implemented\n";
147 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
148 errs() << "FIXME: MCMachoStreamer:EmitDwarfFileDirective not implemented\n";
151 virtual void EmitInstruction(const MCInst &Inst);
152 virtual void Finish();
157 } // end anonymous namespace.
159 void MCMachOStreamer::SwitchSection(const MCSection *Section) {
160 assert(Section && "Cannot switch to a null section!");
162 // If already in this section, then this is a noop.
163 if (Section == CurSection) return;
165 CurSection = Section;
166 CurSectionData = &Assembler.getOrCreateSectionData(*Section);
169 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
170 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
171 assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
172 assert(CurSection && "Cannot emit before setting section!");
174 MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
176 // Update the current atom map, if necessary.
177 bool MustCreateFragment = false;
178 if (Assembler.isSymbolLinkerVisible(&SD)) {
179 CurrentAtomMap[CurSectionData] = &SD;
181 // We have to create a new fragment, fragments cannot span atoms.
182 MustCreateFragment = true;
185 // FIXME: This is wasteful, we don't necessarily need to create a data
186 // fragment. Instead, we should mark the symbol as pointing into the data
187 // fragment if it exists, otherwise we should just queue the label and set its
188 // fragment pointer when we emit the next fragment.
190 MustCreateFragment ? createDataFragment() : getOrCreateDataFragment();
191 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
193 SD.setOffset(F->getContents().size());
195 // This causes the reference type and weak reference flags to be cleared.
196 SD.setFlags(SD.getFlags() & ~(SF_WeakReference | SF_ReferenceTypeMask));
198 Symbol->setSection(*CurSection);
201 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
203 case MCAF_SubsectionsViaSymbols:
204 Assembler.setSubsectionsViaSymbols(true);
208 assert(0 && "invalid assembler flag!");
211 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
212 // FIXME: Lift context changes into super class.
213 Symbol->setVariableValue(AddValueSymbols(Value));
216 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
217 MCSymbolAttr Attribute) {
218 // Indirect symbols are handled differently, to match how 'as' handles
219 // them. This makes writing matching .o files easier.
220 if (Attribute == MCSA_IndirectSymbol) {
221 // Note that we intentionally cannot use the symbol data here; this is
222 // important for matching the string table that 'as' generates.
223 IndirectSymbolData ISD;
225 ISD.SectionData = CurSectionData;
226 Assembler.getIndirectSymbols().push_back(ISD);
230 // Adding a symbol attribute always introduces the symbol, note that an
231 // important side effect of calling getOrCreateSymbolData here is to register
232 // the symbol with the assembler.
233 MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
235 // The implementation of symbol attributes is designed to match 'as', but it
236 // leaves much to desired. It doesn't really make sense to arbitrarily add and
237 // remove flags, but 'as' allows this (in particular, see .desc).
239 // In the future it might be worth trying to make these operations more well
243 case MCSA_ELF_TypeFunction:
244 case MCSA_ELF_TypeIndFunction:
245 case MCSA_ELF_TypeObject:
246 case MCSA_ELF_TypeTLS:
247 case MCSA_ELF_TypeCommon:
248 case MCSA_ELF_TypeNoType:
249 case MCSA_IndirectSymbol:
255 assert(0 && "Invalid symbol attribute for Mach-O!");
259 SD.setExternal(true);
262 case MCSA_LazyReference:
263 // FIXME: This requires -dynamic.
264 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
265 if (Symbol->isUndefined())
266 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
269 // Since .reference sets the no dead strip bit, it is equivalent to
270 // .no_dead_strip in practice.
272 case MCSA_NoDeadStrip:
273 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
276 case MCSA_PrivateExtern:
277 SD.setExternal(true);
278 SD.setPrivateExtern(true);
281 case MCSA_WeakReference:
282 // FIXME: This requires -dynamic.
283 if (Symbol->isUndefined())
284 SD.setFlags(SD.getFlags() | SF_WeakReference);
287 case MCSA_WeakDefinition:
288 // FIXME: 'as' enforces that this is defined and global. The manual claims
289 // it has to be in a coalesced section, but this isn't enforced.
290 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
295 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
296 // Encode the 'desc' value into the lowest implementation defined bits.
297 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
298 "Invalid .desc value!");
299 Assembler.getOrCreateSymbolData(*Symbol).setFlags(DescValue&SF_DescFlagsMask);
302 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
303 unsigned ByteAlignment) {
304 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
305 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
307 MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
308 SD.setExternal(true);
309 SD.setCommon(Size, ByteAlignment);
312 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
313 unsigned Size, unsigned ByteAlignment) {
314 MCSectionData &SectData = Assembler.getOrCreateSectionData(*Section);
316 // The symbol may not be present, which only creates the section.
320 // FIXME: Assert that this section has the zerofill type.
322 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
324 MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
326 // Emit an align fragment if necessary.
327 if (ByteAlignment != 1)
328 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
330 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
332 if (Assembler.isSymbolLinkerVisible(&SD))
335 Symbol->setSection(*Section);
337 // Update the maximum alignment on the zero fill section if necessary.
338 if (ByteAlignment > SectData.getAlignment())
339 SectData.setAlignment(ByteAlignment);
342 void MCMachOStreamer::EmitTBSSSymbol(MCSymbol *Symbol, uint64_t Size,
343 unsigned ByteAlignment) {
344 assert(false && "Implement me!");
347 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
348 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
351 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
352 unsigned AddrSpace) {
353 MCDataFragment *DF = getOrCreateDataFragment();
355 // Avoid fixups when possible.
357 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
358 // FIXME: Endianness assumption.
359 for (unsigned i = 0; i != Size; ++i)
360 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
362 DF->addFixup(MCAsmFixup(DF->getContents().size(), *AddValueSymbols(Value),
363 MCFixup::getKindForSize(Size)));
364 DF->getContents().resize(DF->getContents().size() + Size, 0);
368 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
369 int64_t Value, unsigned ValueSize,
370 unsigned MaxBytesToEmit) {
371 if (MaxBytesToEmit == 0)
372 MaxBytesToEmit = ByteAlignment;
373 MCFragment *F = new MCAlignFragment(ByteAlignment, Value, ValueSize,
374 MaxBytesToEmit, CurSectionData);
375 F->setAtom(CurrentAtomMap.lookup(CurSectionData));
377 // Update the maximum alignment on the current section if necessary.
378 if (ByteAlignment > CurSectionData->getAlignment())
379 CurSectionData->setAlignment(ByteAlignment);
382 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
383 unsigned MaxBytesToEmit) {
384 if (MaxBytesToEmit == 0)
385 MaxBytesToEmit = ByteAlignment;
386 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
388 F->setEmitNops(true);
389 F->setAtom(CurrentAtomMap.lookup(CurSectionData));
391 // Update the maximum alignment on the current section if necessary.
392 if (ByteAlignment > CurSectionData->getAlignment())
393 CurSectionData->setAlignment(ByteAlignment);
396 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
397 unsigned char Value) {
398 MCFragment *F = new MCOrgFragment(*Offset, Value, CurSectionData);
399 F->setAtom(CurrentAtomMap.lookup(CurSectionData));
402 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
404 for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
405 if (Inst.getOperand(i).isExpr())
406 AddValueSymbols(Inst.getOperand(i).getExpr());
408 CurSectionData->setHasInstructions(true);
410 // FIXME-PERF: Common case is that we don't need to relax, encode directly
411 // onto the data fragments buffers.
413 SmallVector<MCFixup, 4> Fixups;
414 SmallString<256> Code;
415 raw_svector_ostream VecOS(Code);
416 Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
419 // FIXME: Eliminate this copy.
420 SmallVector<MCAsmFixup, 4> AsmFixups;
421 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
422 MCFixup &F = Fixups[i];
423 AsmFixups.push_back(MCAsmFixup(F.getOffset(), *F.getValue(),
427 // See if we might need to relax this instruction, if so it needs its own
430 // FIXME-PERF: Support target hook to do a fast path that avoids the encoder,
431 // when we can immediately tell that we will get something which might need
432 // relaxation (and compute its size).
434 // FIXME-PERF: We should also be smart about immediately relaxing instructions
435 // which we can already show will never possibly fit (we can also do a very
436 // good job of this before we do the first relaxation pass, because we have
437 // total knowledge about undefined symbols at that point). Even now, though,
438 // we can do a decent job, especially on Darwin where scattering means that we
439 // are going to often know that we can never fully resolve a fixup.
440 if (Assembler.getBackend().MayNeedRelaxation(Inst, AsmFixups)) {
441 MCInstFragment *IF = new MCInstFragment(Inst, CurSectionData);
442 IF->setAtom(CurrentAtomMap.lookup(CurSectionData));
444 // Add the fixups and data.
446 // FIXME: Revisit this design decision when relaxation is done, we may be
447 // able to get away with not storing any extra data in the MCInst.
448 IF->getCode() = Code;
449 IF->getFixups() = AsmFixups;
454 // Add the fixups and data.
455 MCDataFragment *DF = getOrCreateDataFragment();
456 for (unsigned i = 0, e = AsmFixups.size(); i != e; ++i) {
457 AsmFixups[i].Offset += DF->getContents().size();
458 DF->addFixup(AsmFixups[i]);
460 DF->getContents().append(Code.begin(), Code.end());
463 void MCMachOStreamer::Finish() {
467 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
468 raw_ostream &OS, MCCodeEmitter *CE,
470 MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
472 S->getAssembler().setRelaxAll(true);