Simplify the visitation of target expressions. No functionality change.
[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::visitUsedExpr(const MCExpr &Expr) {
91   switch (Expr.getKind()) {
92   case MCExpr::Target:
93     cast<MCTargetExpr>(Expr).visitUsedExpr(*this);
94     break;
95
96   case MCExpr::Constant:
97     break;
98
99   case MCExpr::Binary: {
100     const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
101     visitUsedExpr(*BE.getLHS());
102     visitUsedExpr(*BE.getRHS());
103     break;
104   }
105
106   case MCExpr::SymbolRef:
107     visitUsedSymbol(cast<MCSymbolRefExpr>(Expr).getSymbol());
108     break;
109
110   case MCExpr::Unary:
111     visitUsedExpr(*cast<MCUnaryExpr>(Expr).getSubExpr());
112     break;
113   }
114 }
115
116 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
117   MCStreamer::EmitCFISections(EH, Debug);
118   EmitEHFrame = EH;
119   EmitDebugFrame = Debug;
120 }
121
122 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
123                                      const SMLoc &Loc) {
124   MCDataFragment *DF = getOrCreateDataFragment();
125
126   MCLineEntry::Make(this, getCurrentSection().first);
127
128   // Avoid fixups when possible.
129   int64_t AbsValue;
130   visitUsedExpr(*Value);
131   if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
132     EmitIntValue(AbsValue, Size);
133     return;
134   }
135   DF->getFixups().push_back(
136       MCFixup::Create(DF->getContents().size(), Value,
137                       MCFixup::getKindForSize(Size, false), Loc));
138   DF->getContents().resize(DF->getContents().size() + Size, 0);
139 }
140
141 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
142   // We need to create a local symbol to avoid relocations.
143   Frame.Begin = getContext().CreateTempSymbol();
144   EmitLabel(Frame.Begin);
145 }
146
147 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
148   Frame.End = getContext().CreateTempSymbol();
149   EmitLabel(Frame.End);
150 }
151
152 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
153   MCStreamer::EmitLabel(Symbol);
154
155   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
156
157   // FIXME: This is wasteful, we don't necessarily need to create a data
158   // fragment. Instead, we should mark the symbol as pointing into the data
159   // fragment if it exists, otherwise we should just queue the label and set its
160   // fragment pointer when we emit the next fragment.
161   MCDataFragment *F = getOrCreateDataFragment();
162   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
163   SD.setFragment(F);
164   SD.setOffset(F->getContents().size());
165 }
166
167 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
168   int64_t IntValue;
169   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
170     EmitULEB128IntValue(IntValue);
171     return;
172   }
173   Value = ForceExpAbs(Value);
174   insert(new MCLEBFragment(*Value, false));
175 }
176
177 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
178   int64_t IntValue;
179   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
180     EmitSLEB128IntValue(IntValue);
181     return;
182   }
183   Value = ForceExpAbs(Value);
184   insert(new MCLEBFragment(*Value, true));
185 }
186
187 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
188                                          const MCSymbol *Symbol) {
189   report_fatal_error("This file format doesn't support weak aliases.");
190 }
191
192 void MCObjectStreamer::ChangeSection(const MCSection *Section,
193                                      const MCExpr *Subsection) {
194   assert(Section && "Cannot switch to a null section!");
195
196   CurSectionData = &getAssembler().getOrCreateSectionData(*Section);
197
198   int64_t IntSubsection = 0;
199   if (Subsection &&
200       !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
201     report_fatal_error("Cannot evaluate subsection number");
202   if (IntSubsection < 0 || IntSubsection > 8192)
203     report_fatal_error("Subsection number out of range");
204   CurInsertionPoint =
205     CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
206 }
207
208 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
209   getAssembler().getOrCreateSymbolData(*Symbol);
210   visitUsedExpr(*Value);
211   MCStreamer::EmitAssignment(Symbol, Value);
212 }
213
214 void MCObjectStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
215   // Scan for values.
216   for (unsigned i = Inst.getNumOperands(); i--; )
217     if (Inst.getOperand(i).isExpr())
218       visitUsedExpr(*Inst.getOperand(i).getExpr());
219
220   MCSectionData *SD = getCurrentSectionData();
221   SD->setHasInstructions(true);
222
223   // Now that a machine instruction has been assembled into this section, make
224   // a line entry for any .loc directive that has been seen.
225   MCLineEntry::Make(this, getCurrentSection().first);
226
227   // If this instruction doesn't need relaxation, just emit it as data.
228   MCAssembler &Assembler = getAssembler();
229   if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
230     EmitInstToData(Inst, STI);
231     return;
232   }
233
234   // Otherwise, relax and emit it as data if either:
235   // - The RelaxAll flag was passed
236   // - Bundling is enabled and this instruction is inside a bundle-locked
237   //   group. We want to emit all such instructions into the same data
238   //   fragment.
239   if (Assembler.getRelaxAll() ||
240       (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
241     MCInst Relaxed;
242     getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
243     while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
244       getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
245     EmitInstToData(Relaxed, STI);
246     return;
247   }
248
249   // Otherwise emit to a separate fragment.
250   EmitInstToFragment(Inst, STI);
251 }
252
253 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
254                                           const MCSubtargetInfo &STI) {
255   // Always create a new, separate fragment here, because its size can change
256   // during relaxation.
257   MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
258   insert(IF);
259
260   SmallString<128> Code;
261   raw_svector_ostream VecOS(Code);
262   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups(),
263                                                 STI);
264   VecOS.flush();
265   IF->getContents().append(Code.begin(), Code.end());
266 }
267
268 #ifndef NDEBUG
269 static const char *const BundlingNotImplementedMsg =
270   "Aligned bundling is not implemented for this object format";
271 #endif
272
273 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
274   llvm_unreachable(BundlingNotImplementedMsg);
275 }
276
277 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
278   llvm_unreachable(BundlingNotImplementedMsg);
279 }
280
281 void MCObjectStreamer::EmitBundleUnlock() {
282   llvm_unreachable(BundlingNotImplementedMsg);
283 }
284
285 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
286                                              unsigned Column, unsigned Flags,
287                                              unsigned Isa,
288                                              unsigned Discriminator,
289                                              StringRef FileName) {
290   // In case we see two .loc directives in a row, make sure the
291   // first one gets a line entry.
292   MCLineEntry::Make(this, getCurrentSection().first);
293
294   this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
295                                           Isa, Discriminator, FileName);
296 }
297
298 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
299                                                 const MCSymbol *LastLabel,
300                                                 const MCSymbol *Label,
301                                                 unsigned PointerSize) {
302   if (!LastLabel) {
303     EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
304     return;
305   }
306   const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
307   int64_t Res;
308   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
309     MCDwarfLineAddr::Emit(this, LineDelta, Res);
310     return;
311   }
312   AddrDelta = ForceExpAbs(AddrDelta);
313   insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
314 }
315
316 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
317                                                  const MCSymbol *Label) {
318   const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
319   int64_t Res;
320   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
321     MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
322     return;
323   }
324   AddrDelta = ForceExpAbs(AddrDelta);
325   insert(new MCDwarfCallFrameFragment(*AddrDelta));
326 }
327
328 void MCObjectStreamer::EmitBytes(StringRef Data) {
329   MCLineEntry::Make(this, getCurrentSection().first);
330   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
331 }
332
333 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
334                                             int64_t Value,
335                                             unsigned ValueSize,
336                                             unsigned MaxBytesToEmit) {
337   if (MaxBytesToEmit == 0)
338     MaxBytesToEmit = ByteAlignment;
339   insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
340
341   // Update the maximum alignment on the current section if necessary.
342   if (ByteAlignment > getCurrentSectionData()->getAlignment())
343     getCurrentSectionData()->setAlignment(ByteAlignment);
344 }
345
346 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
347                                          unsigned MaxBytesToEmit) {
348   EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
349   cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
350 }
351
352 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
353                                          unsigned char Value) {
354   int64_t Res;
355   if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
356     insert(new MCOrgFragment(*Offset, Value));
357     return false;
358   }
359
360   MCSymbol *CurrentPos = getContext().CreateTempSymbol();
361   EmitLabel(CurrentPos);
362   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
363   const MCExpr *Ref =
364     MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
365   const MCExpr *Delta =
366     MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
367
368   if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
369     return true;
370   EmitFill(Res, Value);
371   return false;
372 }
373
374 // Associate GPRel32 fixup with data and resize data area
375 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
376   MCDataFragment *DF = getOrCreateDataFragment();
377
378   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(), 
379                                             Value, FK_GPRel_4));
380   DF->getContents().resize(DF->getContents().size() + 4, 0);
381 }
382
383 // Associate GPRel32 fixup with data and resize data area
384 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
385   MCDataFragment *DF = getOrCreateDataFragment();
386
387   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(), 
388                                             Value, FK_GPRel_4));
389   DF->getContents().resize(DF->getContents().size() + 8, 0);
390 }
391
392 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
393   // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
394   //        problems evaluating expressions across multiple fragments.
395   getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
396 }
397
398 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
399   unsigned ItemSize = getCurrentSection().first->isVirtualSection() ? 0 : 1;
400   insert(new MCFillFragment(0, ItemSize, NumBytes));
401 }
402
403 void MCObjectStreamer::FinishImpl() {
404   // If we are generating dwarf for assembly source files dump out the sections.
405   if (getContext().getGenDwarfForAssembly())
406     MCGenDwarfInfo::Emit(this);
407
408   // Dump out the dwarf file & directory tables and line tables.
409   MCDwarfLineTable::Emit(this);
410
411   getAssembler().Finish();
412 }