1 //===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
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) {}
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) {}
38 MCObjectStreamer::~MCObjectStreamer() {
39 delete &Assembler->getBackend();
40 delete &Assembler->getEmitter();
41 delete &Assembler->getWriter();
45 void MCObjectStreamer::reset() {
48 CurSectionData = nullptr;
49 CurInsertionPoint = MCSectionData::iterator();
51 EmitDebugFrame = false;
55 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
56 if (!getNumFrameInfos())
60 MCDwarfFrameEmitter::Emit(*this, MAB, true);
63 MCDwarfFrameEmitter::Emit(*this, MAB, false);
66 MCFragment *MCObjectStreamer::getCurrentFragment() const {
67 assert(getCurrentSectionData() && "No current section!");
69 if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
70 return std::prev(CurInsertionPoint);
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();
86 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
87 Assembler->getOrCreateSymbolData(Sym);
90 void MCObjectStreamer::visitUsedExpr(const MCExpr &Expr) {
91 switch (Expr.getKind()) {
93 cast<MCTargetExpr>(Expr).visitUsedExpr(*this);
96 case MCExpr::Constant:
99 case MCExpr::Binary: {
100 const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
101 visitUsedExpr(*BE.getLHS());
102 visitUsedExpr(*BE.getRHS());
106 case MCExpr::SymbolRef:
107 visitUsedSymbol(cast<MCSymbolRefExpr>(Expr).getSymbol());
111 visitUsedExpr(*cast<MCUnaryExpr>(Expr).getSubExpr());
116 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
117 MCStreamer::EmitCFISections(EH, Debug);
119 EmitDebugFrame = Debug;
122 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
124 MCDataFragment *DF = getOrCreateDataFragment();
126 MCLineEntry::Make(this, getCurrentSection().first);
128 // Avoid fixups when possible.
130 visitUsedExpr(*Value);
131 if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
132 EmitIntValue(AbsValue, Size);
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);
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);
147 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
148 Frame.End = getContext().CreateTempSymbol();
149 EmitLabel(Frame.End);
152 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
153 MCStreamer::EmitLabel(Symbol);
155 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
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!");
164 SD.setOffset(F->getContents().size());
167 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
169 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
170 EmitULEB128IntValue(IntValue);
173 Value = ForceExpAbs(Value);
174 insert(new MCLEBFragment(*Value, false));
177 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
179 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
180 EmitSLEB128IntValue(IntValue);
183 Value = ForceExpAbs(Value);
184 insert(new MCLEBFragment(*Value, true));
187 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
188 const MCSymbol *Symbol) {
189 report_fatal_error("This file format doesn't support weak aliases.");
192 void MCObjectStreamer::ChangeSection(const MCSection *Section,
193 const MCExpr *Subsection) {
194 assert(Section && "Cannot switch to a null section!");
196 CurSectionData = &getAssembler().getOrCreateSectionData(*Section);
198 int64_t IntSubsection = 0;
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");
205 CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
208 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
209 getAssembler().getOrCreateSymbolData(*Symbol);
210 visitUsedExpr(*Value);
211 MCStreamer::EmitAssignment(Symbol, Value);
214 void MCObjectStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
216 for (unsigned i = Inst.getNumOperands(); i--; )
217 if (Inst.getOperand(i).isExpr())
218 visitUsedExpr(*Inst.getOperand(i).getExpr());
220 MCSectionData *SD = getCurrentSectionData();
221 SD->setHasInstructions(true);
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);
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);
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
239 if (Assembler.getRelaxAll() ||
240 (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
242 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
243 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
244 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
245 EmitInstToData(Relaxed, STI);
249 // Otherwise emit to a separate fragment.
250 EmitInstToFragment(Inst, STI);
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);
260 SmallString<128> Code;
261 raw_svector_ostream VecOS(Code);
262 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups(),
265 IF->getContents().append(Code.begin(), Code.end());
269 static const char *const BundlingNotImplementedMsg =
270 "Aligned bundling is not implemented for this object format";
273 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
274 llvm_unreachable(BundlingNotImplementedMsg);
277 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
278 llvm_unreachable(BundlingNotImplementedMsg);
281 void MCObjectStreamer::EmitBundleUnlock() {
282 llvm_unreachable(BundlingNotImplementedMsg);
285 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
286 unsigned Column, unsigned Flags,
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);
294 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
295 Isa, Discriminator, FileName);
298 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
299 const MCSymbol *LastLabel,
300 const MCSymbol *Label,
301 unsigned PointerSize) {
303 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
306 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
308 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
309 MCDwarfLineAddr::Emit(this, LineDelta, Res);
312 AddrDelta = ForceExpAbs(AddrDelta);
313 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
316 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
317 const MCSymbol *Label) {
318 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
320 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
321 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
324 AddrDelta = ForceExpAbs(AddrDelta);
325 insert(new MCDwarfCallFrameFragment(*AddrDelta));
328 void MCObjectStreamer::EmitBytes(StringRef Data) {
329 MCLineEntry::Make(this, getCurrentSection().first);
330 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
333 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
336 unsigned MaxBytesToEmit) {
337 if (MaxBytesToEmit == 0)
338 MaxBytesToEmit = ByteAlignment;
339 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
341 // Update the maximum alignment on the current section if necessary.
342 if (ByteAlignment > getCurrentSectionData()->getAlignment())
343 getCurrentSectionData()->setAlignment(ByteAlignment);
346 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
347 unsigned MaxBytesToEmit) {
348 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
349 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
352 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
353 unsigned char Value) {
355 if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
356 insert(new MCOrgFragment(*Offset, Value));
360 MCSymbol *CurrentPos = getContext().CreateTempSymbol();
361 EmitLabel(CurrentPos);
362 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
364 MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
365 const MCExpr *Delta =
366 MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
368 if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
370 EmitFill(Res, Value);
374 // Associate GPRel32 fixup with data and resize data area
375 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
376 MCDataFragment *DF = getOrCreateDataFragment();
378 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
380 DF->getContents().resize(DF->getContents().size() + 4, 0);
383 // Associate GPRel32 fixup with data and resize data area
384 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
385 MCDataFragment *DF = getOrCreateDataFragment();
387 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
389 DF->getContents().resize(DF->getContents().size() + 8, 0);
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);
398 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
399 unsigned ItemSize = getCurrentSection().first->isVirtualSection() ? 0 : 1;
400 insert(new MCFillFragment(0, ItemSize, NumBytes));
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);
408 // Dump out the dwarf file & directory tables and line tables.
409 MCDwarfLineTable::Emit(this);
411 getAssembler().Finish();