blob: a5f9c2dee508eab48a9288ff9ff03cfe26b725fa [file] [log] [blame]
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001//===- lib/MC/MCMachOStreamer.cpp - Mach-O Object Output ------------===//
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
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000012#include "llvm/MC/MCAssembler.h"
13#include "llvm/MC/MCContext.h"
Daniel Dunbar4fac7492009-08-27 08:17:51 +000014#include "llvm/MC/MCCodeEmitter.h"
Daniel Dunbar8c2eebe2009-08-31 08:08:38 +000015#include "llvm/MC/MCExpr.h"
Daniel Dunbar4fac7492009-08-27 08:17:51 +000016#include "llvm/MC/MCInst.h"
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +000017#include "llvm/MC/MCObjectStreamer.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000018#include "llvm/MC/MCSection.h"
19#include "llvm/MC/MCSymbol.h"
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +000020#include "llvm/MC/MCMachOSymbolFlags.h"
Kevin Enderbyb07ce602010-08-09 22:52:14 +000021#include "llvm/MC/MCSectionMachO.h"
22#include "llvm/MC/MCDwarf.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000023#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar4fac7492009-08-27 08:17:51 +000024#include "llvm/Support/raw_ostream.h"
Daniel Dunbard8036fb2010-03-23 05:09:03 +000025#include "llvm/Target/TargetAsmBackend.h"
26
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000027using namespace llvm;
28
29namespace {
30
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +000031class MCMachOStreamer : public MCObjectStreamer {
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +000032private:
Daniel Dunbar2ac0c452010-05-26 20:37:00 +000033 void EmitInstToFragment(const MCInst &Inst);
34 void EmitInstToData(const MCInst &Inst);
Kevin Enderbyb07ce602010-08-09 22:52:14 +000035 // FIXME: These will likely moved to a better place.
Kevin Enderby232ab942010-08-31 22:55:11 +000036 void MakeLineEntryForSection(const MCSection *Section);
Kevin Enderbyb07ce602010-08-09 22:52:14 +000037 const MCExpr * MakeStartMinusEndExpr(MCSymbol *Start, MCSymbol *End,
38 int IntVal);
39 void EmitDwarfFileTable(void);
Daniel Dunbar2ac0c452010-05-26 20:37:00 +000040
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000041public:
Daniel Dunbar1f3e4452010-03-11 01:34:27 +000042 MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +000043 raw_ostream &OS, MCCodeEmitter *Emitter)
Rafael Espindola59ff3c92010-09-22 22:27:05 +000044 : MCObjectStreamer(Context, TAB, OS, Emitter, true) {}
Daniel Dunbarac2884a2010-03-25 22:49:09 +000045
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000046 /// @name MCStreamer Interface
47 /// @{
48
Rafael Espindolad80781b2010-09-15 21:48:40 +000049 virtual void InitSections();
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000050 virtual void EmitLabel(MCSymbol *Symbol);
Chris Lattnera5ad93a2010-01-23 06:39:22 +000051 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
Daniel Dunbar821e3332009-08-31 08:09:28 +000052 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
Chris Lattnera5ad93a2010-01-23 06:39:22 +000053 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000054 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
Chris Lattner9eb158d2010-01-23 07:47:02 +000055 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
Daniel Dunbar7092c7e2009-08-30 06:17:16 +000056 unsigned ByteAlignment);
Chris Lattnerb54b9dd2010-05-08 19:54:22 +000057 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
58 assert(0 && "macho doesn't support this directive");
59 }
60 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
61 assert(0 && "macho doesn't support this directive");
62 }
63 virtual void EmitCOFFSymbolType(int Type) {
64 assert(0 && "macho doesn't support this directive");
65 }
66 virtual void EndCOFFSymbolDef() {
67 assert(0 && "macho doesn't support this directive");
68 }
Chris Lattner99328ad2010-01-25 07:52:13 +000069 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
70 assert(0 && "macho doesn't support this directive");
71 }
Chris Lattner9eb158d2010-01-23 07:47:02 +000072 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
73 assert(0 && "macho doesn't support this directive");
74 }
Daniel Dunbar8751b942009-08-28 05:48:22 +000075 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
Daniel Dunbar7092c7e2009-08-30 06:17:16 +000076 unsigned Size = 0, unsigned ByteAlignment = 0);
Eric Christopher011c3f12010-05-18 21:26:41 +000077 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
78 uint64_t Size, unsigned ByteAlignment = 0);
Chris Lattneraaec2052010-01-19 19:46:13 +000079 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
Chris Lattneraaec2052010-01-19 19:46:13 +000080 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
Chris Lattner718fb592010-01-25 21:28:50 +000081 virtual void EmitGPRel32Value(const MCExpr *Value) {
82 assert(0 && "macho doesn't support this directive");
83 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000084 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
85 unsigned ValueSize = 1,
86 unsigned MaxBytesToEmit = 0);
Kevin Enderby6e720482010-02-23 18:26:34 +000087 virtual void EmitCodeAlignment(unsigned ByteAlignment,
88 unsigned MaxBytesToEmit = 0);
Daniel Dunbar821e3332009-08-31 08:09:28 +000089 virtual void EmitValueToOffset(const MCExpr *Offset,
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000090 unsigned char Value = 0);
Daniel Dunbar2ac0c452010-05-26 20:37:00 +000091
Chris Lattnera6594fc2010-01-25 18:58:59 +000092 virtual void EmitFileDirective(StringRef Filename) {
Daniel Dunbar96749672010-07-19 20:44:20 +000093 // FIXME: Just ignore the .file; it isn't important enough to fail the
94 // entire assembly.
95
96 //report_fatal_error("unsupported directive: '.file'");
Chris Lattnera6594fc2010-01-25 18:58:59 +000097 }
98 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
Daniel Dunbar96749672010-07-19 20:44:20 +000099 // FIXME: Just ignore the .file; it isn't important enough to fail the
100 // entire assembly.
101
102 //report_fatal_error("unsupported directive: '.file'");
Chris Lattnera6594fc2010-01-25 18:58:59 +0000103 }
Daniel Dunbar2ac0c452010-05-26 20:37:00 +0000104
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000105 virtual void EmitInstruction(const MCInst &Inst);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000106
Daniel Dunbara86de102010-06-16 20:04:32 +0000107 virtual void Finish();
108
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000109 /// @}
110};
111
112} // end anonymous namespace.
113
Rafael Espindolad80781b2010-09-15 21:48:40 +0000114void MCMachOStreamer::InitSections() {
115 SwitchSection(getContext().getMachOSection("__TEXT", "__text",
116 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
117 0, SectionKind::getText()));
118
119}
120
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000121void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
Michael J. Spencer8067adc2010-07-19 06:13:10 +0000122 // TODO: This is almost exactly the same as WinCOFFStreamer. Consider merging
123 // into MCObjectStreamer.
Daniel Dunbar8906ff12009-08-22 07:22:36 +0000124 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
Daniel Dunbarc3047182010-05-05 19:01:00 +0000125 assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
126 assert(CurSection && "Cannot emit before setting section!");
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000127
Daniel Dunbara86de102010-06-16 20:04:32 +0000128 Symbol->setSection(*CurSection);
129
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000130 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
Daniel Dunbar071f73d2010-05-10 22:45:09 +0000131
Daniel Dunbara86de102010-06-16 20:04:32 +0000132 // We have to create a new fragment if this is an atom defining symbol,
133 // fragments cannot span atoms.
134 if (getAssembler().isSymbolLinkerVisible(SD.getSymbol()))
135 new MCDataFragment(getCurrentSectionData());
Daniel Dunbar071f73d2010-05-10 22:45:09 +0000136
Daniel Dunbarf70f4772010-03-22 20:35:46 +0000137 // FIXME: This is wasteful, we don't necessarily need to create a data
138 // fragment. Instead, we should mark the symbol as pointing into the data
139 // fragment if it exists, otherwise we should just queue the label and set its
140 // fragment pointer when we emit the next fragment.
Daniel Dunbara86de102010-06-16 20:04:32 +0000141 MCDataFragment *F = getOrCreateDataFragment();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000142 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
143 SD.setFragment(F);
144 SD.setOffset(F->getContents().size());
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000145
Daniel Dunbarb18d2dd2010-05-17 20:12:31 +0000146 // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
147 // to clear the weak reference and weak definition bits too, but the
148 // implementation was buggy. For now we just try to match 'as', for
149 // diffability.
150 //
151 // FIXME: Cleanup this code, these bits should be emitted based on semantic
152 // properties, not on the order of definition, etc.
153 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000154}
155
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000156void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
Daniel Dunbar6009db42009-08-26 21:22:22 +0000157 switch (Flag) {
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000158 case MCAF_SubsectionsViaSymbols:
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000159 getAssembler().setSubsectionsViaSymbols(true);
Daniel Dunbar8c3eaf42009-08-28 07:08:47 +0000160 return;
Daniel Dunbar6009db42009-08-26 21:22:22 +0000161 }
Daniel Dunbar8c3eaf42009-08-28 07:08:47 +0000162
163 assert(0 && "invalid assembler flag!");
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000164}
165
Daniel Dunbar821e3332009-08-31 08:09:28 +0000166void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
Michael J. Spencer8067adc2010-07-19 06:13:10 +0000167 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
168 // MCObjectStreamer.
Daniel Dunbara4d86672009-10-16 01:58:23 +0000169 // FIXME: Lift context changes into super class.
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000170 getAssembler().getOrCreateSymbolData(*Symbol);
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000171 Symbol->setVariableValue(AddValueSymbols(Value));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000172}
173
174void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000175 MCSymbolAttr Attribute) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000176 // Indirect symbols are handled differently, to match how 'as' handles
177 // them. This makes writing matching .o files easier.
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000178 if (Attribute == MCSA_IndirectSymbol) {
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000179 // Note that we intentionally cannot use the symbol data here; this is
180 // important for matching the string table that 'as' generates.
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000181 IndirectSymbolData ISD;
182 ISD.Symbol = Symbol;
Daniel Dunbar83b46712010-06-16 20:04:25 +0000183 ISD.SectionData = getCurrentSectionData();
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000184 getAssembler().getIndirectSymbols().push_back(ISD);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000185 return;
186 }
187
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000188 // Adding a symbol attribute always introduces the symbol, note that an
Daniel Dunbar46836a72010-03-10 20:58:29 +0000189 // important side effect of calling getOrCreateSymbolData here is to register
190 // the symbol with the assembler.
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000191 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000192
193 // The implementation of symbol attributes is designed to match 'as', but it
194 // leaves much to desired. It doesn't really make sense to arbitrarily add and
195 // remove flags, but 'as' allows this (in particular, see .desc).
196 //
197 // In the future it might be worth trying to make these operations more well
198 // defined.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000199 switch (Attribute) {
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000200 case MCSA_Invalid:
Chris Lattnered0ab152010-01-25 18:30:45 +0000201 case MCSA_ELF_TypeFunction:
202 case MCSA_ELF_TypeIndFunction:
203 case MCSA_ELF_TypeObject:
204 case MCSA_ELF_TypeTLS:
205 case MCSA_ELF_TypeCommon:
206 case MCSA_ELF_TypeNoType:
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000207 case MCSA_IndirectSymbol:
208 case MCSA_Hidden:
209 case MCSA_Internal:
210 case MCSA_Protected:
211 case MCSA_Weak:
212 case MCSA_Local:
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000213 assert(0 && "Invalid symbol attribute for Mach-O!");
214 break;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000215
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000216 case MCSA_Global:
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000217 SD.setExternal(true);
Daniel Dunbarb18d2dd2010-05-17 20:12:31 +0000218 // This effectively clears the undefined lazy bit, in Darwin 'as', although
219 // it isn't very consistent because it implements this as part of symbol
220 // lookup.
221 //
222 // FIXME: Cleanup this code, these bits should be emitted based on semantic
223 // properties, not on the order of definition, etc.
224 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000225 break;
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000226
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000227 case MCSA_LazyReference:
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000228 // FIXME: This requires -dynamic.
229 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
230 if (Symbol->isUndefined())
231 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
232 break;
233
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000234 // Since .reference sets the no dead strip bit, it is equivalent to
235 // .no_dead_strip in practice.
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000236 case MCSA_Reference:
237 case MCSA_NoDeadStrip:
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000238 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
239 break;
240
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000241 case MCSA_PrivateExtern:
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000242 SD.setExternal(true);
243 SD.setPrivateExtern(true);
244 break;
245
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000246 case MCSA_WeakReference:
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000247 // FIXME: This requires -dynamic.
248 if (Symbol->isUndefined())
249 SD.setFlags(SD.getFlags() | SF_WeakReference);
250 break;
251
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000252 case MCSA_WeakDefinition:
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000253 // FIXME: 'as' enforces that this is defined and global. The manual claims
254 // it has to be in a coalesced section, but this isn't enforced.
255 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
256 break;
Kevin Enderbyf59cac52010-07-08 17:22:42 +0000257
258 case MCSA_WeakDefAutoPrivate:
259 SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
260 break;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000261 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000262}
263
264void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000265 // Encode the 'desc' value into the lowest implementation defined bits.
Daniel Dunbar2ac0c452010-05-26 20:37:00 +0000266 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000267 "Invalid .desc value!");
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000268 getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
269 DescValue & SF_DescFlagsMask);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000270}
271
Chris Lattner9eb158d2010-01-23 07:47:02 +0000272void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
Daniel Dunbar7092c7e2009-08-30 06:17:16 +0000273 unsigned ByteAlignment) {
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000274 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
275 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
276
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000277 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000278 SD.setExternal(true);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +0000279 SD.setCommon(Size, ByteAlignment);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000280}
281
Daniel Dunbar8751b942009-08-28 05:48:22 +0000282void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
Daniel Dunbar7092c7e2009-08-30 06:17:16 +0000283 unsigned Size, unsigned ByteAlignment) {
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000284 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000285
286 // The symbol may not be present, which only creates the section.
287 if (!Symbol)
288 return;
289
290 // FIXME: Assert that this section has the zerofill type.
291
292 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
293
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000294 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000295
Daniel Dunbare73d49e2010-05-12 22:51:27 +0000296 // Emit an align fragment if necessary.
297 if (ByteAlignment != 1)
Daniel Dunbar1c154132010-05-12 22:56:23 +0000298 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
Daniel Dunbare73d49e2010-05-12 22:51:27 +0000299
Daniel Dunbar4e544872010-05-12 22:51:38 +0000300 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000301 SD.setFragment(F);
302
303 Symbol->setSection(*Section);
304
305 // Update the maximum alignment on the zero fill section if necessary.
306 if (ByteAlignment > SectData.getAlignment())
307 SectData.setAlignment(ByteAlignment);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000308}
309
Eric Christopher070c1ab2010-05-21 23:03:53 +0000310// This should always be called with the thread local bss section. Like the
311// .zerofill directive this doesn't actually switch sections on us.
Eric Christopher011c3f12010-05-18 21:26:41 +0000312void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
313 uint64_t Size, unsigned ByteAlignment) {
314 EmitZerofill(Section, Symbol, Size, ByteAlignment);
315 return;
Eric Christopher482eba02010-05-14 01:50:28 +0000316}
317
Chris Lattneraaec2052010-01-19 19:46:13 +0000318void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
Michael J. Spencer8067adc2010-07-19 06:13:10 +0000319 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
320 // MCObjectStreamer.
Daniel Dunbarf70f4772010-03-22 20:35:46 +0000321 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000322}
323
Chris Lattneraaec2052010-01-19 19:46:13 +0000324void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
325 unsigned AddrSpace) {
Michael J. Spencer8067adc2010-07-19 06:13:10 +0000326 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
327 // MCObjectStreamer.
Daniel Dunbarf70f4772010-03-22 20:35:46 +0000328 MCDataFragment *DF = getOrCreateDataFragment();
Daniel Dunbar45f48742010-02-13 09:28:22 +0000329
330 // Avoid fixups when possible.
331 int64_t AbsValue;
Daniel Dunbar40ebe2472010-02-22 22:08:57 +0000332 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
Daniel Dunbar45f48742010-02-13 09:28:22 +0000333 // FIXME: Endianness assumption.
334 for (unsigned i = 0; i != Size; ++i)
335 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
336 } else {
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000337 DF->addFixup(MCFixup::Create(DF->getContents().size(),
338 AddValueSymbols(Value),
339 MCFixup::getKindForSize(Size)));
Daniel Dunbar45f48742010-02-13 09:28:22 +0000340 DF->getContents().resize(DF->getContents().size() + Size, 0);
341 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000342}
343
344void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
345 int64_t Value, unsigned ValueSize,
346 unsigned MaxBytesToEmit) {
Michael J. Spencer8067adc2010-07-19 06:13:10 +0000347 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
348 // MCObjectStreamer.
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000349 if (MaxBytesToEmit == 0)
350 MaxBytesToEmit = ByteAlignment;
Daniel Dunbara86de102010-06-16 20:04:32 +0000351 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
352 getCurrentSectionData());
Kevin Enderby6e720482010-02-23 18:26:34 +0000353
354 // Update the maximum alignment on the current section if necessary.
Daniel Dunbar83b46712010-06-16 20:04:25 +0000355 if (ByteAlignment > getCurrentSectionData()->getAlignment())
356 getCurrentSectionData()->setAlignment(ByteAlignment);
Kevin Enderby6e720482010-02-23 18:26:34 +0000357}
358
359void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
360 unsigned MaxBytesToEmit) {
Michael J. Spencer8067adc2010-07-19 06:13:10 +0000361 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
362 // MCObjectStreamer.
Kevin Enderby6e720482010-02-23 18:26:34 +0000363 if (MaxBytesToEmit == 0)
364 MaxBytesToEmit = ByteAlignment;
Daniel Dunbar1c154132010-05-12 22:56:23 +0000365 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
Daniel Dunbar83b46712010-06-16 20:04:25 +0000366 getCurrentSectionData());
Daniel Dunbar1c154132010-05-12 22:56:23 +0000367 F->setEmitNops(true);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000368
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000369 // Update the maximum alignment on the current section if necessary.
Daniel Dunbar83b46712010-06-16 20:04:25 +0000370 if (ByteAlignment > getCurrentSectionData()->getAlignment())
371 getCurrentSectionData()->setAlignment(ByteAlignment);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000372}
373
Daniel Dunbar821e3332009-08-31 08:09:28 +0000374void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000375 unsigned char Value) {
Daniel Dunbara86de102010-06-16 20:04:32 +0000376 new MCOrgFragment(*Offset, Value, getCurrentSectionData());
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000377}
378
Daniel Dunbar2ac0c452010-05-26 20:37:00 +0000379void MCMachOStreamer::EmitInstToFragment(const MCInst &Inst) {
Daniel Dunbar83b46712010-06-16 20:04:25 +0000380 MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
Daniel Dunbar2ac0c452010-05-26 20:37:00 +0000381
382 // Add the fixups and data.
383 //
384 // FIXME: Revisit this design decision when relaxation is done, we may be
385 // able to get away with not storing any extra data in the MCInst.
386 SmallVector<MCFixup, 4> Fixups;
387 SmallString<256> Code;
388 raw_svector_ostream VecOS(Code);
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000389 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
Daniel Dunbar2ac0c452010-05-26 20:37:00 +0000390 VecOS.flush();
391
392 IF->getCode() = Code;
393 IF->getFixups() = Fixups;
394}
395
396void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
397 MCDataFragment *DF = getOrCreateDataFragment();
398
399 SmallVector<MCFixup, 4> Fixups;
400 SmallString<256> Code;
401 raw_svector_ostream VecOS(Code);
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000402 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
Daniel Dunbar2ac0c452010-05-26 20:37:00 +0000403 VecOS.flush();
404
405 // Add the fixups and data.
406 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
407 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
408 DF->addFixup(Fixups[i]);
409 }
410 DF->getContents().append(Code.begin(), Code.end());
411}
412
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000413void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
Daniel Dunbar4fac7492009-08-27 08:17:51 +0000414 // Scan for values.
Daniel Dunbardb9014d2010-05-17 21:19:59 +0000415 for (unsigned i = Inst.getNumOperands(); i--; )
Daniel Dunbar8c2eebe2009-08-31 08:08:38 +0000416 if (Inst.getOperand(i).isExpr())
417 AddValueSymbols(Inst.getOperand(i).getExpr());
Daniel Dunbar4fac7492009-08-27 08:17:51 +0000418
Daniel Dunbar83b46712010-06-16 20:04:25 +0000419 getCurrentSectionData()->setHasInstructions(true);
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000420
Kevin Enderby232ab942010-08-31 22:55:11 +0000421 // Now that a machine instruction has been assembled into this section, make
422 // a line entry for any .loc directive that has been seen.
423 MakeLineEntryForSection(getCurrentSection());
424
Daniel Dunbar83194de2010-05-26 20:37:03 +0000425 // If this instruction doesn't need relaxation, just emit it as data.
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000426 if (!getAssembler().getBackend().MayNeedRelaxation(Inst)) {
Daniel Dunbar2ac0c452010-05-26 20:37:00 +0000427 EmitInstToData(Inst);
Daniel Dunbar83194de2010-05-26 20:37:03 +0000428 return;
429 }
430
431 // Otherwise, if we are relaxing everything, relax the instruction as much as
432 // possible and emit it as data.
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000433 if (getAssembler().getRelaxAll()) {
Daniel Dunbar83194de2010-05-26 20:37:03 +0000434 MCInst Relaxed;
Daniel Dunbar8dc68ab2010-06-16 20:04:22 +0000435 getAssembler().getBackend().RelaxInstruction(Inst, Relaxed);
436 while (getAssembler().getBackend().MayNeedRelaxation(Relaxed))
437 getAssembler().getBackend().RelaxInstruction(Relaxed, Relaxed);
Daniel Dunbar83194de2010-05-26 20:37:03 +0000438 EmitInstToData(Relaxed);
439 return;
440 }
441
442 // Otherwise emit to a separate fragment.
443 EmitInstToFragment(Inst);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000444}
445
Kevin Enderbyb07ce602010-08-09 22:52:14 +0000446//
Kevin Enderby232ab942010-08-31 22:55:11 +0000447// This is called when an instruction is assembled into the specified section
448// and if there is information from the last .loc directive that has yet to have
449// a line entry made for it is made.
450//
451void MCMachOStreamer::MakeLineEntryForSection(const MCSection *Section) {
452 if (!getContext().getDwarfLocSeen())
453 return;
454
455 // Create a symbol at in the current section for use in the line entry.
456 MCSymbol *LineSym = getContext().CreateTempSymbol();
457 // Set the value of the symbol to use for the MCLineEntry.
458 EmitLabel(LineSym);
459
460 // Get the current .loc info saved in the context.
461 const MCDwarfLoc &DwarfLoc = getContext().getCurrentDwarfLoc();
462
463 // Create a (local) line entry with the symbol and the current .loc info.
464 MCLineEntry LineEntry(LineSym, DwarfLoc);
465
466 // clear DwarfLocSeen saying the current .loc info is now used.
467 getContext().clearDwarfLocSeen();
468
469 // Get the MCLineSection for this section, if one does not exist for this
470 // section create it.
471 DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
472 getContext().getMCLineSections();
473 MCLineSection *LineSection = MCLineSections[Section];
474 if (!LineSection) {
475 // Create a new MCLineSection. This will be deleted after the dwarf line
476 // table is created using it by iterating through the MCLineSections
477 // DenseMap.
478 LineSection = new MCLineSection;
479 // Save a pointer to the new LineSection into the MCLineSections DenseMap.
480 MCLineSections[Section] = LineSection;
481 }
482
483 // Add the line entry to this section's entries.
484 LineSection->addLineEntry(LineEntry);
485}
486
487//
Kevin Enderbyb07ce602010-08-09 22:52:14 +0000488// This helper routine returns an expression of End - Start + IntVal for use
489// by EmitDwarfFileTable() below.
490//
491const MCExpr * MCMachOStreamer::MakeStartMinusEndExpr(MCSymbol *Start,
492 MCSymbol *End,
493 int IntVal) {
494 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
495 const MCExpr *Res =
496 MCSymbolRefExpr::Create(End, Variant, getContext());
497 const MCExpr *RHS =
498 MCSymbolRefExpr::Create(Start, Variant, getContext());
499 const MCExpr *Res1 =
500 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS,getContext());
501 const MCExpr *Res2 =
502 MCConstantExpr::Create(IntVal, getContext());
503 const MCExpr *Res3 =
504 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, getContext());
505 return Res3;
506}
507
508//
509// This emits the Dwarf file (and eventually the line) table.
510//
511void MCMachOStreamer::EmitDwarfFileTable(void) {
512 // For now make sure we don't put out the Dwarf file table if no .file
513 // directives were seen.
514 const std::vector<MCDwarfFile *> &MCDwarfFiles =
515 getContext().getMCDwarfFiles();
516 if (MCDwarfFiles.size() == 0)
517 return;
518
519 // This is the Mach-O section, for ELF it is the .debug_line section.
520 SwitchSection(getContext().getMachOSection("__DWARF", "__debug_line",
521 MCSectionMachO::S_ATTR_DEBUG,
522 0, SectionKind::getDataRelLocal()));
523
524 // Create a symbol at the beginning of this section.
525 MCSymbol *LineStartSym = getContext().CreateTempSymbol();
526 // Set the value of the symbol, as we are at the start of the section.
527 EmitLabel(LineStartSym);
528
529 // Create a symbol for the end of the section (to be set when we get there).
530 MCSymbol *LineEndSym = getContext().CreateTempSymbol();
531
532 // The first 4 bytes is the total length of the information for this
533 // compilation unit (not including these 4 bytes for the length).
534 EmitValue(MakeStartMinusEndExpr(LineStartSym, LineEndSym, 4), 4, 0);
535
536 // Next 2 bytes is the Version, which is Dwarf 2.
537 EmitIntValue(2, 2);
538
539 // Create a symbol for the end of the prologue (to be set when we get there).
540 MCSymbol *ProEndSym = getContext().CreateTempSymbol(); // Lprologue_end
541
542 // Length of the prologue, is the next 4 bytes. Which is the start of the
543 // section to the end of the prologue. Not including the 4 bytes for the
544 // total length, the 2 bytes for the version, and these 4 bytes for the
545 // length of the prologue.
546 EmitValue(MakeStartMinusEndExpr(LineStartSym, ProEndSym, (4 + 2 + 4)), 4, 0);
547
548 // Parameters of the state machine, are next.
549 // Define the architecture-dependent minimum instruction length (in
550 // bytes). This value should be rather too small than too big. */
551 // DWARF2_LINE_MIN_INSN_LENGTH
552 EmitIntValue(1, 1);
553 // Flag that indicates the initial value of the is_stmt_start flag.
554 // DWARF2_LINE_DEFAULT_IS_STMT
555 EmitIntValue(1, 1);
556 // Minimum line offset in a special line info. opcode. This value
557 // was chosen to give a reasonable range of values. */
558 // DWARF2_LINE_BASE
Bill Wendling7d49f2b2010-09-03 19:09:46 +0000559 EmitIntValue(uint64_t(-5), 1);
Kevin Enderbyb07ce602010-08-09 22:52:14 +0000560 // Range of line offsets in a special line info. opcode.
561 // DWARF2_LINE_RANGE
562 EmitIntValue(14, 1);
563 // First special line opcode - leave room for the standard opcodes.
564 // DWARF2_LINE_OPCODE_BASE
565 EmitIntValue(13, 1);
566
567 // Standard opcode lengths
568 EmitIntValue(0, 1); // length of DW_LNS_copy
569 EmitIntValue(1, 1); // length of DW_LNS_advance_pc
570 EmitIntValue(1, 1); // length of DW_LNS_advance_line
571 EmitIntValue(1, 1); // length of DW_LNS_set_file
572 EmitIntValue(1, 1); // length of DW_LNS_set_column
573 EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
574 EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
575 EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
576 EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
577 EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
578 EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
579 EmitIntValue(1, 1); // DW_LNS_set_isa
580
581 // Put out the directory and file tables.
582
583 // First the directory table.
584 const std::vector<StringRef> &MCDwarfDirs =
585 getContext().getMCDwarfDirs();
586 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
587 EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
588 EmitBytes(StringRef("\0", 1), 0); // the null termination of the string
589 }
590 EmitIntValue(0, 1); // Terminate the directory list
591
592 // Second the file table.
593 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
594 EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
595 EmitBytes(StringRef("\0", 1), 0); // the null termination of the string
596 // FIXME the Directory number should be a .uleb128 not a .byte
597 EmitIntValue(MCDwarfFiles[i]->getDirIndex(), 1);
598 EmitIntValue(0, 1); // last modification timestamp (always 0)
599 EmitIntValue(0, 1); // filesize (always 0)
600 }
601 EmitIntValue(0, 1); // Terminate the file list
602
603 // This is the end of the prologue, so set the value of the symbol at the
604 // end of the prologue (that was used in a previous expression).
605 EmitLabel(ProEndSym);
606
607 // TODO: This is the point where the line tables would be emitted.
608
Kevin Enderby232ab942010-08-31 22:55:11 +0000609 // Delete the MCLineSections that were created in
610 // MCMachOStreamer::MakeLineEntryForSection() and used to emit the line
611 // tables.
612 DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
613 getContext().getMCLineSections();
614 for (DenseMap<const MCSection *, MCLineSection *>::iterator it =
615 MCLineSections.begin(), ie = MCLineSections.end(); it != ie; ++it) {
616 delete it->second;
617 }
618
Kevin Enderbyb07ce602010-08-09 22:52:14 +0000619 // If there are no line tables emited then we emit:
620 // The following DW_LNE_set_address sequence to set the address to zero
621 // TODO test for 32-bit or 64-bit output
622 // This is the sequence for 32-bit code
623 EmitIntValue(0, 1);
624 EmitIntValue(5, 1);
625 EmitIntValue(2, 1);
626 EmitIntValue(0, 1);
627 EmitIntValue(0, 1);
628 EmitIntValue(0, 1);
629 EmitIntValue(0, 1);
630
631 // Lastly emit the DW_LNE_end_sequence which consists of 3 bytes '00 01 01'
632 // (00 is the code for extended opcodes, followed by a ULEB128 length of the
633 // extended opcode (01), and the DW_LNE_end_sequence (01).
634 EmitIntValue(0, 1); // DW_LNS_extended_op
635 EmitIntValue(1, 1); // ULEB128 length of the extended opcode
636 EmitIntValue(1, 1); // DW_LNE_end_sequence
637
638 // This is the end of the section, so set the value of the symbol at the end
639 // of this section (that was used in a previous expression).
640 EmitLabel(LineEndSym);
641}
642
Daniel Dunbara86de102010-06-16 20:04:32 +0000643void MCMachOStreamer::Finish() {
Kevin Enderbyb07ce602010-08-09 22:52:14 +0000644 // Dump out the dwarf file and directory tables (soon to include line table)
645 EmitDwarfFileTable();
646
Daniel Dunbara86de102010-06-16 20:04:32 +0000647 // We have to set the fragment atom associations so we can relax properly for
648 // Mach-O.
649
650 // First, scan the symbol table to build a lookup table from fragments to
651 // defining symbols.
652 DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
653 for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
654 ie = getAssembler().symbol_end(); it != ie; ++it) {
655 if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
656 it->getFragment()) {
657 // An atom defining symbol should never be internal to a fragment.
658 assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
659 DefiningSymbolMap[it->getFragment()] = it;
660 }
661 }
662
663 // Set the fragment atom associations by tracking the last seen atom defining
664 // symbol.
665 for (MCAssembler::iterator it = getAssembler().begin(),
666 ie = getAssembler().end(); it != ie; ++it) {
667 MCSymbolData *CurrentAtom = 0;
668 for (MCSectionData::iterator it2 = it->begin(),
669 ie2 = it->end(); it2 != ie2; ++it2) {
670 if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
671 CurrentAtom = SD;
672 it2->setAtom(CurrentAtom);
673 }
674 }
675
676 this->MCObjectStreamer::Finish();
677}
678
Daniel Dunbar1f3e4452010-03-11 01:34:27 +0000679MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
Daniel Dunbarac2884a2010-03-25 22:49:09 +0000680 raw_ostream &OS, MCCodeEmitter *CE,
681 bool RelaxAll) {
682 MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
683 if (RelaxAll)
684 S->getAssembler().setRelaxAll(true);
685 return S;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000686}