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 CurSectionData(nullptr), 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 CurSectionData->getFragmentList().insert(CurInsertionPoint, F);
46 F->setParent(CurSectionData);
48 for (MCSymbolData *SD : PendingLabels) {
50 SD->setOffset(FOffset);
52 PendingLabels.clear();
56 bool MCObjectStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi,
59 // Must have symbol data.
60 if (!Assembler->hasSymbolData(*Hi) || !Assembler->hasSymbolData(*Lo))
62 auto &HiD = Assembler->getSymbolData(*Hi);
63 auto &LoD = Assembler->getSymbolData(*Lo);
65 // Must both be assigned to the same (valid) fragment.
66 if (!HiD.getFragment() || HiD.getFragment() != LoD.getFragment())
69 // Must be a data fragment.
70 if (!isa<MCDataFragment>(HiD.getFragment()))
73 assert(HiD.getOffset() >= LoD.getOffset() &&
74 "Expected Hi to be greater than Lo");
75 EmitIntValue(HiD.getOffset() - LoD.getOffset(), Size);
79 void MCObjectStreamer::reset() {
82 CurSectionData = nullptr;
83 CurInsertionPoint = MCSectionData::iterator();
85 EmitDebugFrame = false;
86 PendingLabels.clear();
90 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
91 if (!getNumFrameInfos())
95 MCDwarfFrameEmitter::Emit(*this, MAB, true);
98 MCDwarfFrameEmitter::Emit(*this, MAB, false);
101 MCFragment *MCObjectStreamer::getCurrentFragment() const {
102 assert(getCurrentSectionData() && "No current section!");
104 if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
105 return std::prev(CurInsertionPoint);
110 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
111 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
112 // When bundling is enabled, we don't want to add data to a fragment that
113 // already has instructions (see MCELFStreamer::EmitInstToData for details)
114 if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() &&
115 F->hasInstructions())) {
116 F = new MCDataFragment();
122 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
123 Assembler->getOrCreateSymbolData(Sym);
126 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
127 MCStreamer::EmitCFISections(EH, Debug);
129 EmitDebugFrame = Debug;
132 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
134 MCStreamer::EmitValueImpl(Value, Size, Loc);
135 MCDataFragment *DF = getOrCreateDataFragment();
137 MCLineEntry::Make(this, getCurrentSection().first);
139 // Avoid fixups when possible.
141 if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
142 EmitIntValue(AbsValue, Size);
145 DF->getFixups().push_back(
146 MCFixup::create(DF->getContents().size(), Value,
147 MCFixup::getKindForSize(Size, false), Loc));
148 DF->getContents().resize(DF->getContents().size() + Size, 0);
151 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
152 // We need to create a local symbol to avoid relocations.
153 Frame.Begin = getContext().createTempSymbol();
154 EmitLabel(Frame.Begin);
157 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
158 Frame.End = getContext().createTempSymbol();
159 EmitLabel(Frame.End);
162 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
163 MCStreamer::EmitLabel(Symbol);
165 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
166 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
168 // If there is a current fragment, mark the symbol as pointing into it.
169 // Otherwise queue the label and set its fragment pointer when we emit the
171 auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
172 if (F && !(getAssembler().isBundlingEnabled() &&
173 getAssembler().getRelaxAll())) {
175 SD.setOffset(F->getContents().size());
177 PendingLabels.push_back(&SD);
181 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
183 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
184 EmitULEB128IntValue(IntValue);
187 insert(new MCLEBFragment(*Value, false));
190 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
192 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
193 EmitSLEB128IntValue(IntValue);
196 insert(new MCLEBFragment(*Value, true));
199 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
200 const MCSymbol *Symbol) {
201 report_fatal_error("This file format doesn't support weak aliases.");
204 void MCObjectStreamer::ChangeSection(MCSection *Section,
205 const MCExpr *Subsection) {
206 changeSectionImpl(Section, Subsection);
209 bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
210 const MCExpr *Subsection) {
211 assert(Section && "Cannot switch to a null section!");
212 flushPendingLabels(nullptr);
215 getAssembler().getOrCreateSectionData(*Section, &Created);
216 CurSectionData = Section;
218 int64_t IntSubsection = 0;
220 !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
221 report_fatal_error("Cannot evaluate subsection number");
222 if (IntSubsection < 0 || IntSubsection > 8192)
223 report_fatal_error("Subsection number out of range");
225 CurSectionData->getSectionData().getSubsectionInsertionPoint(
226 unsigned(IntSubsection));
230 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
231 getAssembler().getOrCreateSymbolData(*Symbol);
232 MCStreamer::EmitAssignment(Symbol, Value);
235 bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
236 return Sec.hasInstructions();
239 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
240 const MCSubtargetInfo &STI) {
241 MCStreamer::EmitInstruction(Inst, STI);
243 MCSection *Sec = getCurrentSectionData();
244 Sec->setHasInstructions(true);
246 // Now that a machine instruction has been assembled into this section, make
247 // a line entry for any .loc directive that has been seen.
248 MCLineEntry::Make(this, getCurrentSection().first);
250 // If this instruction doesn't need relaxation, just emit it as data.
251 MCAssembler &Assembler = getAssembler();
252 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
253 EmitInstToData(Inst, STI);
257 // Otherwise, relax and emit it as data if either:
258 // - The RelaxAll flag was passed
259 // - Bundling is enabled and this instruction is inside a bundle-locked
260 // group. We want to emit all such instructions into the same data
262 if (Assembler.getRelaxAll() ||
263 (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) {
265 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
266 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
267 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
268 EmitInstToData(Relaxed, STI);
272 // Otherwise emit to a separate fragment.
273 EmitInstToFragment(Inst, STI);
276 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
277 const MCSubtargetInfo &STI) {
278 if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled())
279 llvm_unreachable("All instructions should have already been relaxed");
281 // Always create a new, separate fragment here, because its size can change
282 // during relaxation.
283 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
286 SmallString<128> Code;
287 raw_svector_ostream VecOS(Code);
288 getAssembler().getEmitter().encodeInstruction(Inst, VecOS, IF->getFixups(),
291 IF->getContents().append(Code.begin(), Code.end());
295 static const char *const BundlingNotImplementedMsg =
296 "Aligned bundling is not implemented for this object format";
299 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
300 llvm_unreachable(BundlingNotImplementedMsg);
303 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
304 llvm_unreachable(BundlingNotImplementedMsg);
307 void MCObjectStreamer::EmitBundleUnlock() {
308 llvm_unreachable(BundlingNotImplementedMsg);
311 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
312 unsigned Column, unsigned Flags,
314 unsigned Discriminator,
315 StringRef FileName) {
316 // In case we see two .loc directives in a row, make sure the
317 // first one gets a line entry.
318 MCLineEntry::Make(this, getCurrentSection().first);
320 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
321 Isa, Discriminator, FileName);
324 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
326 MCContext &Context = OS.getContext();
327 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
328 const MCExpr *ARef = MCSymbolRefExpr::Create(A, Variant, Context);
329 const MCExpr *BRef = MCSymbolRefExpr::Create(B, Variant, Context);
330 const MCExpr *AddrDelta =
331 MCBinaryExpr::Create(MCBinaryExpr::Sub, ARef, BRef, Context);
335 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
336 const MCSymbol *Label, int PointerSize) {
337 // emit the sequence to set the address
338 OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
339 OS.EmitULEB128IntValue(PointerSize + 1);
340 OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
341 OS.EmitSymbolValue(Label, PointerSize);
343 // emit the sequence for the LineDelta (from 1) and a zero address delta.
344 MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
347 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
348 const MCSymbol *LastLabel,
349 const MCSymbol *Label,
350 unsigned PointerSize) {
352 emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
355 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
357 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
358 MCDwarfLineAddr::Emit(this, LineDelta, Res);
361 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
364 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
365 const MCSymbol *Label) {
366 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
368 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
369 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
372 insert(new MCDwarfCallFrameFragment(*AddrDelta));
375 void MCObjectStreamer::EmitBytes(StringRef Data) {
376 MCLineEntry::Make(this, getCurrentSection().first);
377 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
380 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
383 unsigned MaxBytesToEmit) {
384 if (MaxBytesToEmit == 0)
385 MaxBytesToEmit = ByteAlignment;
386 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
388 // Update the maximum alignment on the current section if necessary.
389 MCSection *CurSec = getCurrentSection().first;
390 if (ByteAlignment > CurSec->getAlignment())
391 CurSec->setAlignment(ByteAlignment);
394 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
395 unsigned MaxBytesToEmit) {
396 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
397 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
400 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
401 unsigned char Value) {
403 if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
404 insert(new MCOrgFragment(*Offset, Value));
408 MCSymbol *CurrentPos = getContext().createTempSymbol();
409 EmitLabel(CurrentPos);
410 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
412 MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
413 const MCExpr *Delta =
414 MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
416 if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
418 EmitFill(Res, Value);
422 // Associate GPRel32 fixup with data and resize data area
423 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
424 MCDataFragment *DF = getOrCreateDataFragment();
426 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
428 DF->getContents().resize(DF->getContents().size() + 4, 0);
431 // Associate GPRel32 fixup with data and resize data area
432 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
433 MCDataFragment *DF = getOrCreateDataFragment();
435 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
437 DF->getContents().resize(DF->getContents().size() + 8, 0);
440 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
441 // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
442 // problems evaluating expressions across multiple fragments.
443 getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
446 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
447 const MCSection *Sec = getCurrentSection().first;
448 assert(Sec && "need a section");
449 unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
450 insert(new MCFillFragment(0, ItemSize, NumBytes));
453 void MCObjectStreamer::FinishImpl() {
454 // If we are generating dwarf for assembly source files dump out the sections.
455 if (getContext().getGenDwarfForAssembly())
456 MCGenDwarfInfo::Emit(this);
458 // Dump out the dwarf file & directory tables and line tables.
459 MCDwarfLineTable::Emit(this);
461 flushPendingLabels(nullptr);
462 getAssembler().Finish();