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"
25 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
26 raw_ostream &OS, MCCodeEmitter *Emitter_)
27 : MCStreamer(Context),
28 Assembler(new MCAssembler(Context, TAB, *Emitter_,
29 *TAB.createObjectWriter(OS), OS)),
30 CurSectionData(nullptr), EmitEHFrame(true), EmitDebugFrame(false) {}
32 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
33 raw_ostream &OS, MCCodeEmitter *Emitter_,
34 MCAssembler *_Assembler)
35 : MCStreamer(Context), Assembler(_Assembler), CurSectionData(nullptr),
36 EmitEHFrame(true), EmitDebugFrame(false) {}
38 MCObjectStreamer::~MCObjectStreamer() {
39 delete &Assembler->getBackend();
40 delete &Assembler->getEmitter();
41 delete &Assembler->getWriter();
45 void MCObjectStreamer::reset() {
48 CurSectionData = nullptr;
49 CurInsertionPoint = MCSectionData::iterator();
51 EmitDebugFrame = false;
55 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
56 if (!getNumFrameInfos())
60 MCDwarfFrameEmitter::Emit(*this, MAB, true);
63 MCDwarfFrameEmitter::Emit(*this, MAB, false);
66 MCFragment *MCObjectStreamer::getCurrentFragment() const {
67 assert(getCurrentSectionData() && "No current section!");
69 if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
70 return std::prev(CurInsertionPoint);
75 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() const {
76 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
77 // When bundling is enabled, we don't want to add data to a fragment that
78 // already has instructions (see MCELFStreamer::EmitInstToData for details)
79 if (!F || (Assembler->isBundlingEnabled() && F->hasInstructions())) {
80 F = new MCDataFragment();
86 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
87 Assembler->getOrCreateSymbolData(Sym);
90 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
91 MCStreamer::EmitCFISections(EH, Debug);
93 EmitDebugFrame = Debug;
96 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
98 MCStreamer::EmitValueImpl(Value, Size, Loc);
99 MCDataFragment *DF = getOrCreateDataFragment();
101 MCLineEntry::Make(this, getCurrentSection().first);
103 // Avoid fixups when possible.
105 if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
106 EmitIntValue(AbsValue, Size);
109 DF->getFixups().push_back(
110 MCFixup::Create(DF->getContents().size(), Value,
111 MCFixup::getKindForSize(Size, false), Loc));
112 DF->getContents().resize(DF->getContents().size() + Size, 0);
115 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
116 // We need to create a local symbol to avoid relocations.
117 Frame.Begin = getContext().CreateTempSymbol();
118 EmitLabel(Frame.Begin);
121 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
122 Frame.End = getContext().CreateTempSymbol();
123 EmitLabel(Frame.End);
126 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
127 MCStreamer::EmitLabel(Symbol);
129 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
131 // FIXME: This is wasteful, we don't necessarily need to create a data
132 // fragment. Instead, we should mark the symbol as pointing into the data
133 // fragment if it exists, otherwise we should just queue the label and set its
134 // fragment pointer when we emit the next fragment.
135 MCDataFragment *F = getOrCreateDataFragment();
136 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
138 SD.setOffset(F->getContents().size());
141 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
143 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
144 EmitULEB128IntValue(IntValue);
147 insert(new MCLEBFragment(*Value, false));
150 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
152 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
153 EmitSLEB128IntValue(IntValue);
156 insert(new MCLEBFragment(*Value, true));
159 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
160 const MCSymbol *Symbol) {
161 report_fatal_error("This file format doesn't support weak aliases.");
164 void MCObjectStreamer::ChangeSection(const MCSection *Section,
165 const MCExpr *Subsection) {
166 assert(Section && "Cannot switch to a null section!");
168 CurSectionData = &getAssembler().getOrCreateSectionData(*Section);
170 int64_t IntSubsection = 0;
172 !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
173 report_fatal_error("Cannot evaluate subsection number");
174 if (IntSubsection < 0 || IntSubsection > 8192)
175 report_fatal_error("Subsection number out of range");
177 CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
180 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
181 getAssembler().getOrCreateSymbolData(*Symbol);
182 MCStreamer::EmitAssignment(Symbol, Value);
185 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
186 const MCSubtargetInfo &STI) {
187 MCStreamer::EmitInstruction(Inst, STI);
189 MCSectionData *SD = getCurrentSectionData();
190 SD->setHasInstructions(true);
192 // Now that a machine instruction has been assembled into this section, make
193 // a line entry for any .loc directive that has been seen.
194 MCLineEntry::Make(this, getCurrentSection().first);
196 // If this instruction doesn't need relaxation, just emit it as data.
197 MCAssembler &Assembler = getAssembler();
198 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
199 EmitInstToData(Inst, STI);
203 // Otherwise, relax and emit it as data if either:
204 // - The RelaxAll flag was passed
205 // - Bundling is enabled and this instruction is inside a bundle-locked
206 // group. We want to emit all such instructions into the same data
208 if (Assembler.getRelaxAll() ||
209 (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
211 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
212 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
213 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
214 EmitInstToData(Relaxed, STI);
218 // Otherwise emit to a separate fragment.
219 EmitInstToFragment(Inst, STI);
222 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
223 const MCSubtargetInfo &STI) {
224 // Always create a new, separate fragment here, because its size can change
225 // during relaxation.
226 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
229 SmallString<128> Code;
230 raw_svector_ostream VecOS(Code);
231 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups(),
234 IF->getContents().append(Code.begin(), Code.end());
238 static const char *const BundlingNotImplementedMsg =
239 "Aligned bundling is not implemented for this object format";
242 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
243 llvm_unreachable(BundlingNotImplementedMsg);
246 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
247 llvm_unreachable(BundlingNotImplementedMsg);
250 void MCObjectStreamer::EmitBundleUnlock() {
251 llvm_unreachable(BundlingNotImplementedMsg);
254 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
255 unsigned Column, unsigned Flags,
257 unsigned Discriminator,
258 StringRef FileName) {
259 // In case we see two .loc directives in a row, make sure the
260 // first one gets a line entry.
261 MCLineEntry::Make(this, getCurrentSection().first);
263 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
264 Isa, Discriminator, FileName);
267 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
269 MCContext &Context = OS.getContext();
270 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
271 const MCExpr *ARef = MCSymbolRefExpr::Create(A, Variant, Context);
272 const MCExpr *BRef = MCSymbolRefExpr::Create(B, Variant, Context);
273 const MCExpr *AddrDelta =
274 MCBinaryExpr::Create(MCBinaryExpr::Sub, ARef, BRef, Context);
278 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
279 const MCSymbol *Label, int PointerSize) {
280 // emit the sequence to set the address
281 OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
282 OS.EmitULEB128IntValue(PointerSize + 1);
283 OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
284 OS.EmitSymbolValue(Label, PointerSize);
286 // emit the sequence for the LineDelta (from 1) and a zero address delta.
287 MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
290 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
291 const MCSymbol *LastLabel,
292 const MCSymbol *Label,
293 unsigned PointerSize) {
295 emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
298 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
300 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
301 MCDwarfLineAddr::Emit(this, LineDelta, Res);
304 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
307 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
308 const MCSymbol *Label) {
309 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
311 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
312 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
315 insert(new MCDwarfCallFrameFragment(*AddrDelta));
318 void MCObjectStreamer::EmitBytes(StringRef Data) {
319 MCLineEntry::Make(this, getCurrentSection().first);
320 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
323 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
326 unsigned MaxBytesToEmit) {
327 if (MaxBytesToEmit == 0)
328 MaxBytesToEmit = ByteAlignment;
329 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
331 // Update the maximum alignment on the current section if necessary.
332 if (ByteAlignment > getCurrentSectionData()->getAlignment())
333 getCurrentSectionData()->setAlignment(ByteAlignment);
336 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
337 unsigned MaxBytesToEmit) {
338 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
339 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
342 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
343 unsigned char Value) {
345 if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
346 insert(new MCOrgFragment(*Offset, Value));
350 MCSymbol *CurrentPos = getContext().CreateTempSymbol();
351 EmitLabel(CurrentPos);
352 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
354 MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
355 const MCExpr *Delta =
356 MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
358 if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
360 EmitFill(Res, Value);
364 // Associate GPRel32 fixup with data and resize data area
365 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
366 MCDataFragment *DF = getOrCreateDataFragment();
368 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
370 DF->getContents().resize(DF->getContents().size() + 4, 0);
373 // Associate GPRel32 fixup with data and resize data area
374 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
375 MCDataFragment *DF = getOrCreateDataFragment();
377 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
379 DF->getContents().resize(DF->getContents().size() + 8, 0);
382 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
383 // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
384 // problems evaluating expressions across multiple fragments.
385 getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
388 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
389 unsigned ItemSize = getCurrentSection().first->isVirtualSection() ? 0 : 1;
390 insert(new MCFillFragment(0, ItemSize, NumBytes));
393 void MCObjectStreamer::FinishImpl() {
394 // If we are generating dwarf for assembly source files dump out the sections.
395 if (getContext().getGenDwarfForAssembly())
396 MCGenDwarfInfo::Emit(this);
398 // Dump out the dwarf file & directory tables and line tables.
399 MCDwarfLineTable::Emit(this);
401 getAssembler().Finish();