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_ostream &OS, MCCodeEmitter *Emitter_)
28 : MCStreamer(Context),
29 Assembler(new MCAssembler(Context, TAB, *Emitter_,
30 *TAB.createObjectWriter(OS), OS)),
31 CurSectionData(nullptr), EmitEHFrame(true), EmitDebugFrame(false) {}
33 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
34 raw_ostream &OS, MCCodeEmitter *Emitter_,
35 MCAssembler *Assembler)
36 : MCStreamer(Context), Assembler(Assembler), CurSectionData(nullptr),
37 EmitEHFrame(true), EmitDebugFrame(false) {}
39 MCObjectStreamer::~MCObjectStreamer() {
40 delete &Assembler->getBackend();
41 delete &Assembler->getEmitter();
42 delete &Assembler->getWriter();
46 void MCObjectStreamer::flushPendingLabels(MCFragment *F) {
47 if (PendingLabels.size()) {
49 F = new MCDataFragment();
50 CurSectionData->getFragmentList().insert(CurInsertionPoint, F);
51 F->setParent(CurSectionData);
53 for (MCSymbolData *SD : PendingLabels) {
57 PendingLabels.clear();
61 void MCObjectStreamer::reset() {
64 CurSectionData = nullptr;
65 CurInsertionPoint = MCSectionData::iterator();
67 EmitDebugFrame = false;
68 PendingLabels.clear();
72 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
73 if (!getNumFrameInfos())
77 MCDwarfFrameEmitter::Emit(*this, MAB, true);
80 MCDwarfFrameEmitter::Emit(*this, MAB, false);
83 MCFragment *MCObjectStreamer::getCurrentFragment() const {
84 assert(getCurrentSectionData() && "No current section!");
86 if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
87 return std::prev(CurInsertionPoint);
92 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
93 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
94 // When bundling is enabled, we don't want to add data to a fragment that
95 // already has instructions (see MCELFStreamer::EmitInstToData for details)
96 if (!F || (Assembler->isBundlingEnabled() && F->hasInstructions())) {
97 F = new MCDataFragment();
103 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
104 Assembler->getOrCreateSymbolData(Sym);
107 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
108 MCStreamer::EmitCFISections(EH, Debug);
110 EmitDebugFrame = Debug;
113 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
115 MCStreamer::EmitValueImpl(Value, Size, Loc);
116 MCDataFragment *DF = getOrCreateDataFragment();
118 MCLineEntry::Make(this, getCurrentSection().first);
120 // Avoid fixups when possible.
122 if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
123 EmitIntValue(AbsValue, Size);
126 DF->getFixups().push_back(
127 MCFixup::Create(DF->getContents().size(), Value,
128 MCFixup::getKindForSize(Size, false), Loc));
129 DF->getContents().resize(DF->getContents().size() + Size, 0);
132 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
133 // We need to create a local symbol to avoid relocations.
134 Frame.Begin = getContext().CreateTempSymbol();
135 EmitLabel(Frame.Begin);
138 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
139 Frame.End = getContext().CreateTempSymbol();
140 EmitLabel(Frame.End);
143 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
144 MCStreamer::EmitLabel(Symbol);
146 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
147 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
149 // If there is a current fragment, mark the symbol as pointing into it.
150 // Otherwise queue the label and set its fragment pointer when we emit the
152 if (auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment())) {
154 SD.setOffset(F->getContents().size());
156 PendingLabels.push_back(&SD);
160 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
162 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
163 EmitULEB128IntValue(IntValue);
166 insert(new MCLEBFragment(*Value, false));
169 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
171 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
172 EmitSLEB128IntValue(IntValue);
175 insert(new MCLEBFragment(*Value, true));
178 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
179 const MCSymbol *Symbol) {
180 report_fatal_error("This file format doesn't support weak aliases.");
183 void MCObjectStreamer::ChangeSection(const MCSection *Section,
184 const MCExpr *Subsection) {
185 changeSectionImpl(Section, Subsection);
188 bool MCObjectStreamer::changeSectionImpl(const MCSection *Section,
189 const MCExpr *Subsection) {
190 assert(Section && "Cannot switch to a null section!");
191 flushPendingLabels(nullptr);
194 CurSectionData = &getAssembler().getOrCreateSectionData(*Section, &Created);
196 int64_t IntSubsection = 0;
198 !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
199 report_fatal_error("Cannot evaluate subsection number");
200 if (IntSubsection < 0 || IntSubsection > 8192)
201 report_fatal_error("Subsection number out of range");
203 CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
207 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
208 getAssembler().getOrCreateSymbolData(*Symbol);
209 MCStreamer::EmitAssignment(Symbol, Value);
212 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
213 const MCSubtargetInfo &STI) {
214 MCStreamer::EmitInstruction(Inst, STI);
216 MCSectionData *SD = getCurrentSectionData();
217 SD->setHasInstructions(true);
219 // Now that a machine instruction has been assembled into this section, make
220 // a line entry for any .loc directive that has been seen.
221 MCLineEntry::Make(this, getCurrentSection().first);
223 // If this instruction doesn't need relaxation, just emit it as data.
224 MCAssembler &Assembler = getAssembler();
225 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
226 EmitInstToData(Inst, STI);
230 // Otherwise, relax and emit it as data if either:
231 // - The RelaxAll flag was passed
232 // - Bundling is enabled and this instruction is inside a bundle-locked
233 // group. We want to emit all such instructions into the same data
235 if (Assembler.getRelaxAll() ||
236 (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
238 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
239 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
240 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
241 EmitInstToData(Relaxed, STI);
245 // Otherwise emit to a separate fragment.
246 EmitInstToFragment(Inst, STI);
249 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
250 const MCSubtargetInfo &STI) {
251 // Always create a new, separate fragment here, because its size can change
252 // during relaxation.
253 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
256 SmallString<128> Code;
257 raw_svector_ostream VecOS(Code);
258 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups(),
261 IF->getContents().append(Code.begin(), Code.end());
265 static const char *const BundlingNotImplementedMsg =
266 "Aligned bundling is not implemented for this object format";
269 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
270 llvm_unreachable(BundlingNotImplementedMsg);
273 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
274 llvm_unreachable(BundlingNotImplementedMsg);
277 void MCObjectStreamer::EmitBundleUnlock() {
278 llvm_unreachable(BundlingNotImplementedMsg);
281 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
282 unsigned Column, unsigned Flags,
284 unsigned Discriminator,
285 StringRef FileName) {
286 // In case we see two .loc directives in a row, make sure the
287 // first one gets a line entry.
288 MCLineEntry::Make(this, getCurrentSection().first);
290 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
291 Isa, Discriminator, FileName);
294 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
296 MCContext &Context = OS.getContext();
297 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
298 const MCExpr *ARef = MCSymbolRefExpr::Create(A, Variant, Context);
299 const MCExpr *BRef = MCSymbolRefExpr::Create(B, Variant, Context);
300 const MCExpr *AddrDelta =
301 MCBinaryExpr::Create(MCBinaryExpr::Sub, ARef, BRef, Context);
305 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
306 const MCSymbol *Label, int PointerSize) {
307 // emit the sequence to set the address
308 OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
309 OS.EmitULEB128IntValue(PointerSize + 1);
310 OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
311 OS.EmitSymbolValue(Label, PointerSize);
313 // emit the sequence for the LineDelta (from 1) and a zero address delta.
314 MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
317 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
318 const MCSymbol *LastLabel,
319 const MCSymbol *Label,
320 unsigned PointerSize) {
322 emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
325 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
327 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
328 MCDwarfLineAddr::Emit(this, LineDelta, Res);
331 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
334 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
335 const MCSymbol *Label) {
336 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
338 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
339 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
342 insert(new MCDwarfCallFrameFragment(*AddrDelta));
345 void MCObjectStreamer::EmitBytes(StringRef Data) {
346 MCLineEntry::Make(this, getCurrentSection().first);
347 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
350 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
353 unsigned MaxBytesToEmit) {
354 if (MaxBytesToEmit == 0)
355 MaxBytesToEmit = ByteAlignment;
356 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
358 // Update the maximum alignment on the current section if necessary.
359 if (ByteAlignment > getCurrentSectionData()->getAlignment())
360 getCurrentSectionData()->setAlignment(ByteAlignment);
363 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
364 unsigned MaxBytesToEmit) {
365 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
366 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
369 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
370 unsigned char Value) {
372 if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
373 insert(new MCOrgFragment(*Offset, Value));
377 MCSymbol *CurrentPos = getContext().CreateTempSymbol();
378 EmitLabel(CurrentPos);
379 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
381 MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
382 const MCExpr *Delta =
383 MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
385 if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
387 EmitFill(Res, Value);
391 // Associate GPRel32 fixup with data and resize data area
392 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
393 MCDataFragment *DF = getOrCreateDataFragment();
395 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
397 DF->getContents().resize(DF->getContents().size() + 4, 0);
400 // Associate GPRel32 fixup with data and resize data area
401 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
402 MCDataFragment *DF = getOrCreateDataFragment();
404 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
406 DF->getContents().resize(DF->getContents().size() + 8, 0);
409 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
410 // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
411 // problems evaluating expressions across multiple fragments.
412 getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
415 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
416 const MCSection *Sec = getCurrentSection().first;
417 assert(Sec && "need a section");
418 unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
419 insert(new MCFillFragment(0, ItemSize, NumBytes));
422 void MCObjectStreamer::FinishImpl() {
423 // If we are generating dwarf for assembly source files dump out the sections.
424 if (getContext().getGenDwarfForAssembly())
425 MCGenDwarfInfo::Emit(this);
427 // Dump out the dwarf file & directory tables and line tables.
428 MCDwarfLineTable::Emit(this);
430 flushPendingLabels(nullptr);
431 getAssembler().Finish();