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"
23 #include "llvm/Support/TargetRegistry.h"
26 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
27 raw_pwrite_stream &OS,
28 MCCodeEmitter *Emitter_)
29 : MCStreamer(Context),
30 Assembler(new MCAssembler(Context, TAB, *Emitter_,
31 *TAB.createObjectWriter(OS))),
32 EmitEHFrame(true), EmitDebugFrame(false) {}
34 MCObjectStreamer::~MCObjectStreamer() {
35 delete &Assembler->getBackend();
36 delete &Assembler->getEmitter();
37 delete &Assembler->getWriter();
41 void MCObjectStreamer::flushPendingLabels(MCFragment *F, uint64_t FOffset) {
42 if (PendingLabels.empty())
45 F = new MCDataFragment();
46 MCSection *CurSection = getCurrentSectionOnly();
47 CurSection->getFragmentList().insert(CurInsertionPoint, F);
48 F->setParent(CurSection);
50 for (MCSymbol *Sym : PendingLabels) {
52 Sym->setOffset(FOffset);
54 PendingLabels.clear();
57 void MCObjectStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi,
60 // If not assigned to the same (valid) fragment, fallback.
61 if (!Hi->getFragment() || Hi->getFragment() != Lo->getFragment() ||
62 Hi->isVariable() || Lo->isVariable()) {
63 MCStreamer::emitAbsoluteSymbolDiff(Hi, Lo, Size);
67 EmitIntValue(Hi->getOffset() - Lo->getOffset(), Size);
70 void MCObjectStreamer::reset() {
73 CurInsertionPoint = MCSection::iterator();
75 EmitDebugFrame = false;
76 PendingLabels.clear();
80 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
81 if (!getNumFrameInfos())
85 MCDwarfFrameEmitter::Emit(*this, MAB, true);
88 MCDwarfFrameEmitter::Emit(*this, MAB, false);
91 MCFragment *MCObjectStreamer::getCurrentFragment() const {
92 assert(getCurrentSectionOnly() && "No current section!");
94 if (CurInsertionPoint != getCurrentSectionOnly()->getFragmentList().begin())
95 return &*std::prev(CurInsertionPoint);
100 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
101 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
102 // When bundling is enabled, we don't want to add data to a fragment that
103 // already has instructions (see MCELFStreamer::EmitInstToData for details)
104 if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() &&
105 F->hasInstructions())) {
106 F = new MCDataFragment();
112 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
113 Assembler->registerSymbol(Sym);
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 MCStreamer::EmitValueImpl(Value, Size, Loc);
125 MCDataFragment *DF = getOrCreateDataFragment();
126 flushPendingLabels(DF, DF->getContents().size());
128 MCLineEntry::Make(this, getCurrentSection().first);
130 // Avoid fixups when possible.
132 if (Value->evaluateAsAbsolute(AbsValue, getAssembler())) {
133 EmitIntValue(AbsValue, Size);
136 DF->getFixups().push_back(
137 MCFixup::create(DF->getContents().size(), Value,
138 MCFixup::getKindForSize(Size, false), Loc));
139 DF->getContents().resize(DF->getContents().size() + Size, 0);
142 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
143 // We need to create a local symbol to avoid relocations.
144 Frame.Begin = getContext().createTempSymbol();
145 EmitLabel(Frame.Begin);
148 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
149 Frame.End = getContext().createTempSymbol();
150 EmitLabel(Frame.End);
153 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
154 MCStreamer::EmitLabel(Symbol);
156 getAssembler().registerSymbol(*Symbol);
158 // If there is a current fragment, mark the symbol as pointing into it.
159 // Otherwise queue the label and set its fragment pointer when we emit the
161 auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
162 if (F && !(getAssembler().isBundlingEnabled() &&
163 getAssembler().getRelaxAll())) {
164 Symbol->setFragment(F);
165 Symbol->setOffset(F->getContents().size());
167 PendingLabels.push_back(Symbol);
171 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
173 if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
174 EmitULEB128IntValue(IntValue);
177 insert(new MCLEBFragment(*Value, false));
180 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
182 if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
183 EmitSLEB128IntValue(IntValue);
186 insert(new MCLEBFragment(*Value, true));
189 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
190 const MCSymbol *Symbol) {
191 report_fatal_error("This file format doesn't support weak aliases.");
194 void MCObjectStreamer::ChangeSection(MCSection *Section,
195 const MCExpr *Subsection) {
196 changeSectionImpl(Section, Subsection);
199 bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
200 const MCExpr *Subsection) {
201 assert(Section && "Cannot switch to a null section!");
202 flushPendingLabels(nullptr);
204 bool Created = getAssembler().registerSection(*Section);
206 int64_t IntSubsection = 0;
208 !Subsection->evaluateAsAbsolute(IntSubsection, getAssembler()))
209 report_fatal_error("Cannot evaluate subsection number");
210 if (IntSubsection < 0 || IntSubsection > 8192)
211 report_fatal_error("Subsection number out of range");
213 Section->getSubsectionInsertionPoint(unsigned(IntSubsection));
217 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
218 getAssembler().registerSymbol(*Symbol);
219 MCStreamer::EmitAssignment(Symbol, Value);
222 bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
223 return Sec.hasInstructions();
226 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
227 const MCSubtargetInfo &STI) {
228 MCStreamer::EmitInstruction(Inst, STI);
230 MCSection *Sec = getCurrentSectionOnly();
231 Sec->setHasInstructions(true);
233 // Now that a machine instruction has been assembled into this section, make
234 // a line entry for any .loc directive that has been seen.
235 MCLineEntry::Make(this, getCurrentSection().first);
237 // If this instruction doesn't need relaxation, just emit it as data.
238 MCAssembler &Assembler = getAssembler();
239 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
240 EmitInstToData(Inst, STI);
244 // Otherwise, relax and emit it as data if either:
245 // - The RelaxAll flag was passed
246 // - Bundling is enabled and this instruction is inside a bundle-locked
247 // group. We want to emit all such instructions into the same data
249 if (Assembler.getRelaxAll() ||
250 (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) {
252 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
253 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
254 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
255 EmitInstToData(Relaxed, STI);
259 // Otherwise emit to a separate fragment.
260 EmitInstToFragment(Inst, STI);
263 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
264 const MCSubtargetInfo &STI) {
265 if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled())
266 llvm_unreachable("All instructions should have already been relaxed");
268 // Always create a new, separate fragment here, because its size can change
269 // during relaxation.
270 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
273 SmallString<128> Code;
274 raw_svector_ostream VecOS(Code);
275 getAssembler().getEmitter().encodeInstruction(Inst, VecOS, IF->getFixups(),
277 IF->getContents().append(Code.begin(), Code.end());
281 static const char *const BundlingNotImplementedMsg =
282 "Aligned bundling is not implemented for this object format";
285 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
286 llvm_unreachable(BundlingNotImplementedMsg);
289 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
290 llvm_unreachable(BundlingNotImplementedMsg);
293 void MCObjectStreamer::EmitBundleUnlock() {
294 llvm_unreachable(BundlingNotImplementedMsg);
297 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
298 unsigned Column, unsigned Flags,
300 unsigned Discriminator,
301 StringRef FileName) {
302 // In case we see two .loc directives in a row, make sure the
303 // first one gets a line entry.
304 MCLineEntry::Make(this, getCurrentSection().first);
306 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
307 Isa, Discriminator, FileName);
310 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
312 MCContext &Context = OS.getContext();
313 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
314 const MCExpr *ARef = MCSymbolRefExpr::create(A, Variant, Context);
315 const MCExpr *BRef = MCSymbolRefExpr::create(B, Variant, Context);
316 const MCExpr *AddrDelta =
317 MCBinaryExpr::create(MCBinaryExpr::Sub, ARef, BRef, Context);
321 static void emitDwarfSetLineAddr(MCObjectStreamer &OS,
322 MCDwarfLineTableParams Params,
323 int64_t LineDelta, const MCSymbol *Label,
325 // emit the sequence to set the address
326 OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
327 OS.EmitULEB128IntValue(PointerSize + 1);
328 OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
329 OS.EmitSymbolValue(Label, PointerSize);
331 // emit the sequence for the LineDelta (from 1) and a zero address delta.
332 MCDwarfLineAddr::Emit(&OS, Params, LineDelta, 0);
335 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
336 const MCSymbol *LastLabel,
337 const MCSymbol *Label,
338 unsigned PointerSize) {
340 emitDwarfSetLineAddr(*this, Assembler->getDWARFLinetableParams(), LineDelta,
344 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
346 if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
347 MCDwarfLineAddr::Emit(this, Assembler->getDWARFLinetableParams(), LineDelta,
351 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
354 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
355 const MCSymbol *Label) {
356 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
358 if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
359 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
362 insert(new MCDwarfCallFrameFragment(*AddrDelta));
365 void MCObjectStreamer::EmitBytes(StringRef Data) {
366 MCLineEntry::Make(this, getCurrentSection().first);
367 MCDataFragment *DF = getOrCreateDataFragment();
368 flushPendingLabels(DF, DF->getContents().size());
369 DF->getContents().append(Data.begin(), Data.end());
372 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
375 unsigned MaxBytesToEmit) {
376 if (MaxBytesToEmit == 0)
377 MaxBytesToEmit = ByteAlignment;
378 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
380 // Update the maximum alignment on the current section if necessary.
381 MCSection *CurSec = getCurrentSection().first;
382 if (ByteAlignment > CurSec->getAlignment())
383 CurSec->setAlignment(ByteAlignment);
386 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
387 unsigned MaxBytesToEmit) {
388 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
389 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
392 void MCObjectStreamer::emitValueToOffset(const MCExpr *Offset,
393 unsigned char Value) {
394 insert(new MCOrgFragment(*Offset, Value));
397 // Associate GPRel32 fixup with data and resize data area
398 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
399 MCDataFragment *DF = getOrCreateDataFragment();
400 flushPendingLabels(DF, DF->getContents().size());
402 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
404 DF->getContents().resize(DF->getContents().size() + 4, 0);
407 // Associate GPRel32 fixup with data and resize data area
408 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
409 MCDataFragment *DF = getOrCreateDataFragment();
410 flushPendingLabels(DF, DF->getContents().size());
412 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
414 DF->getContents().resize(DF->getContents().size() + 8, 0);
417 bool MCObjectStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name,
418 const MCExpr *Expr, SMLoc Loc) {
420 if (!Offset.evaluateAsAbsolute(OffsetValue))
421 llvm_unreachable("Offset is not absolute");
423 MCDataFragment *DF = getOrCreateDataFragment();
424 flushPendingLabels(DF, DF->getContents().size());
427 if (!Assembler->getBackend().getFixupKind(Name, Kind))
432 MCSymbolRefExpr::create(getContext().createTempSymbol(), getContext());
433 DF->getFixups().push_back(MCFixup::create(OffsetValue, Expr, Kind, Loc));
437 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
438 const MCSection *Sec = getCurrentSection().first;
439 assert(Sec && "need a section");
440 unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
441 insert(new MCFillFragment(FillValue, ItemSize, NumBytes));
444 void MCObjectStreamer::FinishImpl() {
445 // If we are generating dwarf for assembly source files dump out the sections.
446 if (getContext().getGenDwarfForAssembly())
447 MCGenDwarfInfo::Emit(this);
449 // Dump out the dwarf file & directory tables and line tables.
450 MCDwarfLineTable::Emit(this, getAssembler().getDWARFLinetableParams());
452 flushPendingLabels(nullptr);
453 getAssembler().Finish();