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/MCCodeView.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCDwarf.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCObjectWriter.h"
21 #include "llvm/MC/MCSection.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/TargetRegistry.h"
28 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
29 raw_pwrite_stream &OS,
30 MCCodeEmitter *Emitter_)
31 : MCStreamer(Context),
32 Assembler(new MCAssembler(Context, TAB, *Emitter_,
33 *TAB.createObjectWriter(OS))),
34 EmitEHFrame(true), EmitDebugFrame(false) {}
36 MCObjectStreamer::~MCObjectStreamer() {
37 delete &Assembler->getBackend();
38 delete &Assembler->getEmitter();
39 delete &Assembler->getWriter();
43 void MCObjectStreamer::flushPendingLabels(MCFragment *F, uint64_t FOffset) {
44 if (PendingLabels.empty())
47 F = new MCDataFragment();
48 MCSection *CurSection = getCurrentSectionOnly();
49 CurSection->getFragmentList().insert(CurInsertionPoint, F);
50 F->setParent(CurSection);
52 for (MCSymbol *Sym : PendingLabels) {
54 Sym->setOffset(FOffset);
56 PendingLabels.clear();
59 void MCObjectStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi,
62 // If not assigned to the same (valid) fragment, fallback.
63 if (!Hi->getFragment() || Hi->getFragment() != Lo->getFragment() ||
64 Hi->isVariable() || Lo->isVariable()) {
65 MCStreamer::emitAbsoluteSymbolDiff(Hi, Lo, Size);
69 EmitIntValue(Hi->getOffset() - Lo->getOffset(), Size);
72 void MCObjectStreamer::reset() {
75 CurInsertionPoint = MCSection::iterator();
77 EmitDebugFrame = false;
78 PendingLabels.clear();
82 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
83 if (!getNumFrameInfos())
87 MCDwarfFrameEmitter::Emit(*this, MAB, true);
90 MCDwarfFrameEmitter::Emit(*this, MAB, false);
93 MCFragment *MCObjectStreamer::getCurrentFragment() const {
94 assert(getCurrentSectionOnly() && "No current section!");
96 if (CurInsertionPoint != getCurrentSectionOnly()->getFragmentList().begin())
97 return &*std::prev(CurInsertionPoint);
102 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
103 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
104 // When bundling is enabled, we don't want to add data to a fragment that
105 // already has instructions (see MCELFStreamer::EmitInstToData for details)
106 if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() &&
107 F->hasInstructions())) {
108 F = new MCDataFragment();
114 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
115 Assembler->registerSymbol(Sym);
118 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
119 MCStreamer::EmitCFISections(EH, Debug);
121 EmitDebugFrame = Debug;
124 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
126 MCStreamer::EmitValueImpl(Value, Size, Loc);
127 MCDataFragment *DF = getOrCreateDataFragment();
128 flushPendingLabels(DF, DF->getContents().size());
130 MCCVLineEntry::Make(this);
131 MCDwarfLineEntry::Make(this, getCurrentSectionOnly());
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);
161 // If there is a current fragment, mark the symbol as pointing into it.
162 // Otherwise queue the label and set its fragment pointer when we emit the
164 auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
165 if (F && !(getAssembler().isBundlingEnabled() &&
166 getAssembler().getRelaxAll())) {
167 Symbol->setFragment(F);
168 Symbol->setOffset(F->getContents().size());
170 PendingLabels.push_back(Symbol);
174 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
176 if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
177 EmitULEB128IntValue(IntValue);
180 insert(new MCLEBFragment(*Value, false));
183 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
185 if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
186 EmitSLEB128IntValue(IntValue);
189 insert(new MCLEBFragment(*Value, true));
192 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
193 const MCSymbol *Symbol) {
194 report_fatal_error("This file format doesn't support weak aliases.");
197 void MCObjectStreamer::ChangeSection(MCSection *Section,
198 const MCExpr *Subsection) {
199 changeSectionImpl(Section, Subsection);
202 bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
203 const MCExpr *Subsection) {
204 assert(Section && "Cannot switch to a null section!");
205 flushPendingLabels(nullptr);
207 bool Created = getAssembler().registerSection(*Section);
209 int64_t IntSubsection = 0;
211 !Subsection->evaluateAsAbsolute(IntSubsection, getAssembler()))
212 report_fatal_error("Cannot evaluate subsection number");
213 if (IntSubsection < 0 || IntSubsection > 8192)
214 report_fatal_error("Subsection number out of range");
216 Section->getSubsectionInsertionPoint(unsigned(IntSubsection));
220 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
221 getAssembler().registerSymbol(*Symbol);
222 MCStreamer::EmitAssignment(Symbol, Value);
225 bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
226 return Sec.hasInstructions();
229 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
230 const MCSubtargetInfo &STI) {
231 MCStreamer::EmitInstruction(Inst, STI);
233 MCSection *Sec = getCurrentSectionOnly();
234 Sec->setHasInstructions(true);
236 // Now that a machine instruction has been assembled into this section, make
237 // a line entry for any .loc directive that has been seen.
238 MCCVLineEntry::Make(this);
239 MCDwarfLineEntry::Make(this, getCurrentSectionOnly());
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, STI, Relaxed);
257 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
258 getAssembler().getBackend().relaxInstruction(Relaxed, STI, 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(),
281 IF->getContents().append(Code.begin(), Code.end());
285 static const char *const BundlingNotImplementedMsg =
286 "Aligned bundling is not implemented for this object format";
289 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
290 llvm_unreachable(BundlingNotImplementedMsg);
293 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
294 llvm_unreachable(BundlingNotImplementedMsg);
297 void MCObjectStreamer::EmitBundleUnlock() {
298 llvm_unreachable(BundlingNotImplementedMsg);
301 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
302 unsigned Column, unsigned Flags,
304 unsigned Discriminator,
305 StringRef FileName) {
306 // In case we see two .loc directives in a row, make sure the
307 // first one gets a line entry.
308 MCDwarfLineEntry::Make(this, getCurrentSectionOnly());
310 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
311 Isa, Discriminator, FileName);
314 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
316 MCContext &Context = OS.getContext();
317 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
318 const MCExpr *ARef = MCSymbolRefExpr::create(A, Variant, Context);
319 const MCExpr *BRef = MCSymbolRefExpr::create(B, Variant, Context);
320 const MCExpr *AddrDelta =
321 MCBinaryExpr::create(MCBinaryExpr::Sub, ARef, BRef, Context);
325 static void emitDwarfSetLineAddr(MCObjectStreamer &OS,
326 MCDwarfLineTableParams Params,
327 int64_t LineDelta, const MCSymbol *Label,
329 // emit the sequence to set the address
330 OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
331 OS.EmitULEB128IntValue(PointerSize + 1);
332 OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
333 OS.EmitSymbolValue(Label, PointerSize);
335 // emit the sequence for the LineDelta (from 1) and a zero address delta.
336 MCDwarfLineAddr::Emit(&OS, Params, LineDelta, 0);
339 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
340 const MCSymbol *LastLabel,
341 const MCSymbol *Label,
342 unsigned PointerSize) {
344 emitDwarfSetLineAddr(*this, Assembler->getDWARFLinetableParams(), LineDelta,
348 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
350 if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
351 MCDwarfLineAddr::Emit(this, Assembler->getDWARFLinetableParams(), LineDelta,
355 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
358 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
359 const MCSymbol *Label) {
360 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
362 if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
363 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
366 insert(new MCDwarfCallFrameFragment(*AddrDelta));
369 void MCObjectStreamer::EmitCVLocDirective(unsigned FunctionId, unsigned FileNo,
370 unsigned Line, unsigned Column,
371 bool PrologueEnd, bool IsStmt,
372 StringRef FileName, SMLoc Loc) {
373 // In case we see two .cv_loc directives in a row, make sure the
374 // first one gets a line entry.
375 MCCVLineEntry::Make(this);
377 this->MCStreamer::EmitCVLocDirective(FunctionId, FileNo, Line, Column,
378 PrologueEnd, IsStmt, FileName, Loc);
381 void MCObjectStreamer::EmitCVLinetableDirective(unsigned FunctionId,
382 const MCSymbol *Begin,
383 const MCSymbol *End) {
384 getContext().getCVContext().emitLineTableForFunction(*this, FunctionId, Begin,
386 this->MCStreamer::EmitCVLinetableDirective(FunctionId, Begin, End);
389 void MCObjectStreamer::EmitCVInlineLinetableDirective(
390 unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum,
391 const MCSymbol *FnStartSym, const MCSymbol *FnEndSym) {
392 getContext().getCVContext().emitInlineLineTableForFunction(
393 *this, PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym,
395 this->MCStreamer::EmitCVInlineLinetableDirective(
396 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
399 void MCObjectStreamer::EmitCVDefRangeDirective(
400 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
401 StringRef FixedSizePortion) {
402 getContext().getCVContext().emitDefRange(*this, Ranges, FixedSizePortion);
403 this->MCStreamer::EmitCVDefRangeDirective(Ranges, FixedSizePortion);
406 void MCObjectStreamer::EmitCVStringTableDirective() {
407 getContext().getCVContext().emitStringTable(*this);
409 void MCObjectStreamer::EmitCVFileChecksumsDirective() {
410 getContext().getCVContext().emitFileChecksums(*this);
414 void MCObjectStreamer::EmitBytes(StringRef Data) {
415 MCCVLineEntry::Make(this);
416 MCDwarfLineEntry::Make(this, getCurrentSectionOnly());
417 MCDataFragment *DF = getOrCreateDataFragment();
418 flushPendingLabels(DF, DF->getContents().size());
419 DF->getContents().append(Data.begin(), Data.end());
422 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
425 unsigned MaxBytesToEmit) {
426 if (MaxBytesToEmit == 0)
427 MaxBytesToEmit = ByteAlignment;
428 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
430 // Update the maximum alignment on the current section if necessary.
431 MCSection *CurSec = getCurrentSectionOnly();
432 if (ByteAlignment > CurSec->getAlignment())
433 CurSec->setAlignment(ByteAlignment);
436 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
437 unsigned MaxBytesToEmit) {
438 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
439 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
442 void MCObjectStreamer::emitValueToOffset(const MCExpr *Offset,
445 insert(new MCOrgFragment(*Offset, Value, Loc));
448 // Associate DTPRel32 fixup with data and resize data area
449 void MCObjectStreamer::EmitDTPRel32Value(const MCExpr *Value) {
450 MCDataFragment *DF = getOrCreateDataFragment();
451 flushPendingLabels(DF, DF->getContents().size());
453 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
454 Value, FK_DTPRel_4));
455 DF->getContents().resize(DF->getContents().size() + 4, 0);
458 // Associate DTPRel64 fixup with data and resize data area
459 void MCObjectStreamer::EmitDTPRel64Value(const MCExpr *Value) {
460 MCDataFragment *DF = getOrCreateDataFragment();
461 flushPendingLabels(DF, DF->getContents().size());
463 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
464 Value, FK_DTPRel_8));
465 DF->getContents().resize(DF->getContents().size() + 8, 0);
468 // Associate TPRel32 fixup with data and resize data area
469 void MCObjectStreamer::EmitTPRel32Value(const MCExpr *Value) {
470 MCDataFragment *DF = getOrCreateDataFragment();
471 flushPendingLabels(DF, DF->getContents().size());
473 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
475 DF->getContents().resize(DF->getContents().size() + 4, 0);
478 // Associate TPRel64 fixup with data and resize data area
479 void MCObjectStreamer::EmitTPRel64Value(const MCExpr *Value) {
480 MCDataFragment *DF = getOrCreateDataFragment();
481 flushPendingLabels(DF, DF->getContents().size());
483 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
485 DF->getContents().resize(DF->getContents().size() + 8, 0);
488 // Associate GPRel32 fixup with data and resize data area
489 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
490 MCDataFragment *DF = getOrCreateDataFragment();
491 flushPendingLabels(DF, DF->getContents().size());
493 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
495 DF->getContents().resize(DF->getContents().size() + 4, 0);
498 // Associate GPRel64 fixup with data and resize data area
499 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
500 MCDataFragment *DF = getOrCreateDataFragment();
501 flushPendingLabels(DF, DF->getContents().size());
503 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
505 DF->getContents().resize(DF->getContents().size() + 8, 0);
508 bool MCObjectStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name,
509 const MCExpr *Expr, SMLoc Loc) {
511 if (!Offset.evaluateAsAbsolute(OffsetValue))
512 llvm_unreachable("Offset is not absolute");
515 llvm_unreachable("Offset is negative");
517 MCDataFragment *DF = getOrCreateDataFragment();
518 flushPendingLabels(DF, DF->getContents().size());
520 Optional<MCFixupKind> MaybeKind = Assembler->getBackend().getFixupKind(Name);
521 if (!MaybeKind.hasValue())
524 MCFixupKind Kind = *MaybeKind;
528 MCSymbolRefExpr::create(getContext().createTempSymbol(), getContext());
529 DF->getFixups().push_back(MCFixup::create(OffsetValue, Expr, Kind, Loc));
533 void MCObjectStreamer::emitFill(uint64_t NumBytes, uint8_t FillValue) {
534 assert(getCurrentSectionOnly() && "need a section");
535 insert(new MCFillFragment(FillValue, NumBytes));
538 void MCObjectStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
540 MCDataFragment *DF = getOrCreateDataFragment();
541 flushPendingLabels(DF, DF->getContents().size());
544 if (!NumBytes.evaluateAsAbsolute(IntNumBytes, getAssembler())) {
545 getContext().reportError(Loc, "expected absolute expression");
549 if (IntNumBytes <= 0) {
550 getContext().reportError(Loc, "invalid number of bytes");
554 emitFill(IntNumBytes, FillValue);
557 void MCObjectStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
558 int64_t Expr, SMLoc Loc) {
559 int64_t IntNumValues;
560 if (!NumValues.evaluateAsAbsolute(IntNumValues, getAssembler())) {
561 getContext().reportError(Loc, "expected absolute expression");
565 if (IntNumValues < 0) {
566 getContext().getSourceManager()->PrintMessage(
567 Loc, SourceMgr::DK_Warning,
568 "'.fill' directive with negative repeat count has no effect");
572 MCStreamer::emitFill(IntNumValues, Size, Expr);
575 void MCObjectStreamer::FinishImpl() {
576 // If we are generating dwarf for assembly source files dump out the sections.
577 if (getContext().getGenDwarfForAssembly())
578 MCGenDwarfInfo::Emit(this);
580 // Dump out the dwarf file & directory tables and line tables.
581 MCDwarfLineTable::Emit(this, getAssembler().getDWARFLinetableParams());
583 flushPendingLabels(nullptr);
584 getAssembler().Finish();