Split the object streamer callback in one per file format.
[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/ADT/STLExtras.h"
12 #include "llvm/MC/MCAsmBackend.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCAssembler.h"
15 #include "llvm/MC/MCCodeEmitter.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCDwarf.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCObjectWriter.h"
20 #include "llvm/MC/MCSection.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/TargetRegistry.h"
24 using namespace llvm;
25
26 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
27                                    raw_ostream &OS, MCCodeEmitter *Emitter_)
28     : MCStreamer(Context),
29       Assembler(new MCAssembler(Context, TAB, *Emitter_,
30                                 *TAB.createObjectWriter(OS), OS)),
31       CurSectionData(nullptr), EmitEHFrame(true), EmitDebugFrame(false) {}
32
33 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
34                                    raw_ostream &OS, MCCodeEmitter *Emitter_,
35                                    MCAssembler *Assembler)
36     : MCStreamer(Context), Assembler(Assembler), CurSectionData(nullptr),
37       EmitEHFrame(true), EmitDebugFrame(false) {}
38
39 MCObjectStreamer::~MCObjectStreamer() {
40   delete &Assembler->getBackend();
41   delete &Assembler->getEmitter();
42   delete &Assembler->getWriter();
43   delete Assembler;
44 }
45
46 void MCObjectStreamer::flushPendingLabels(MCFragment *F) {
47   if (PendingLabels.size()) {
48     if (!F) {
49       F = new MCDataFragment();
50       CurSectionData->getFragmentList().insert(CurInsertionPoint, F);
51       F->setParent(CurSectionData);
52     }
53     for (MCSymbolData *SD : PendingLabels) {
54       SD->setFragment(F);
55       SD->setOffset(0);
56     }
57     PendingLabels.clear();
58   }
59 }
60
61 void MCObjectStreamer::reset() {
62   if (Assembler)
63     Assembler->reset();
64   CurSectionData = nullptr;
65   CurInsertionPoint = MCSectionData::iterator();
66   EmitEHFrame = true;
67   EmitDebugFrame = false;
68   PendingLabels.clear();
69   MCStreamer::reset();
70 }
71
72 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
73   if (!getNumFrameInfos())
74     return;
75
76   if (EmitEHFrame)
77     MCDwarfFrameEmitter::Emit(*this, MAB, true);
78
79   if (EmitDebugFrame)
80     MCDwarfFrameEmitter::Emit(*this, MAB, false);
81 }
82
83 MCFragment *MCObjectStreamer::getCurrentFragment() const {
84   assert(getCurrentSectionData() && "No current section!");
85
86   if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
87     return std::prev(CurInsertionPoint);
88
89   return nullptr;
90 }
91
92 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
93   MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
94   // When bundling is enabled, we don't want to add data to a fragment that
95   // already has instructions (see MCELFStreamer::EmitInstToData for details)
96   if (!F || (Assembler->isBundlingEnabled() && F->hasInstructions())) {
97     F = new MCDataFragment();
98     insert(F);
99   }
100   return F;
101 }
102
103 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
104   Assembler->getOrCreateSymbolData(Sym);
105 }
106
107 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
108   MCStreamer::EmitCFISections(EH, Debug);
109   EmitEHFrame = EH;
110   EmitDebugFrame = Debug;
111 }
112
113 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
114                                      const SMLoc &Loc) {
115   MCStreamer::EmitValueImpl(Value, Size, Loc);
116   MCDataFragment *DF = getOrCreateDataFragment();
117
118   MCLineEntry::Make(this, getCurrentSection().first);
119
120   // Avoid fixups when possible.
121   int64_t AbsValue;
122   if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
123     EmitIntValue(AbsValue, Size);
124     return;
125   }
126   DF->getFixups().push_back(
127       MCFixup::Create(DF->getContents().size(), Value,
128                       MCFixup::getKindForSize(Size, false), Loc));
129   DF->getContents().resize(DF->getContents().size() + Size, 0);
130 }
131
132 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
133   // We need to create a local symbol to avoid relocations.
134   Frame.Begin = getContext().CreateTempSymbol();
135   EmitLabel(Frame.Begin);
136 }
137
138 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
139   Frame.End = getContext().CreateTempSymbol();
140   EmitLabel(Frame.End);
141 }
142
143 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
144   MCStreamer::EmitLabel(Symbol);
145
146   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
147   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
148
149   // If there is a current fragment, mark the symbol as pointing into it.
150   // Otherwise queue the label and set its fragment pointer when we emit the
151   // next fragment.
152   if (auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment())) {
153     SD.setFragment(F);
154     SD.setOffset(F->getContents().size());
155   } else {
156     PendingLabels.push_back(&SD);
157   }
158 }
159
160 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
161   int64_t IntValue;
162   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
163     EmitULEB128IntValue(IntValue);
164     return;
165   }
166   insert(new MCLEBFragment(*Value, false));
167 }
168
169 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
170   int64_t IntValue;
171   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
172     EmitSLEB128IntValue(IntValue);
173     return;
174   }
175   insert(new MCLEBFragment(*Value, true));
176 }
177
178 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
179                                          const MCSymbol *Symbol) {
180   report_fatal_error("This file format doesn't support weak aliases.");
181 }
182
183 void MCObjectStreamer::ChangeSection(const MCSection *Section,
184                                      const MCExpr *Subsection) {
185   assert(Section && "Cannot switch to a null section!");
186   flushPendingLabels(nullptr);
187
188   CurSectionData = &getAssembler().getOrCreateSectionData(*Section);
189
190   int64_t IntSubsection = 0;
191   if (Subsection &&
192       !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
193     report_fatal_error("Cannot evaluate subsection number");
194   if (IntSubsection < 0 || IntSubsection > 8192)
195     report_fatal_error("Subsection number out of range");
196   CurInsertionPoint =
197     CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
198 }
199
200 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
201   getAssembler().getOrCreateSymbolData(*Symbol);
202   MCStreamer::EmitAssignment(Symbol, Value);
203 }
204
205 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
206                                        const MCSubtargetInfo &STI) {
207   MCStreamer::EmitInstruction(Inst, STI);
208
209   MCSectionData *SD = getCurrentSectionData();
210   SD->setHasInstructions(true);
211
212   // Now that a machine instruction has been assembled into this section, make
213   // a line entry for any .loc directive that has been seen.
214   MCLineEntry::Make(this, getCurrentSection().first);
215
216   // If this instruction doesn't need relaxation, just emit it as data.
217   MCAssembler &Assembler = getAssembler();
218   if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
219     EmitInstToData(Inst, STI);
220     return;
221   }
222
223   // Otherwise, relax and emit it as data if either:
224   // - The RelaxAll flag was passed
225   // - Bundling is enabled and this instruction is inside a bundle-locked
226   //   group. We want to emit all such instructions into the same data
227   //   fragment.
228   if (Assembler.getRelaxAll() ||
229       (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
230     MCInst Relaxed;
231     getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
232     while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
233       getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
234     EmitInstToData(Relaxed, STI);
235     return;
236   }
237
238   // Otherwise emit to a separate fragment.
239   EmitInstToFragment(Inst, STI);
240 }
241
242 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
243                                           const MCSubtargetInfo &STI) {
244   // Always create a new, separate fragment here, because its size can change
245   // during relaxation.
246   MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
247   insert(IF);
248
249   SmallString<128> Code;
250   raw_svector_ostream VecOS(Code);
251   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups(),
252                                                 STI);
253   VecOS.flush();
254   IF->getContents().append(Code.begin(), Code.end());
255 }
256
257 #ifndef NDEBUG
258 static const char *const BundlingNotImplementedMsg =
259   "Aligned bundling is not implemented for this object format";
260 #endif
261
262 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
263   llvm_unreachable(BundlingNotImplementedMsg);
264 }
265
266 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
267   llvm_unreachable(BundlingNotImplementedMsg);
268 }
269
270 void MCObjectStreamer::EmitBundleUnlock() {
271   llvm_unreachable(BundlingNotImplementedMsg);
272 }
273
274 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
275                                              unsigned Column, unsigned Flags,
276                                              unsigned Isa,
277                                              unsigned Discriminator,
278                                              StringRef FileName) {
279   // In case we see two .loc directives in a row, make sure the
280   // first one gets a line entry.
281   MCLineEntry::Make(this, getCurrentSection().first);
282
283   this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
284                                           Isa, Discriminator, FileName);
285 }
286
287 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
288                                      const MCSymbol *B) {
289   MCContext &Context = OS.getContext();
290   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
291   const MCExpr *ARef = MCSymbolRefExpr::Create(A, Variant, Context);
292   const MCExpr *BRef = MCSymbolRefExpr::Create(B, Variant, Context);
293   const MCExpr *AddrDelta =
294       MCBinaryExpr::Create(MCBinaryExpr::Sub, ARef, BRef, Context);
295   return AddrDelta;
296 }
297
298 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
299                                  const MCSymbol *Label, int PointerSize) {
300   // emit the sequence to set the address
301   OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
302   OS.EmitULEB128IntValue(PointerSize + 1);
303   OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
304   OS.EmitSymbolValue(Label, PointerSize);
305
306   // emit the sequence for the LineDelta (from 1) and a zero address delta.
307   MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
308 }
309
310 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
311                                                 const MCSymbol *LastLabel,
312                                                 const MCSymbol *Label,
313                                                 unsigned PointerSize) {
314   if (!LastLabel) {
315     emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
316     return;
317   }
318   const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
319   int64_t Res;
320   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
321     MCDwarfLineAddr::Emit(this, LineDelta, Res);
322     return;
323   }
324   insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
325 }
326
327 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
328                                                  const MCSymbol *Label) {
329   const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
330   int64_t Res;
331   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
332     MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
333     return;
334   }
335   insert(new MCDwarfCallFrameFragment(*AddrDelta));
336 }
337
338 void MCObjectStreamer::EmitBytes(StringRef Data) {
339   MCLineEntry::Make(this, getCurrentSection().first);
340   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
341 }
342
343 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
344                                             int64_t Value,
345                                             unsigned ValueSize,
346                                             unsigned MaxBytesToEmit) {
347   if (MaxBytesToEmit == 0)
348     MaxBytesToEmit = ByteAlignment;
349   insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
350
351   // Update the maximum alignment on the current section if necessary.
352   if (ByteAlignment > getCurrentSectionData()->getAlignment())
353     getCurrentSectionData()->setAlignment(ByteAlignment);
354 }
355
356 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
357                                          unsigned MaxBytesToEmit) {
358   EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
359   cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
360 }
361
362 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
363                                          unsigned char Value) {
364   int64_t Res;
365   if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
366     insert(new MCOrgFragment(*Offset, Value));
367     return false;
368   }
369
370   MCSymbol *CurrentPos = getContext().CreateTempSymbol();
371   EmitLabel(CurrentPos);
372   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
373   const MCExpr *Ref =
374     MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
375   const MCExpr *Delta =
376     MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
377
378   if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
379     return true;
380   EmitFill(Res, Value);
381   return false;
382 }
383
384 // Associate GPRel32 fixup with data and resize data area
385 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
386   MCDataFragment *DF = getOrCreateDataFragment();
387
388   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(), 
389                                             Value, FK_GPRel_4));
390   DF->getContents().resize(DF->getContents().size() + 4, 0);
391 }
392
393 // Associate GPRel32 fixup with data and resize data area
394 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
395   MCDataFragment *DF = getOrCreateDataFragment();
396
397   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(), 
398                                             Value, FK_GPRel_4));
399   DF->getContents().resize(DF->getContents().size() + 8, 0);
400 }
401
402 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
403   // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
404   //        problems evaluating expressions across multiple fragments.
405   getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
406 }
407
408 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
409   const MCSection *Sec = getCurrentSection().first;
410   assert(Sec && "need a section");
411   unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
412   insert(new MCFillFragment(0, ItemSize, NumBytes));
413 }
414
415 void MCObjectStreamer::FinishImpl() {
416   // If we are generating dwarf for assembly source files dump out the sections.
417   if (getContext().getGenDwarfForAssembly())
418     MCGenDwarfInfo::Emit(this);
419
420   // Dump out the dwarf file & directory tables and line tables.
421   MCDwarfLineTable::Emit(this);
422
423   flushPendingLabels(nullptr);
424   getAssembler().Finish();
425 }