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), 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.size()) {
44 F = new MCDataFragment();
45 MCSection *CurSection = getCurrentSectionOnly();
46 CurSection->getFragmentList().insert(CurInsertionPoint, F);
47 F->setParent(CurSection);
49 for (MCSymbol *Sym : PendingLabels) {
51 Sym->setOffset(FOffset);
53 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 MCStreamer::emitAbsoluteSymbolDiff(Hi, Lo, Size);
66 assert(Hi->getOffset() >= Lo->getOffset() &&
67 "Expected Hi to be greater than Lo");
68 EmitIntValue(Hi->getOffset() - Lo->getOffset(), Size);
71 void MCObjectStreamer::reset() {
74 CurInsertionPoint = MCSection::iterator();
76 EmitDebugFrame = false;
77 PendingLabels.clear();
81 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
82 if (!getNumFrameInfos())
86 MCDwarfFrameEmitter::Emit(*this, MAB, true);
89 MCDwarfFrameEmitter::Emit(*this, MAB, false);
92 MCFragment *MCObjectStreamer::getCurrentFragment() const {
93 assert(getCurrentSectionOnly() && "No current section!");
95 if (CurInsertionPoint != getCurrentSectionOnly()->getFragmentList().begin())
96 return std::prev(CurInsertionPoint);
101 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
102 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
103 // When bundling is enabled, we don't want to add data to a fragment that
104 // already has instructions (see MCELFStreamer::EmitInstToData for details)
105 if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() &&
106 F->hasInstructions())) {
107 F = new MCDataFragment();
113 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
114 Assembler->registerSymbol(Sym);
117 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
118 MCStreamer::EmitCFISections(EH, Debug);
120 EmitDebugFrame = Debug;
123 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
125 MCStreamer::EmitValueImpl(Value, Size, Loc);
126 MCDataFragment *DF = getOrCreateDataFragment();
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);
157 assert(!Symbol->getFragment() && "Unexpected fragment on symbol data!");
159 // If there is a current fragment, mark the symbol as pointing into it.
160 // Otherwise queue the label and set its fragment pointer when we emit the
162 auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
163 if (F && !(getAssembler().isBundlingEnabled() &&
164 getAssembler().getRelaxAll())) {
165 Symbol->setFragment(F);
166 Symbol->setOffset(F->getContents().size());
168 PendingLabels.push_back(Symbol);
172 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
174 if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
175 EmitULEB128IntValue(IntValue);
178 insert(new MCLEBFragment(*Value, false));
181 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
183 if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
184 EmitSLEB128IntValue(IntValue);
187 insert(new MCLEBFragment(*Value, true));
190 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
191 const MCSymbol *Symbol) {
192 report_fatal_error("This file format doesn't support weak aliases.");
195 void MCObjectStreamer::ChangeSection(MCSection *Section,
196 const MCExpr *Subsection) {
197 changeSectionImpl(Section, Subsection);
200 bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
201 const MCExpr *Subsection) {
202 assert(Section && "Cannot switch to a null section!");
203 flushPendingLabels(nullptr);
205 bool Created = getAssembler().registerSection(*Section);
207 int64_t IntSubsection = 0;
209 !Subsection->evaluateAsAbsolute(IntSubsection, getAssembler()))
210 report_fatal_error("Cannot evaluate subsection number");
211 if (IntSubsection < 0 || IntSubsection > 8192)
212 report_fatal_error("Subsection number out of range");
214 Section->getSubsectionInsertionPoint(unsigned(IntSubsection));
218 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
219 getAssembler().registerSymbol(*Symbol);
220 MCStreamer::EmitAssignment(Symbol, Value);
223 bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
224 return Sec.hasInstructions();
227 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
228 const MCSubtargetInfo &STI) {
229 MCStreamer::EmitInstruction(Inst, STI);
231 MCSection *Sec = getCurrentSectionOnly();
232 Sec->setHasInstructions(true);
234 // Now that a machine instruction has been assembled into this section, make
235 // a line entry for any .loc directive that has been seen.
236 MCLineEntry::Make(this, getCurrentSection().first);
238 // If this instruction doesn't need relaxation, just emit it as data.
239 MCAssembler &Assembler = getAssembler();
240 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
241 EmitInstToData(Inst, STI);
245 // Otherwise, relax and emit it as data if either:
246 // - The RelaxAll flag was passed
247 // - Bundling is enabled and this instruction is inside a bundle-locked
248 // group. We want to emit all such instructions into the same data
250 if (Assembler.getRelaxAll() ||
251 (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) {
253 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
254 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
255 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
256 EmitInstToData(Relaxed, STI);
260 // Otherwise emit to a separate fragment.
261 EmitInstToFragment(Inst, STI);
264 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
265 const MCSubtargetInfo &STI) {
266 if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled())
267 llvm_unreachable("All instructions should have already been relaxed");
269 // Always create a new, separate fragment here, because its size can change
270 // during relaxation.
271 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
274 SmallString<128> Code;
275 raw_svector_ostream VecOS(Code);
276 getAssembler().getEmitter().encodeInstruction(Inst, VecOS, IF->getFixups(),
279 IF->getContents().append(Code.begin(), Code.end());
283 static const char *const BundlingNotImplementedMsg =
284 "Aligned bundling is not implemented for this object format";
287 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
288 llvm_unreachable(BundlingNotImplementedMsg);
291 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
292 llvm_unreachable(BundlingNotImplementedMsg);
295 void MCObjectStreamer::EmitBundleUnlock() {
296 llvm_unreachable(BundlingNotImplementedMsg);
299 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
300 unsigned Column, unsigned Flags,
302 unsigned Discriminator,
303 StringRef FileName) {
304 // In case we see two .loc directives in a row, make sure the
305 // first one gets a line entry.
306 MCLineEntry::Make(this, getCurrentSection().first);
308 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
309 Isa, Discriminator, FileName);
312 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
314 MCContext &Context = OS.getContext();
315 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
316 const MCExpr *ARef = MCSymbolRefExpr::create(A, Variant, Context);
317 const MCExpr *BRef = MCSymbolRefExpr::create(B, Variant, Context);
318 const MCExpr *AddrDelta =
319 MCBinaryExpr::create(MCBinaryExpr::Sub, ARef, BRef, Context);
323 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
324 const MCSymbol *Label, int PointerSize) {
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, LineDelta, 0);
335 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
336 const MCSymbol *LastLabel,
337 const MCSymbol *Label,
338 unsigned PointerSize) {
340 emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
343 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
345 if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
346 MCDwarfLineAddr::Emit(this, LineDelta, Res);
349 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
352 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
353 const MCSymbol *Label) {
354 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
356 if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
357 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
360 insert(new MCDwarfCallFrameFragment(*AddrDelta));
363 void MCObjectStreamer::EmitBytes(StringRef Data) {
364 MCLineEntry::Make(this, getCurrentSection().first);
365 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
368 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
371 unsigned MaxBytesToEmit) {
372 if (MaxBytesToEmit == 0)
373 MaxBytesToEmit = ByteAlignment;
374 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
376 // Update the maximum alignment on the current section if necessary.
377 MCSection *CurSec = getCurrentSection().first;
378 if (ByteAlignment > CurSec->getAlignment())
379 CurSec->setAlignment(ByteAlignment);
382 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
383 unsigned MaxBytesToEmit) {
384 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
385 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
388 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
389 unsigned char Value) {
391 if (Offset->evaluateAsAbsolute(Res, getAssembler())) {
392 insert(new MCOrgFragment(*Offset, Value));
396 MCSymbol *CurrentPos = getContext().createTempSymbol();
397 EmitLabel(CurrentPos);
398 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
400 MCSymbolRefExpr::create(CurrentPos, Variant, getContext());
401 const MCExpr *Delta =
402 MCBinaryExpr::create(MCBinaryExpr::Sub, Offset, Ref, getContext());
404 if (!Delta->evaluateAsAbsolute(Res, getAssembler()))
406 EmitFill(Res, Value);
410 // Associate GPRel32 fixup with data and resize data area
411 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
412 MCDataFragment *DF = getOrCreateDataFragment();
414 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
416 DF->getContents().resize(DF->getContents().size() + 4, 0);
419 // Associate GPRel32 fixup with data and resize data area
420 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
421 MCDataFragment *DF = getOrCreateDataFragment();
423 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
425 DF->getContents().resize(DF->getContents().size() + 8, 0);
428 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
429 // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
430 // problems evaluating expressions across multiple fragments.
431 getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
434 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
435 const MCSection *Sec = getCurrentSection().first;
436 assert(Sec && "need a section");
437 unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
438 insert(new MCFillFragment(0, ItemSize, NumBytes));
441 void MCObjectStreamer::FinishImpl() {
442 // If we are generating dwarf for assembly source files dump out the sections.
443 if (getContext().getGenDwarfForAssembly())
444 MCGenDwarfInfo::Emit(this);
446 // Dump out the dwarf file & directory tables and line tables.
447 MCDwarfLineTable::Emit(this);
449 flushPendingLabels(nullptr);
450 getAssembler().Finish();