Refactor MCInstFragment and MCDataFragment to adhere to a common interface,
[oota-llvm.git] / lib / MC / MCObjectStreamer.cpp
1 //===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===//
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/MCObjectStreamer.h"
11 #include "llvm/MC/MCAsmBackend.h"
12 #include "llvm/MC/MCAsmInfo.h"
13 #include "llvm/MC/MCAssembler.h"
14 #include "llvm/MC/MCCodeEmitter.h"
15 #include "llvm/MC/MCContext.h"
16 #include "llvm/MC/MCDwarf.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCObjectWriter.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/Support/ErrorHandling.h"
21 using namespace llvm;
22
23 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
24                                    raw_ostream &OS, MCCodeEmitter *Emitter_)
25   : MCStreamer(Context),
26     Assembler(new MCAssembler(Context, TAB,
27                               *Emitter_, *TAB.createObjectWriter(OS),
28                               OS)),
29     CurSectionData(0)
30 {
31 }
32
33 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
34                                    raw_ostream &OS, MCCodeEmitter *Emitter_,
35                                    MCAssembler *_Assembler)
36   : MCStreamer(Context), Assembler(_Assembler), CurSectionData(0)
37 {
38 }
39
40 MCObjectStreamer::~MCObjectStreamer() {
41   delete &Assembler->getBackend();
42   delete &Assembler->getEmitter();
43   delete &Assembler->getWriter();
44   delete Assembler;
45 }
46
47 MCFragment *MCObjectStreamer::getCurrentFragment() const {
48   assert(getCurrentSectionData() && "No current section!");
49
50   if (!getCurrentSectionData()->empty())
51     return &getCurrentSectionData()->getFragmentList().back();
52
53   return 0;
54 }
55
56 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() const {
57   MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
58   if (!F)
59     F = new MCDataFragment(getCurrentSectionData());
60   return F;
61 }
62
63 const MCExpr *MCObjectStreamer::AddValueSymbols(const MCExpr *Value) {
64   switch (Value->getKind()) {
65   case MCExpr::Target:
66     cast<MCTargetExpr>(Value)->AddValueSymbols(Assembler);
67     break;
68
69   case MCExpr::Constant:
70     break;
71
72   case MCExpr::Binary: {
73     const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
74     AddValueSymbols(BE->getLHS());
75     AddValueSymbols(BE->getRHS());
76     break;
77   }
78
79   case MCExpr::SymbolRef:
80     Assembler->getOrCreateSymbolData(cast<MCSymbolRefExpr>(Value)->getSymbol());
81     break;
82
83   case MCExpr::Unary:
84     AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
85     break;
86   }
87
88   return Value;
89 }
90
91 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
92                                      unsigned AddrSpace) {
93   assert(AddrSpace == 0 && "Address space must be 0!");
94   MCDataFragment *DF = getOrCreateDataFragment();
95
96   // Avoid fixups when possible.
97   int64_t AbsValue;
98   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue, getAssembler())) {
99     EmitIntValue(AbsValue, Size, AddrSpace);
100     return;
101   }
102   DF->getFixups().push_back(
103       MCFixup::Create(DF->getContents().size(), Value,
104                       MCFixup::getKindForSize(Size, false)));
105   DF->getContents().resize(DF->getContents().size() + Size, 0);
106 }
107
108 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
109   RecordProcStart(Frame);
110 }
111
112 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
113   RecordProcEnd(Frame);
114 }
115
116 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
117   MCStreamer::EmitLabel(Symbol);
118
119   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
120
121   // FIXME: This is wasteful, we don't necessarily need to create a data
122   // fragment. Instead, we should mark the symbol as pointing into the data
123   // fragment if it exists, otherwise we should just queue the label and set its
124   // fragment pointer when we emit the next fragment.
125   MCDataFragment *F = getOrCreateDataFragment();
126   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
127   SD.setFragment(F);
128   SD.setOffset(F->getContents().size());
129 }
130
131 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
132   int64_t IntValue;
133   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
134     EmitULEB128IntValue(IntValue);
135     return;
136   }
137   Value = ForceExpAbs(Value);
138   new MCLEBFragment(*Value, false, getCurrentSectionData());
139 }
140
141 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
142   int64_t IntValue;
143   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
144     EmitSLEB128IntValue(IntValue);
145     return;
146   }
147   Value = ForceExpAbs(Value);
148   new MCLEBFragment(*Value, true, getCurrentSectionData());
149 }
150
151 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
152                                          const MCSymbol *Symbol) {
153   report_fatal_error("This file format doesn't support weak aliases.");
154 }
155
156 void MCObjectStreamer::ChangeSection(const MCSection *Section) {
157   assert(Section && "Cannot switch to a null section!");
158
159   CurSectionData = &getAssembler().getOrCreateSectionData(*Section);
160 }
161
162 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
163   getAssembler().getOrCreateSymbolData(*Symbol);
164   Symbol->setVariableValue(AddValueSymbols(Value));
165 }
166
167 void MCObjectStreamer::EmitInstruction(const MCInst &Inst) {
168   // Scan for values.
169   for (unsigned i = Inst.getNumOperands(); i--; )
170     if (Inst.getOperand(i).isExpr())
171       AddValueSymbols(Inst.getOperand(i).getExpr());
172
173   getCurrentSectionData()->setHasInstructions(true);
174
175   // Now that a machine instruction has been assembled into this section, make
176   // a line entry for any .loc directive that has been seen.
177   MCLineEntry::Make(this, getCurrentSection());
178
179   // If this instruction doesn't need relaxation, just emit it as data.
180   if (!getAssembler().getBackend().mayNeedRelaxation(Inst)) {
181     EmitInstToData(Inst);
182     return;
183   }
184
185   // Otherwise, if we are relaxing everything, relax the instruction as much as
186   // possible and emit it as data.
187   if (getAssembler().getRelaxAll()) {
188     MCInst Relaxed;
189     getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
190     while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
191       getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
192     EmitInstToData(Relaxed);
193     return;
194   }
195
196   // Otherwise emit to a separate fragment.
197   EmitInstToFragment(Inst);
198 }
199
200 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst) {
201   MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
202
203   SmallString<128> Code;
204   raw_svector_ostream VecOS(Code);
205   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups());
206   VecOS.flush();
207   IF->getContents().append(Code.begin(), Code.end());
208 }
209
210 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
211                                                 const MCSymbol *LastLabel,
212                                                 const MCSymbol *Label,
213                                                 unsigned PointerSize) {
214   if (!LastLabel) {
215     EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
216     return;
217   }
218   const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
219   int64_t Res;
220   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
221     MCDwarfLineAddr::Emit(this, LineDelta, Res);
222     return;
223   }
224   AddrDelta = ForceExpAbs(AddrDelta);
225   new MCDwarfLineAddrFragment(LineDelta, *AddrDelta, getCurrentSectionData());
226 }
227
228 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
229                                                  const MCSymbol *Label) {
230   const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
231   int64_t Res;
232   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
233     MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
234     return;
235   }
236   AddrDelta = ForceExpAbs(AddrDelta);
237   new MCDwarfCallFrameFragment(*AddrDelta, getCurrentSectionData());
238 }
239
240 void MCObjectStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
241   assert(AddrSpace == 0 && "Address space must be 0!");
242   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
243 }
244
245 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
246                                             int64_t Value,
247                                             unsigned ValueSize,
248                                             unsigned MaxBytesToEmit) {
249   if (MaxBytesToEmit == 0)
250     MaxBytesToEmit = ByteAlignment;
251   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
252                       getCurrentSectionData());
253
254   // Update the maximum alignment on the current section if necessary.
255   if (ByteAlignment > getCurrentSectionData()->getAlignment())
256     getCurrentSectionData()->setAlignment(ByteAlignment);
257 }
258
259 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
260                                          unsigned MaxBytesToEmit) {
261   EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
262   cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
263 }
264
265 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
266                                          unsigned char Value) {
267   int64_t Res;
268   if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
269     new MCOrgFragment(*Offset, Value, getCurrentSectionData());
270     return false;
271   }
272
273   MCSymbol *CurrentPos = getContext().CreateTempSymbol();
274   EmitLabel(CurrentPos);
275   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
276   const MCExpr *Ref =
277     MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
278   const MCExpr *Delta =
279     MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
280
281   if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
282     return true;
283   EmitFill(Res, Value, 0);
284   return false;
285 }
286
287 // Associate GPRel32 fixup with data and resize data area
288 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
289   MCDataFragment *DF = getOrCreateDataFragment();
290
291   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(), 
292                                             Value, FK_GPRel_4));
293   DF->getContents().resize(DF->getContents().size() + 4, 0);
294 }
295
296 // Associate GPRel32 fixup with data and resize data area
297 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
298   MCDataFragment *DF = getOrCreateDataFragment();
299
300   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(), 
301                                             Value, FK_GPRel_4));
302   DF->getContents().resize(DF->getContents().size() + 8, 0);
303 }
304
305 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
306                                 unsigned AddrSpace) {
307   assert(AddrSpace == 0 && "Address space must be 0!");
308   // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
309   //        problems evaluating expressions across multiple fragments.
310   getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
311 }
312
313 void MCObjectStreamer::FinishImpl() {
314   // Dump out the dwarf file & directory tables and line tables.
315   const MCSymbol *LineSectionSymbol = NULL;
316   if (getContext().hasDwarfFiles())
317     LineSectionSymbol = MCDwarfFileTable::Emit(this);
318
319   // If we are generating dwarf for assembly source files dump out the sections.
320   if (getContext().getGenDwarfForAssembly())
321     MCGenDwarfInfo::Emit(this, LineSectionSymbol);
322
323   getAssembler().Finish();
324 }