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/MCSymbol.h"
21 #include "llvm/Support/ErrorHandling.h"
24 MCObjectStreamer::MCObjectStreamer(StreamerKind Kind, MCContext &Context,
25 MCAsmBackend &TAB, raw_ostream &OS,
26 MCCodeEmitter *Emitter_)
27 : MCStreamer(Kind, Context),
28 Assembler(new MCAssembler(Context, TAB, *Emitter_,
29 *TAB.createObjectWriter(OS), OS)),
32 MCObjectStreamer::MCObjectStreamer(StreamerKind Kind, MCContext &Context,
33 MCAsmBackend &TAB, raw_ostream &OS,
34 MCCodeEmitter *Emitter_,
35 MCAssembler *_Assembler)
36 : MCStreamer(Kind, Context), Assembler(_Assembler), CurSectionData(0) {}
38 MCObjectStreamer::~MCObjectStreamer() {
39 delete &Assembler->getBackend();
40 delete &Assembler->getEmitter();
41 delete &Assembler->getWriter();
45 void MCObjectStreamer::reset() {
49 CurInsertionPoint = MCSectionData::iterator();
53 MCFragment *MCObjectStreamer::getCurrentFragment() const {
54 assert(getCurrentSectionData() && "No current section!");
56 if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
57 return prior(CurInsertionPoint);
62 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() const {
63 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
64 // When bundling is enabled, we don't want to add data to a fragment that
65 // already has instructions (see MCELFStreamer::EmitInstToData for details)
66 if (!F || (Assembler->isBundlingEnabled() && F->hasInstructions())) {
67 F = new MCDataFragment();
73 const MCExpr *MCObjectStreamer::AddValueSymbols(const MCExpr *Value) {
74 switch (Value->getKind()) {
76 cast<MCTargetExpr>(Value)->AddValueSymbols(Assembler);
79 case MCExpr::Constant:
82 case MCExpr::Binary: {
83 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
84 AddValueSymbols(BE->getLHS());
85 AddValueSymbols(BE->getRHS());
89 case MCExpr::SymbolRef:
90 Assembler->getOrCreateSymbolData(cast<MCSymbolRefExpr>(Value)->getSymbol());
94 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
101 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
102 unsigned AddrSpace) {
103 assert(AddrSpace == 0 && "Address space must be 0!");
104 MCDataFragment *DF = getOrCreateDataFragment();
106 // Avoid fixups when possible.
108 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue, getAssembler())) {
109 EmitIntValue(AbsValue, Size, AddrSpace);
112 DF->getFixups().push_back(
113 MCFixup::Create(DF->getContents().size(), Value,
114 MCFixup::getKindForSize(Size, false)));
115 DF->getContents().resize(DF->getContents().size() + Size, 0);
118 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
119 RecordProcStart(Frame);
122 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
123 RecordProcEnd(Frame);
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::EmitDebugLabel(MCSymbol *Symbol) {
145 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
147 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
148 EmitULEB128IntValue(IntValue);
151 Value = ForceExpAbs(Value);
152 insert(new MCLEBFragment(*Value, false));
155 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
157 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
158 EmitSLEB128IntValue(IntValue);
161 Value = ForceExpAbs(Value);
162 insert(new MCLEBFragment(*Value, true));
165 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
166 const MCSymbol *Symbol) {
167 report_fatal_error("This file format doesn't support weak aliases.");
170 void MCObjectStreamer::ChangeSection(const MCSection *Section,
171 const MCExpr *Subsection) {
172 assert(Section && "Cannot switch to a null section!");
174 CurSectionData = &getAssembler().getOrCreateSectionData(*Section);
176 int64_t IntSubsection = 0;
178 !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
179 report_fatal_error("Cannot evaluate subsection number");
180 if (IntSubsection < 0 || IntSubsection > 8192)
181 report_fatal_error("Subsection number out of range");
183 CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
186 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
187 getAssembler().getOrCreateSymbolData(*Symbol);
188 Symbol->setVariableValue(AddValueSymbols(Value));
191 void MCObjectStreamer::EmitInstruction(const MCInst &Inst) {
193 for (unsigned i = Inst.getNumOperands(); i--; )
194 if (Inst.getOperand(i).isExpr())
195 AddValueSymbols(Inst.getOperand(i).getExpr());
197 MCSectionData *SD = getCurrentSectionData();
198 SD->setHasInstructions(true);
200 // Now that a machine instruction has been assembled into this section, make
201 // a line entry for any .loc directive that has been seen.
202 MCLineEntry::Make(this, getCurrentSection().first);
204 // If this instruction doesn't need relaxation, just emit it as data.
205 MCAssembler &Assembler = getAssembler();
206 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
207 EmitInstToData(Inst);
211 // Otherwise, relax and emit it as data if either:
212 // - The RelaxAll flag was passed
213 // - Bundling is enabled and this instruction is inside a bundle-locked
214 // group. We want to emit all such instructions into the same data
216 if (Assembler.getRelaxAll() ||
217 (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
219 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
220 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
221 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
222 EmitInstToData(Relaxed);
226 // Otherwise emit to a separate fragment.
227 EmitInstToFragment(Inst);
230 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst) {
231 // Always create a new, separate fragment here, because its size can change
232 // during relaxation.
233 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst);
236 SmallString<128> Code;
237 raw_svector_ostream VecOS(Code);
238 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups());
240 IF->getContents().append(Code.begin(), Code.end());
244 static const char *BundlingNotImplementedMsg =
245 "Aligned bundling is not implemented for this object format";
248 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
249 llvm_unreachable(BundlingNotImplementedMsg);
252 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
253 llvm_unreachable(BundlingNotImplementedMsg);
256 void MCObjectStreamer::EmitBundleUnlock() {
257 llvm_unreachable(BundlingNotImplementedMsg);
260 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
261 const MCSymbol *LastLabel,
262 const MCSymbol *Label,
263 unsigned PointerSize) {
265 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
268 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
270 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
271 MCDwarfLineAddr::Emit(this, LineDelta, Res);
274 AddrDelta = ForceExpAbs(AddrDelta);
275 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
278 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
279 const MCSymbol *Label) {
280 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
282 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
283 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
286 AddrDelta = ForceExpAbs(AddrDelta);
287 insert(new MCDwarfCallFrameFragment(*AddrDelta));
290 void MCObjectStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
291 assert(AddrSpace == 0 && "Address space must be 0!");
292 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
295 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
298 unsigned MaxBytesToEmit) {
299 if (MaxBytesToEmit == 0)
300 MaxBytesToEmit = ByteAlignment;
301 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
303 // Update the maximum alignment on the current section if necessary.
304 if (ByteAlignment > getCurrentSectionData()->getAlignment())
305 getCurrentSectionData()->setAlignment(ByteAlignment);
308 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
309 unsigned MaxBytesToEmit) {
310 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
311 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
314 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
315 unsigned char Value) {
317 if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
318 insert(new MCOrgFragment(*Offset, Value));
322 MCSymbol *CurrentPos = getContext().CreateTempSymbol();
323 EmitLabel(CurrentPos);
324 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
326 MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
327 const MCExpr *Delta =
328 MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
330 if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
332 EmitFill(Res, Value);
336 // Associate GPRel32 fixup with data and resize data area
337 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
338 MCDataFragment *DF = getOrCreateDataFragment();
340 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
342 DF->getContents().resize(DF->getContents().size() + 4, 0);
345 // Associate GPRel32 fixup with data and resize data area
346 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
347 MCDataFragment *DF = getOrCreateDataFragment();
349 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
351 DF->getContents().resize(DF->getContents().size() + 8, 0);
354 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
355 unsigned AddrSpace) {
356 assert(AddrSpace == 0 && "Address space must be 0!");
357 // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
358 // problems evaluating expressions across multiple fragments.
359 getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
362 void MCObjectStreamer::FinishImpl() {
363 // Dump out the dwarf file & directory tables and line tables.
364 const MCSymbol *LineSectionSymbol = NULL;
365 if (getContext().hasDwarfFiles())
366 LineSectionSymbol = MCDwarfFileTable::Emit(this);
368 // If we are generating dwarf for assembly source files dump out the sections.
369 if (getContext().getGenDwarfForAssembly())
370 MCGenDwarfInfo::Emit(this, LineSectionSymbol);
372 getAssembler().Finish();