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