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 void MCObjectStreamer::reset() {
59 CurSectionData = nullptr;
60 CurInsertionPoint = MCSectionData::iterator();
62 EmitDebugFrame = false;
63 PendingLabels.clear();
67 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
68 if (!getNumFrameInfos())
72 MCDwarfFrameEmitter::Emit(*this, MAB, true);
75 MCDwarfFrameEmitter::Emit(*this, MAB, false);
78 MCFragment *MCObjectStreamer::getCurrentFragment() const {
79 assert(getCurrentSectionData() && "No current section!");
81 if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
82 return std::prev(CurInsertionPoint);
87 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
88 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
89 // When bundling is enabled, we don't want to add data to a fragment that
90 // already has instructions (see MCELFStreamer::EmitInstToData for details)
91 if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() &&
92 F->hasInstructions())) {
93 F = new MCDataFragment();
99 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
100 Assembler->getOrCreateSymbolData(Sym);
103 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
104 MCStreamer::EmitCFISections(EH, Debug);
106 EmitDebugFrame = Debug;
109 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
111 MCStreamer::EmitValueImpl(Value, Size, Loc);
112 MCDataFragment *DF = getOrCreateDataFragment();
114 MCLineEntry::Make(this, getCurrentSection().first);
116 // Avoid fixups when possible.
118 if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
119 EmitIntValue(AbsValue, Size);
122 DF->getFixups().push_back(
123 MCFixup::create(DF->getContents().size(), Value,
124 MCFixup::getKindForSize(Size, false), Loc));
125 DF->getContents().resize(DF->getContents().size() + Size, 0);
128 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
129 // We need to create a local symbol to avoid relocations.
130 Frame.Begin = getContext().CreateTempSymbol();
131 EmitLabel(Frame.Begin);
134 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
135 Frame.End = getContext().CreateTempSymbol();
136 EmitLabel(Frame.End);
139 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
140 MCStreamer::EmitLabel(Symbol);
142 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
143 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
145 // If there is a current fragment, mark the symbol as pointing into it.
146 // Otherwise queue the label and set its fragment pointer when we emit the
148 auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
149 if (F && !(getAssembler().isBundlingEnabled() &&
150 getAssembler().getRelaxAll())) {
152 SD.setOffset(F->getContents().size());
154 PendingLabels.push_back(&SD);
158 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
160 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
161 EmitULEB128IntValue(IntValue);
164 insert(new MCLEBFragment(*Value, false));
167 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
169 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
170 EmitSLEB128IntValue(IntValue);
173 insert(new MCLEBFragment(*Value, true));
176 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
177 const MCSymbol *Symbol) {
178 report_fatal_error("This file format doesn't support weak aliases.");
181 void MCObjectStreamer::ChangeSection(const MCSection *Section,
182 const MCExpr *Subsection) {
183 changeSectionImpl(Section, Subsection);
186 bool MCObjectStreamer::changeSectionImpl(const MCSection *Section,
187 const MCExpr *Subsection) {
188 assert(Section && "Cannot switch to a null section!");
189 flushPendingLabels(nullptr);
192 CurSectionData = &getAssembler().getOrCreateSectionData(*Section, &Created);
194 int64_t IntSubsection = 0;
196 !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
197 report_fatal_error("Cannot evaluate subsection number");
198 if (IntSubsection < 0 || IntSubsection > 8192)
199 report_fatal_error("Subsection number out of range");
201 CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
205 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
206 getAssembler().getOrCreateSymbolData(*Symbol);
207 MCStreamer::EmitAssignment(Symbol, Value);
210 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
211 const MCSubtargetInfo &STI) {
212 MCStreamer::EmitInstruction(Inst, STI);
214 MCSectionData *SD = getCurrentSectionData();
215 SD->setHasInstructions(true);
217 // Now that a machine instruction has been assembled into this section, make
218 // a line entry for any .loc directive that has been seen.
219 MCLineEntry::Make(this, getCurrentSection().first);
221 // If this instruction doesn't need relaxation, just emit it as data.
222 MCAssembler &Assembler = getAssembler();
223 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
224 EmitInstToData(Inst, STI);
228 // Otherwise, relax and emit it as data if either:
229 // - The RelaxAll flag was passed
230 // - Bundling is enabled and this instruction is inside a bundle-locked
231 // group. We want to emit all such instructions into the same data
233 if (Assembler.getRelaxAll() ||
234 (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
236 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
237 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
238 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
239 EmitInstToData(Relaxed, STI);
243 // Otherwise emit to a separate fragment.
244 EmitInstToFragment(Inst, STI);
247 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
248 const MCSubtargetInfo &STI) {
249 if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled())
250 llvm_unreachable("All instructions should have already been relaxed");
252 // Always create a new, separate fragment here, because its size can change
253 // during relaxation.
254 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
257 SmallString<128> Code;
258 raw_svector_ostream VecOS(Code);
259 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups(),
262 IF->getContents().append(Code.begin(), Code.end());
266 static const char *const BundlingNotImplementedMsg =
267 "Aligned bundling is not implemented for this object format";
270 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
271 llvm_unreachable(BundlingNotImplementedMsg);
274 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
275 llvm_unreachable(BundlingNotImplementedMsg);
278 void MCObjectStreamer::EmitBundleUnlock() {
279 llvm_unreachable(BundlingNotImplementedMsg);
282 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
283 unsigned Column, unsigned Flags,
285 unsigned Discriminator,
286 StringRef FileName) {
287 // In case we see two .loc directives in a row, make sure the
288 // first one gets a line entry.
289 MCLineEntry::Make(this, getCurrentSection().first);
291 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
292 Isa, Discriminator, FileName);
295 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
297 MCContext &Context = OS.getContext();
298 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
299 const MCExpr *ARef = MCSymbolRefExpr::Create(A, Variant, Context);
300 const MCExpr *BRef = MCSymbolRefExpr::Create(B, Variant, Context);
301 const MCExpr *AddrDelta =
302 MCBinaryExpr::Create(MCBinaryExpr::Sub, ARef, BRef, Context);
306 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
307 const MCSymbol *Label, int PointerSize) {
308 // emit the sequence to set the address
309 OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
310 OS.EmitULEB128IntValue(PointerSize + 1);
311 OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
312 OS.EmitSymbolValue(Label, PointerSize);
314 // emit the sequence for the LineDelta (from 1) and a zero address delta.
315 MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
318 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
319 const MCSymbol *LastLabel,
320 const MCSymbol *Label,
321 unsigned PointerSize) {
323 emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
326 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
328 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
329 MCDwarfLineAddr::Emit(this, LineDelta, Res);
332 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
335 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
336 const MCSymbol *Label) {
337 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
339 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
340 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
343 insert(new MCDwarfCallFrameFragment(*AddrDelta));
346 void MCObjectStreamer::EmitBytes(StringRef Data) {
347 MCLineEntry::Make(this, getCurrentSection().first);
348 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
351 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
354 unsigned MaxBytesToEmit) {
355 if (MaxBytesToEmit == 0)
356 MaxBytesToEmit = ByteAlignment;
357 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
359 // Update the maximum alignment on the current section if necessary.
360 if (ByteAlignment > getCurrentSectionData()->getAlignment())
361 getCurrentSectionData()->setAlignment(ByteAlignment);
364 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
365 unsigned MaxBytesToEmit) {
366 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
367 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
370 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
371 unsigned char Value) {
373 if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
374 insert(new MCOrgFragment(*Offset, Value));
378 MCSymbol *CurrentPos = getContext().CreateTempSymbol();
379 EmitLabel(CurrentPos);
380 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
382 MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
383 const MCExpr *Delta =
384 MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
386 if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
388 EmitFill(Res, Value);
392 // Associate GPRel32 fixup with data and resize data area
393 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
394 MCDataFragment *DF = getOrCreateDataFragment();
396 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
398 DF->getContents().resize(DF->getContents().size() + 4, 0);
401 // Associate GPRel32 fixup with data and resize data area
402 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
403 MCDataFragment *DF = getOrCreateDataFragment();
405 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
407 DF->getContents().resize(DF->getContents().size() + 8, 0);
410 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
411 // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
412 // problems evaluating expressions across multiple fragments.
413 getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
416 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
417 const MCSection *Sec = getCurrentSection().first;
418 assert(Sec && "need a section");
419 unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
420 insert(new MCFillFragment(0, ItemSize, NumBytes));
423 void MCObjectStreamer::FinishImpl() {
424 // If we are generating dwarf for assembly source files dump out the sections.
425 if (getContext().getGenDwarfForAssembly())
426 MCGenDwarfInfo::Emit(this);
428 // Dump out the dwarf file & directory tables and line tables.
429 MCDwarfLineTable::Emit(this);
431 flushPendingLabels(nullptr);
432 getAssembler().Finish();