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 have symbol data.
61 if (!Assembler->hasSymbolData(*Hi) || !Assembler->hasSymbolData(*Lo))
64 // Must both be assigned to the same (valid) fragment.
65 if (!Hi->getFragment() || Hi->getFragment() != Lo->getFragment())
68 // Must be a data fragment.
69 if (!isa<MCDataFragment>(Hi->getFragment()))
72 assert(Hi->getOffset() >= Lo->getOffset() &&
73 "Expected Hi to be greater than Lo");
74 EmitIntValue(Hi->getOffset() - Lo->getOffset(), Size);
78 void MCObjectStreamer::reset() {
81 CurInsertionPoint = MCSection::iterator();
83 EmitDebugFrame = false;
84 PendingLabels.clear();
88 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
89 if (!getNumFrameInfos())
93 MCDwarfFrameEmitter::Emit(*this, MAB, true);
96 MCDwarfFrameEmitter::Emit(*this, MAB, false);
99 MCFragment *MCObjectStreamer::getCurrentFragment() const {
100 assert(getCurrentSectionOnly() && "No current section!");
102 if (CurInsertionPoint != getCurrentSectionOnly()->getFragmentList().begin())
103 return std::prev(CurInsertionPoint);
108 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
109 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
110 // When bundling is enabled, we don't want to add data to a fragment that
111 // already has instructions (see MCELFStreamer::EmitInstToData for details)
112 if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() &&
113 F->hasInstructions())) {
114 F = new MCDataFragment();
120 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
121 Assembler->registerSymbol(Sym);
124 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
125 MCStreamer::EmitCFISections(EH, Debug);
127 EmitDebugFrame = Debug;
130 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
132 MCStreamer::EmitValueImpl(Value, Size, Loc);
133 MCDataFragment *DF = getOrCreateDataFragment();
135 MCLineEntry::Make(this, getCurrentSection().first);
137 // Avoid fixups when possible.
139 if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
140 EmitIntValue(AbsValue, Size);
143 DF->getFixups().push_back(
144 MCFixup::create(DF->getContents().size(), Value,
145 MCFixup::getKindForSize(Size, false), Loc));
146 DF->getContents().resize(DF->getContents().size() + Size, 0);
149 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
150 // We need to create a local symbol to avoid relocations.
151 Frame.Begin = getContext().createTempSymbol();
152 EmitLabel(Frame.Begin);
155 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
156 Frame.End = getContext().createTempSymbol();
157 EmitLabel(Frame.End);
160 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
161 MCStreamer::EmitLabel(Symbol);
163 getAssembler().registerSymbol(*Symbol);
164 assert(!Symbol->getFragment() && "Unexpected fragment on symbol data!");
166 // If there is a current fragment, mark the symbol as pointing into it.
167 // Otherwise queue the label and set its fragment pointer when we emit the
169 auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
170 if (F && !(getAssembler().isBundlingEnabled() &&
171 getAssembler().getRelaxAll())) {
172 Symbol->setFragment(F);
173 Symbol->setOffset(F->getContents().size());
175 PendingLabels.push_back(Symbol);
179 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
181 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
182 EmitULEB128IntValue(IntValue);
185 insert(new MCLEBFragment(*Value, false));
188 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
190 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
191 EmitSLEB128IntValue(IntValue);
194 insert(new MCLEBFragment(*Value, true));
197 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
198 const MCSymbol *Symbol) {
199 report_fatal_error("This file format doesn't support weak aliases.");
202 void MCObjectStreamer::ChangeSection(MCSection *Section,
203 const MCExpr *Subsection) {
204 changeSectionImpl(Section, Subsection);
207 bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
208 const MCExpr *Subsection) {
209 assert(Section && "Cannot switch to a null section!");
210 flushPendingLabels(nullptr);
212 bool Created = getAssembler().registerSection(*Section);
214 int64_t IntSubsection = 0;
216 !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
217 report_fatal_error("Cannot evaluate subsection number");
218 if (IntSubsection < 0 || IntSubsection > 8192)
219 report_fatal_error("Subsection number out of range");
221 Section->getSubsectionInsertionPoint(unsigned(IntSubsection));
225 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
226 getAssembler().registerSymbol(*Symbol);
227 MCStreamer::EmitAssignment(Symbol, Value);
230 bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
231 return Sec.hasInstructions();
234 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
235 const MCSubtargetInfo &STI) {
236 MCStreamer::EmitInstruction(Inst, STI);
238 MCSection *Sec = getCurrentSectionOnly();
239 Sec->setHasInstructions(true);
241 // Now that a machine instruction has been assembled into this section, make
242 // a line entry for any .loc directive that has been seen.
243 MCLineEntry::Make(this, getCurrentSection().first);
245 // If this instruction doesn't need relaxation, just emit it as data.
246 MCAssembler &Assembler = getAssembler();
247 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
248 EmitInstToData(Inst, STI);
252 // Otherwise, relax and emit it as data if either:
253 // - The RelaxAll flag was passed
254 // - Bundling is enabled and this instruction is inside a bundle-locked
255 // group. We want to emit all such instructions into the same data
257 if (Assembler.getRelaxAll() ||
258 (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) {
260 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
261 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
262 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
263 EmitInstToData(Relaxed, STI);
267 // Otherwise emit to a separate fragment.
268 EmitInstToFragment(Inst, STI);
271 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
272 const MCSubtargetInfo &STI) {
273 if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled())
274 llvm_unreachable("All instructions should have already been relaxed");
276 // Always create a new, separate fragment here, because its size can change
277 // during relaxation.
278 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
281 SmallString<128> Code;
282 raw_svector_ostream VecOS(Code);
283 getAssembler().getEmitter().encodeInstruction(Inst, VecOS, IF->getFixups(),
286 IF->getContents().append(Code.begin(), Code.end());
290 static const char *const BundlingNotImplementedMsg =
291 "Aligned bundling is not implemented for this object format";
294 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
295 llvm_unreachable(BundlingNotImplementedMsg);
298 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
299 llvm_unreachable(BundlingNotImplementedMsg);
302 void MCObjectStreamer::EmitBundleUnlock() {
303 llvm_unreachable(BundlingNotImplementedMsg);
306 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
307 unsigned Column, unsigned Flags,
309 unsigned Discriminator,
310 StringRef FileName) {
311 // In case we see two .loc directives in a row, make sure the
312 // first one gets a line entry.
313 MCLineEntry::Make(this, getCurrentSection().first);
315 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
316 Isa, Discriminator, FileName);
319 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
321 MCContext &Context = OS.getContext();
322 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
323 const MCExpr *ARef = MCSymbolRefExpr::Create(A, Variant, Context);
324 const MCExpr *BRef = MCSymbolRefExpr::Create(B, Variant, Context);
325 const MCExpr *AddrDelta =
326 MCBinaryExpr::Create(MCBinaryExpr::Sub, ARef, BRef, Context);
330 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
331 const MCSymbol *Label, int PointerSize) {
332 // emit the sequence to set the address
333 OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
334 OS.EmitULEB128IntValue(PointerSize + 1);
335 OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
336 OS.EmitSymbolValue(Label, PointerSize);
338 // emit the sequence for the LineDelta (from 1) and a zero address delta.
339 MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
342 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
343 const MCSymbol *LastLabel,
344 const MCSymbol *Label,
345 unsigned PointerSize) {
347 emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
350 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
352 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
353 MCDwarfLineAddr::Emit(this, LineDelta, Res);
356 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
359 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
360 const MCSymbol *Label) {
361 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
363 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
364 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
367 insert(new MCDwarfCallFrameFragment(*AddrDelta));
370 void MCObjectStreamer::EmitBytes(StringRef Data) {
371 MCLineEntry::Make(this, getCurrentSection().first);
372 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
375 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
378 unsigned MaxBytesToEmit) {
379 if (MaxBytesToEmit == 0)
380 MaxBytesToEmit = ByteAlignment;
381 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
383 // Update the maximum alignment on the current section if necessary.
384 MCSection *CurSec = getCurrentSection().first;
385 if (ByteAlignment > CurSec->getAlignment())
386 CurSec->setAlignment(ByteAlignment);
389 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
390 unsigned MaxBytesToEmit) {
391 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
392 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
395 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
396 unsigned char Value) {
398 if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
399 insert(new MCOrgFragment(*Offset, Value));
403 MCSymbol *CurrentPos = getContext().createTempSymbol();
404 EmitLabel(CurrentPos);
405 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
407 MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
408 const MCExpr *Delta =
409 MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
411 if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
413 EmitFill(Res, Value);
417 // Associate GPRel32 fixup with data and resize data area
418 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
419 MCDataFragment *DF = getOrCreateDataFragment();
421 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
423 DF->getContents().resize(DF->getContents().size() + 4, 0);
426 // Associate GPRel32 fixup with data and resize data area
427 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
428 MCDataFragment *DF = getOrCreateDataFragment();
430 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
432 DF->getContents().resize(DF->getContents().size() + 8, 0);
435 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
436 // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
437 // problems evaluating expressions across multiple fragments.
438 getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
441 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
442 const MCSection *Sec = getCurrentSection().first;
443 assert(Sec && "need a section");
444 unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
445 insert(new MCFillFragment(0, ItemSize, NumBytes));
448 void MCObjectStreamer::FinishImpl() {
449 // If we are generating dwarf for assembly source files dump out the sections.
450 if (getContext().getGenDwarfForAssembly())
451 MCGenDwarfInfo::Emit(this);
453 // Dump out the dwarf file & directory tables and line tables.
454 MCDwarfLineTable::Emit(this);
456 flushPendingLabels(nullptr);
457 getAssembler().Finish();