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 bool MCObjectStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi,
60 // Must both be assigned to the same (valid) fragment.
61 if (!Hi->getFragment() || Hi->getFragment() != Lo->getFragment())
64 // Must be a data fragment.
65 if (!isa<MCDataFragment>(Hi->getFragment()))
68 assert(Hi->getOffset() >= Lo->getOffset() &&
69 "Expected Hi to be greater than Lo");
70 EmitIntValue(Hi->getOffset() - Lo->getOffset(), Size);
74 void MCObjectStreamer::reset() {
77 CurInsertionPoint = MCSection::iterator();
79 EmitDebugFrame = false;
80 PendingLabels.clear();
84 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
85 if (!getNumFrameInfos())
89 MCDwarfFrameEmitter::Emit(*this, MAB, true);
92 MCDwarfFrameEmitter::Emit(*this, MAB, false);
95 MCFragment *MCObjectStreamer::getCurrentFragment() const {
96 assert(getCurrentSectionOnly() && "No current section!");
98 if (CurInsertionPoint != getCurrentSectionOnly()->getFragmentList().begin())
99 return std::prev(CurInsertionPoint);
104 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
105 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
106 // When bundling is enabled, we don't want to add data to a fragment that
107 // already has instructions (see MCELFStreamer::EmitInstToData for details)
108 if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() &&
109 F->hasInstructions())) {
110 F = new MCDataFragment();
116 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
117 Assembler->registerSymbol(Sym);
120 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
121 MCStreamer::EmitCFISections(EH, Debug);
123 EmitDebugFrame = Debug;
126 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
128 MCStreamer::EmitValueImpl(Value, Size, Loc);
129 MCDataFragment *DF = getOrCreateDataFragment();
131 MCLineEntry::Make(this, getCurrentSection().first);
133 // Avoid fixups when possible.
135 if (Value->evaluateAsAbsolute(AbsValue, getAssembler())) {
136 EmitIntValue(AbsValue, Size);
139 DF->getFixups().push_back(
140 MCFixup::create(DF->getContents().size(), Value,
141 MCFixup::getKindForSize(Size, false), Loc));
142 DF->getContents().resize(DF->getContents().size() + Size, 0);
145 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
146 // We need to create a local symbol to avoid relocations.
147 Frame.Begin = getContext().createTempSymbol();
148 EmitLabel(Frame.Begin);
151 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
152 Frame.End = getContext().createTempSymbol();
153 EmitLabel(Frame.End);
156 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
157 MCStreamer::EmitLabel(Symbol);
159 getAssembler().registerSymbol(*Symbol);
160 assert(!Symbol->getFragment() && "Unexpected fragment on symbol data!");
162 // If there is a current fragment, mark the symbol as pointing into it.
163 // Otherwise queue the label and set its fragment pointer when we emit the
165 auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
166 if (F && !(getAssembler().isBundlingEnabled() &&
167 getAssembler().getRelaxAll())) {
168 Symbol->setFragment(F);
169 Symbol->setOffset(F->getContents().size());
171 PendingLabels.push_back(Symbol);
175 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
177 if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
178 EmitULEB128IntValue(IntValue);
181 insert(new MCLEBFragment(*Value, false));
184 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
186 if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
187 EmitSLEB128IntValue(IntValue);
190 insert(new MCLEBFragment(*Value, true));
193 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
194 const MCSymbol *Symbol) {
195 report_fatal_error("This file format doesn't support weak aliases.");
198 void MCObjectStreamer::ChangeSection(MCSection *Section,
199 const MCExpr *Subsection) {
200 changeSectionImpl(Section, Subsection);
203 bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
204 const MCExpr *Subsection) {
205 assert(Section && "Cannot switch to a null section!");
206 flushPendingLabels(nullptr);
208 bool Created = getAssembler().registerSection(*Section);
210 int64_t IntSubsection = 0;
212 !Subsection->evaluateAsAbsolute(IntSubsection, getAssembler()))
213 report_fatal_error("Cannot evaluate subsection number");
214 if (IntSubsection < 0 || IntSubsection > 8192)
215 report_fatal_error("Subsection number out of range");
217 Section->getSubsectionInsertionPoint(unsigned(IntSubsection));
221 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
222 getAssembler().registerSymbol(*Symbol);
223 MCStreamer::EmitAssignment(Symbol, Value);
226 bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
227 return Sec.hasInstructions();
230 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
231 const MCSubtargetInfo &STI) {
232 MCStreamer::EmitInstruction(Inst, STI);
234 MCSection *Sec = getCurrentSectionOnly();
235 Sec->setHasInstructions(true);
237 // Now that a machine instruction has been assembled into this section, make
238 // a line entry for any .loc directive that has been seen.
239 MCLineEntry::Make(this, getCurrentSection().first);
241 // If this instruction doesn't need relaxation, just emit it as data.
242 MCAssembler &Assembler = getAssembler();
243 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
244 EmitInstToData(Inst, STI);
248 // Otherwise, relax and emit it as data if either:
249 // - The RelaxAll flag was passed
250 // - Bundling is enabled and this instruction is inside a bundle-locked
251 // group. We want to emit all such instructions into the same data
253 if (Assembler.getRelaxAll() ||
254 (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) {
256 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
257 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
258 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
259 EmitInstToData(Relaxed, STI);
263 // Otherwise emit to a separate fragment.
264 EmitInstToFragment(Inst, STI);
267 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
268 const MCSubtargetInfo &STI) {
269 if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled())
270 llvm_unreachable("All instructions should have already been relaxed");
272 // Always create a new, separate fragment here, because its size can change
273 // during relaxation.
274 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
277 SmallString<128> Code;
278 raw_svector_ostream VecOS(Code);
279 getAssembler().getEmitter().encodeInstruction(Inst, VecOS, IF->getFixups(),
282 IF->getContents().append(Code.begin(), Code.end());
286 static const char *const BundlingNotImplementedMsg =
287 "Aligned bundling is not implemented for this object format";
290 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
291 llvm_unreachable(BundlingNotImplementedMsg);
294 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
295 llvm_unreachable(BundlingNotImplementedMsg);
298 void MCObjectStreamer::EmitBundleUnlock() {
299 llvm_unreachable(BundlingNotImplementedMsg);
302 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
303 unsigned Column, unsigned Flags,
305 unsigned Discriminator,
306 StringRef FileName) {
307 // In case we see two .loc directives in a row, make sure the
308 // first one gets a line entry.
309 MCLineEntry::Make(this, getCurrentSection().first);
311 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
312 Isa, Discriminator, FileName);
315 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
317 MCContext &Context = OS.getContext();
318 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
319 const MCExpr *ARef = MCSymbolRefExpr::create(A, Variant, Context);
320 const MCExpr *BRef = MCSymbolRefExpr::create(B, Variant, Context);
321 const MCExpr *AddrDelta =
322 MCBinaryExpr::create(MCBinaryExpr::Sub, ARef, BRef, Context);
326 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
327 const MCSymbol *Label, int PointerSize) {
328 // emit the sequence to set the address
329 OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
330 OS.EmitULEB128IntValue(PointerSize + 1);
331 OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
332 OS.EmitSymbolValue(Label, PointerSize);
334 // emit the sequence for the LineDelta (from 1) and a zero address delta.
335 MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
338 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
339 const MCSymbol *LastLabel,
340 const MCSymbol *Label,
341 unsigned PointerSize) {
343 emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
346 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
348 if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
349 MCDwarfLineAddr::Emit(this, LineDelta, Res);
352 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
355 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
356 const MCSymbol *Label) {
357 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
359 if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
360 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
363 insert(new MCDwarfCallFrameFragment(*AddrDelta));
366 void MCObjectStreamer::EmitBytes(StringRef Data) {
367 MCLineEntry::Make(this, getCurrentSection().first);
368 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
371 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
374 unsigned MaxBytesToEmit) {
375 if (MaxBytesToEmit == 0)
376 MaxBytesToEmit = ByteAlignment;
377 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
379 // Update the maximum alignment on the current section if necessary.
380 MCSection *CurSec = getCurrentSection().first;
381 if (ByteAlignment > CurSec->getAlignment())
382 CurSec->setAlignment(ByteAlignment);
385 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
386 unsigned MaxBytesToEmit) {
387 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
388 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
391 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
392 unsigned char Value) {
394 if (Offset->evaluateAsAbsolute(Res, getAssembler())) {
395 insert(new MCOrgFragment(*Offset, Value));
399 MCSymbol *CurrentPos = getContext().createTempSymbol();
400 EmitLabel(CurrentPos);
401 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
403 MCSymbolRefExpr::create(CurrentPos, Variant, getContext());
404 const MCExpr *Delta =
405 MCBinaryExpr::create(MCBinaryExpr::Sub, Offset, Ref, getContext());
407 if (!Delta->evaluateAsAbsolute(Res, getAssembler()))
409 EmitFill(Res, Value);
413 // Associate GPRel32 fixup with data and resize data area
414 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
415 MCDataFragment *DF = getOrCreateDataFragment();
417 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
419 DF->getContents().resize(DF->getContents().size() + 4, 0);
422 // Associate GPRel32 fixup with data and resize data area
423 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
424 MCDataFragment *DF = getOrCreateDataFragment();
426 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
428 DF->getContents().resize(DF->getContents().size() + 8, 0);
431 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
432 // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
433 // problems evaluating expressions across multiple fragments.
434 getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
437 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
438 const MCSection *Sec = getCurrentSection().first;
439 assert(Sec && "need a section");
440 unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
441 insert(new MCFillFragment(0, 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);
452 flushPendingLabels(nullptr);
453 getAssembler().Finish();