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() {
34 delete &Assembler->getBackend();
35 delete &Assembler->getEmitter();
36 delete &Assembler->getWriter();
40 void MCObjectStreamer::flushPendingLabels(MCFragment *F) {
41 if (PendingLabels.size()) {
43 F = new MCDataFragment();
44 CurSectionData->getFragmentList().insert(CurInsertionPoint, F);
45 F->setParent(CurSectionData);
47 for (MCSymbolData *SD : PendingLabels) {
51 PendingLabels.clear();
55 void MCObjectStreamer::reset() {
58 CurSectionData = nullptr;
59 CurInsertionPoint = MCSectionData::iterator();
61 EmitDebugFrame = false;
62 PendingLabels.clear();
66 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
67 if (!getNumFrameInfos())
71 MCDwarfFrameEmitter::Emit(*this, MAB, true);
74 MCDwarfFrameEmitter::Emit(*this, MAB, false);
77 MCFragment *MCObjectStreamer::getCurrentFragment() const {
78 assert(getCurrentSectionData() && "No current section!");
80 if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
81 return std::prev(CurInsertionPoint);
86 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
87 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
88 // When bundling is enabled, we don't want to add data to a fragment that
89 // already has instructions (see MCELFStreamer::EmitInstToData for details)
90 if (!F || (Assembler->isBundlingEnabled() && F->hasInstructions())) {
91 F = new MCDataFragment();
97 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
98 Assembler->getOrCreateSymbolData(Sym);
101 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
102 MCStreamer::EmitCFISections(EH, Debug);
104 EmitDebugFrame = Debug;
107 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
109 MCStreamer::EmitValueImpl(Value, Size, Loc);
110 MCDataFragment *DF = getOrCreateDataFragment();
112 MCLineEntry::Make(this, getCurrentSection().first);
114 // Avoid fixups when possible.
116 if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
117 EmitIntValue(AbsValue, Size);
120 DF->getFixups().push_back(
121 MCFixup::Create(DF->getContents().size(), Value,
122 MCFixup::getKindForSize(Size, false), Loc));
123 DF->getContents().resize(DF->getContents().size() + Size, 0);
126 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
127 // We need to create a local symbol to avoid relocations.
128 Frame.Begin = getContext().CreateTempSymbol();
129 EmitLabel(Frame.Begin);
132 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
133 Frame.End = getContext().CreateTempSymbol();
134 EmitLabel(Frame.End);
137 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
138 MCStreamer::EmitLabel(Symbol);
140 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
141 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
143 // If there is a current fragment, mark the symbol as pointing into it.
144 // Otherwise queue the label and set its fragment pointer when we emit the
146 if (auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment())) {
148 SD.setOffset(F->getContents().size());
150 PendingLabels.push_back(&SD);
154 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
156 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
157 EmitULEB128IntValue(IntValue);
160 insert(new MCLEBFragment(*Value, false));
163 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
165 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
166 EmitSLEB128IntValue(IntValue);
169 insert(new MCLEBFragment(*Value, true));
172 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
173 const MCSymbol *Symbol) {
174 report_fatal_error("This file format doesn't support weak aliases.");
177 void MCObjectStreamer::ChangeSection(const MCSection *Section,
178 const MCExpr *Subsection) {
179 changeSectionImpl(Section, Subsection);
182 bool MCObjectStreamer::changeSectionImpl(const MCSection *Section,
183 const MCExpr *Subsection) {
184 assert(Section && "Cannot switch to a null section!");
185 flushPendingLabels(nullptr);
188 CurSectionData = &getAssembler().getOrCreateSectionData(*Section, &Created);
190 int64_t IntSubsection = 0;
192 !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
193 report_fatal_error("Cannot evaluate subsection number");
194 if (IntSubsection < 0 || IntSubsection > 8192)
195 report_fatal_error("Subsection number out of range");
197 CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
201 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
202 getAssembler().getOrCreateSymbolData(*Symbol);
203 MCStreamer::EmitAssignment(Symbol, Value);
206 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
207 const MCSubtargetInfo &STI) {
208 MCStreamer::EmitInstruction(Inst, STI);
210 MCSectionData *SD = getCurrentSectionData();
211 SD->setHasInstructions(true);
213 // Now that a machine instruction has been assembled into this section, make
214 // a line entry for any .loc directive that has been seen.
215 MCLineEntry::Make(this, getCurrentSection().first);
217 // If this instruction doesn't need relaxation, just emit it as data.
218 MCAssembler &Assembler = getAssembler();
219 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
220 EmitInstToData(Inst, STI);
224 // Otherwise, relax and emit it as data if either:
225 // - The RelaxAll flag was passed
226 // - Bundling is enabled and this instruction is inside a bundle-locked
227 // group. We want to emit all such instructions into the same data
229 if (Assembler.getRelaxAll() ||
230 (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
232 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
233 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
234 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
235 EmitInstToData(Relaxed, STI);
239 // Otherwise emit to a separate fragment.
240 EmitInstToFragment(Inst, STI);
243 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
244 const MCSubtargetInfo &STI) {
245 // Always create a new, separate fragment here, because its size can change
246 // during relaxation.
247 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
250 SmallString<128> Code;
251 raw_svector_ostream VecOS(Code);
252 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups(),
255 IF->getContents().append(Code.begin(), Code.end());
259 static const char *const BundlingNotImplementedMsg =
260 "Aligned bundling is not implemented for this object format";
263 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
264 llvm_unreachable(BundlingNotImplementedMsg);
267 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
268 llvm_unreachable(BundlingNotImplementedMsg);
271 void MCObjectStreamer::EmitBundleUnlock() {
272 llvm_unreachable(BundlingNotImplementedMsg);
275 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
276 unsigned Column, unsigned Flags,
278 unsigned Discriminator,
279 StringRef FileName) {
280 // In case we see two .loc directives in a row, make sure the
281 // first one gets a line entry.
282 MCLineEntry::Make(this, getCurrentSection().first);
284 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
285 Isa, Discriminator, FileName);
288 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
290 MCContext &Context = OS.getContext();
291 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
292 const MCExpr *ARef = MCSymbolRefExpr::Create(A, Variant, Context);
293 const MCExpr *BRef = MCSymbolRefExpr::Create(B, Variant, Context);
294 const MCExpr *AddrDelta =
295 MCBinaryExpr::Create(MCBinaryExpr::Sub, ARef, BRef, Context);
299 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
300 const MCSymbol *Label, int PointerSize) {
301 // emit the sequence to set the address
302 OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
303 OS.EmitULEB128IntValue(PointerSize + 1);
304 OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
305 OS.EmitSymbolValue(Label, PointerSize);
307 // emit the sequence for the LineDelta (from 1) and a zero address delta.
308 MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
311 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
312 const MCSymbol *LastLabel,
313 const MCSymbol *Label,
314 unsigned PointerSize) {
316 emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
319 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
321 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
322 MCDwarfLineAddr::Emit(this, LineDelta, Res);
325 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
328 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
329 const MCSymbol *Label) {
330 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
332 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
333 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
336 insert(new MCDwarfCallFrameFragment(*AddrDelta));
339 void MCObjectStreamer::EmitBytes(StringRef Data) {
340 MCLineEntry::Make(this, getCurrentSection().first);
341 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
344 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
347 unsigned MaxBytesToEmit) {
348 if (MaxBytesToEmit == 0)
349 MaxBytesToEmit = ByteAlignment;
350 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
352 // Update the maximum alignment on the current section if necessary.
353 if (ByteAlignment > getCurrentSectionData()->getAlignment())
354 getCurrentSectionData()->setAlignment(ByteAlignment);
357 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
358 unsigned MaxBytesToEmit) {
359 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
360 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
363 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
364 unsigned char Value) {
366 if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
367 insert(new MCOrgFragment(*Offset, Value));
371 MCSymbol *CurrentPos = getContext().CreateTempSymbol();
372 EmitLabel(CurrentPos);
373 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
375 MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
376 const MCExpr *Delta =
377 MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
379 if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
381 EmitFill(Res, Value);
385 // Associate GPRel32 fixup with data and resize data area
386 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
387 MCDataFragment *DF = getOrCreateDataFragment();
389 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
391 DF->getContents().resize(DF->getContents().size() + 4, 0);
394 // Associate GPRel32 fixup with data and resize data area
395 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
396 MCDataFragment *DF = getOrCreateDataFragment();
398 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
400 DF->getContents().resize(DF->getContents().size() + 8, 0);
403 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
404 // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
405 // problems evaluating expressions across multiple fragments.
406 getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
409 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
410 const MCSection *Sec = getCurrentSection().first;
411 assert(Sec && "need a section");
412 unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
413 insert(new MCFillFragment(0, ItemSize, NumBytes));
416 void MCObjectStreamer::FinishImpl() {
417 // If we are generating dwarf for assembly source files dump out the sections.
418 if (getContext().getGenDwarfForAssembly())
419 MCGenDwarfInfo::Emit(this);
421 // Dump out the dwarf file & directory tables and line tables.
422 MCDwarfLineTable::Emit(this);
424 flushPendingLabels(nullptr);
425 getAssembler().Finish();