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