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